@authrim/core 0.1.8 → 0.1.10
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.cjs +2 -2
- package/dist/index.d.cts +57 -1
- package/dist/index.d.ts +57 -1
- package/dist/index.js +2 -2
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
'use strict';function $(s){return {...s,scopes:s.scopes??["openid","profile"],flowEngine:s.flowEngine??false,discoveryCacheTtlMs:s.discoveryCacheTtlMs??3600*1e3,refreshSkewSeconds:s.refreshSkewSeconds??30,stateTtlSeconds:s.stateTtlSeconds??600,hashOptions:{hashLength:s.hashOptions?.hashLength??16}}}var a=class s extends Error{constructor(e,t,r){super(t),this.name="AuthrimError",this.code=e,this.details=r?.details,this.errorUri=r?.errorUri,this.cause=r?.cause;}static fromOAuthError(e){let r=["invalid_request","unauthorized_client","access_denied","unsupported_response_type","invalid_scope","server_error","temporarily_unavailable","invalid_grant","invalid_token"].includes(e.error)?e.error:"invalid_request";return new s(r,e.error_description??e.error,{errorUri:e.error_uri,details:{originalError:e.error}})}isRetryable(){return this.code==="network_error"||this.code==="timeout_error"}get meta(){return ce(this.code)}},ke={invalid_request:{transient:false,retryable:false,userAction:"contact_support",severity:"error"},unauthorized_client:{transient:false,retryable:false,userAction:"contact_support",severity:"fatal"},access_denied:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},unsupported_response_type:{transient:false,retryable:false,userAction:"contact_support",severity:"fatal"},invalid_scope:{transient:false,retryable:false,userAction:"contact_support",severity:"error"},server_error:{transient:true,retryable:true,retryAfterMs:5e3,maxRetries:3,userAction:"retry",severity:"error"},temporarily_unavailable:{transient:true,retryable:true,retryAfterMs:1e4,maxRetries:3,userAction:"retry",severity:"warning"},invalid_grant:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},invalid_token:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},invalid_state:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},expired_state:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},invalid_nonce:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},nonce_mismatch:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},missing_nonce:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},missing_id_token:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},session_expired:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},session_check_failed:{transient:true,retryable:true,retryAfterMs:3e3,maxRetries:2,userAction:"retry",severity:"warning"},network_error:{transient:true,retryable:true,retryAfterMs:2e3,maxRetries:3,userAction:"check_network",severity:"error"},timeout_error:{transient:true,retryable:true,retryAfterMs:3e3,maxRetries:3,userAction:"retry",severity:"warning"},discovery_error:{transient:true,retryable:true,retryAfterMs:5e3,maxRetries:2,userAction:"retry",severity:"error"},discovery_mismatch:{transient:false,retryable:false,userAction:"contact_support",severity:"fatal"},configuration_error:{transient:false,retryable:false,userAction:"contact_support",severity:"fatal"},storage_error:{transient:true,retryable:true,retryAfterMs:1e3,maxRetries:2,userAction:"retry",severity:"error"},flow_engine_error:{transient:false,retryable:false,userAction:"contact_support",severity:"error"},no_tokens:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},token_expired:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},token_error:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},refresh_error:{transient:false,retryable:false,retryAfterMs:0,maxRetries:0,userAction:"reauthenticate",severity:"error"},token_exchange_error:{transient:false,retryable:false,retryAfterMs:0,maxRetries:0,userAction:"reauthenticate",severity:"error"},oauth_error:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},missing_code:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},missing_state:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},not_initialized:{transient:false,retryable:false,userAction:"none",severity:"fatal"},no_discovery:{transient:true,retryable:true,retryAfterMs:3e3,maxRetries:2,userAction:"retry",severity:"error"},no_userinfo_endpoint:{transient:false,retryable:false,userAction:"none",severity:"warning"},userinfo_error:{transient:true,retryable:true,retryAfterMs:2e3,maxRetries:2,userAction:"retry",severity:"error"},introspection_error:{transient:true,retryable:true,retryAfterMs:2e3,maxRetries:2,userAction:"retry",severity:"error"},revocation_error:{transient:true,retryable:true,retryAfterMs:2e3,maxRetries:2,userAction:"retry",severity:"error"},no_introspection_endpoint:{transient:false,retryable:false,userAction:"none",severity:"warning"},no_revocation_endpoint:{transient:false,retryable:false,userAction:"none",severity:"warning"},login_required:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},interaction_required:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},consent_required:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},account_selection_required:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},dom_not_ready:{transient:true,retryable:true,retryAfterMs:100,maxRetries:3,userAction:"retry",severity:"error"},state_mismatch:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},popup_blocked:{transient:false,retryable:false,userAction:"none",severity:"warning"},popup_closed:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},invalid_response:{transient:false,retryable:false,userAction:"contact_support",severity:"error"},invalid_callback:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},passkey_not_found:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},passkey_verification_failed:{transient:false,retryable:true,retryAfterMs:1e3,maxRetries:3,userAction:"retry",severity:"error"},passkey_not_supported:{transient:false,retryable:false,userAction:"none",severity:"warning"},passkey_cancelled:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},passkey_invalid_credential:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},email_code_invalid:{transient:false,retryable:true,retryAfterMs:0,maxRetries:5,userAction:"retry",severity:"warning"},email_code_expired:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},email_code_too_many_attempts:{transient:false,retryable:false,retryAfterMs:3e5,userAction:"retry",severity:"error"},challenge_expired:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},challenge_invalid:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},auth_code_invalid:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},auth_code_expired:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},pkce_mismatch:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},origin_not_allowed:{transient:false,retryable:false,userAction:"contact_support",severity:"fatal"},mfa_required:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},email_verification_required:{transient:false,retryable:false,userAction:"none",severity:"warning"},consent_required_direct:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},rate_limited:{transient:true,retryable:true,retryAfterMs:6e4,maxRetries:3,userAction:"retry",severity:"warning"},event_handler_error:{transient:false,retryable:false,userAction:"none",severity:"warning"},par_required:{transient:false,retryable:false,userAction:"none",severity:"fatal"},no_par_endpoint:{transient:false,retryable:false,userAction:"contact_support",severity:"fatal"},par_error:{transient:true,retryable:true,retryAfterMs:2e3,maxRetries:2,userAction:"retry",severity:"error"},par_request_uri_expired:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},no_device_authorization_endpoint:{transient:false,retryable:false,userAction:"contact_support",severity:"fatal"},device_authorization_error:{transient:true,retryable:true,retryAfterMs:2e3,maxRetries:2,userAction:"retry",severity:"error"},device_authorization_pending:{transient:true,retryable:true,retryAfterMs:5e3,maxRetries:60,userAction:"none",severity:"warning"},device_slow_down:{transient:true,retryable:true,retryAfterMs:1e4,maxRetries:60,userAction:"none",severity:"warning"},device_authorization_expired:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},device_access_denied:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},client_credentials_error:{transient:true,retryable:true,retryAfterMs:2e3,maxRetries:2,userAction:"retry",severity:"error"},invalid_client_authentication:{transient:false,retryable:false,userAction:"contact_support",severity:"fatal"},insecure_client_auth:{transient:false,retryable:false,userAction:"none",severity:"fatal"},dpop_key_generation_error:{transient:true,retryable:true,retryAfterMs:1e3,maxRetries:2,userAction:"retry",severity:"error"},dpop_proof_generation_error:{transient:false,retryable:false,userAction:"none",severity:"error"},dpop_nonce_required:{transient:true,retryable:true,retryAfterMs:0,maxRetries:1,userAction:"none",severity:"warning"},jar_signing_error:{transient:false,retryable:false,userAction:"contact_support",severity:"error"},jar_required:{transient:false,retryable:false,userAction:"none",severity:"fatal"},jarm_validation_error:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},jarm_signature_invalid:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},operation_cancelled:{transient:false,retryable:true,retryAfterMs:0,maxRetries:1,userAction:"retry",severity:"warning"},invalid_return_to:{transient:false,retryable:false,userAction:"none",severity:"error"}};function ce(s){return ke[s]}function W(s){let e=s.meta;if(!e.retryable&&e.userAction==="contact_support")return {severity:"fatal",remediation:"contact_support"};if(e.severity==="fatal")return {severity:"fatal",remediation:we(e.userAction)};let t="none";return e.retryable?t="retry":e.userAction==="reauthenticate"?t="reauthenticate":s.code==="popup_blocked"?t="switch_flow":e.userAction==="contact_support"&&(t="contact_support"),{severity:"recoverable",remediation:t}}function we(s){switch(s){case "retry":case "check_network":return "retry";case "reauthenticate":return "reauthenticate";case "contact_support":return "contact_support";default:return "none"}}function w(s){let e=W(s);return e.severity==="recoverable"&&e.remediation==="retry"}function A(s,e,t){let{severity:r,remediation:n}=W(e),i=Date.now(),o=t.source??"core",c={error:e,severity:r,remediation:n,context:t.context,timestamp:i,source:o,operationId:t.operationId};s.emit("error",c),r==="recoverable"?s.emit("error:recoverable",{...c,severity:"recoverable"}):s.emit("error:fatal",{...c,severity:"fatal"});}function T(s){return s.replace(/\/+$/,"")}var N=class N{constructor(e){this.cache=new Map;this.http=e.http,this.cacheTtlMs=e.cacheTtlMs??N.DEFAULT_CACHE_TTL_MS;}async discover(e){let t=T(e),r=this.cache.get(t);if(r&&!this.isExpired(r))return r.doc;let n=`${t}/.well-known/openid-configuration`,i;try{let c=await this.http.fetch(n);if(!c.ok)throw new a("discovery_error",`Discovery request failed: ${c.status}`,{details:{status:c.status,statusText:c.statusText}});i=c.data;}catch(c){throw c instanceof a?c:new a("discovery_error","Failed to fetch discovery document",{cause:c instanceof Error?c:void 0,details:{url:n}})}let o=T(i.issuer);if(o!==t)throw new a("discovery_mismatch",`Issuer mismatch in discovery document: expected "${t}", got "${o}"`,{details:{expected:t,actual:o}});return this.cache.set(t,{doc:i,fetchedAt:Date.now()}),i}isExpired(e){return Date.now()-e.fetchedAt>this.cacheTtlMs}clearCache(){this.cache.clear();}clearIssuer(e){this.cache.delete(T(e));}};N.DEFAULT_CACHE_TTL_MS=3600*1e3;var x=N;var b=class{constructor(){this.listeners=new Map;}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>{this.off(e,t);}}once(e,t){let r=(n=>{this.off(e,r),t(n);});return this.on(e,r)}off(e,t){let r=this.listeners.get(e);r&&(r.delete(t),r.size===0&&this.listeners.delete(e));}emit(e,t){let r=this.listeners.get(e);if(r)for(let n of r)try{n(t);}catch(i){if(e!=="error"){let o=i instanceof a?i:new a("event_handler_error","Event handler threw an error",{cause:i instanceof Error?i:void 0});this.emit("error",{error:o,context:`Error in event handler for '${e}'`});}}}removeAllListeners(e){e?this.listeners.delete(e):this.listeners.clear();}listenerCount(e){return this.listeners.get(e)?.size??0}};var P=class{constructor(e){this.crypto=e;}async generatePKCE(){let e=await this.crypto.generateCodeVerifier(),t=await this.crypto.generateCodeChallenge(e);return {codeVerifier:e,codeChallenge:t,codeChallengeMethod:"S256"}}async generateCodeVerifier(){return this.crypto.generateCodeVerifier()}async generateCodeChallenge(e){return this.crypto.generateCodeChallenge(e)}};function f(s){let e="",t=s.length;for(let r=0;r<t;r+=3){let n=s[r],i=r+1<t?s[r+1]:0,o=r+2<t?s[r+2]:0,c=n<<16|i<<8|o;e+=E[c>>18&63],e+=E[c>>12&63],e+=r+1<t?E[c>>6&63]:"",e+=r+2<t?E[c&63]:"";}return e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function le(s){if(!/^[A-Za-z0-9_-]*$/.test(s))throw new Error("Invalid base64url string: contains invalid characters");let e=s.replace(/-/g,"+").replace(/_/g,"/");for(;e.length%4;)e+="=";let t=e.length,r=e.endsWith("==")?2:e.endsWith("=")?1:0,n=t*3/4-r,i=new Uint8Array(n),o=0;for(let c=0;c<t;c+=4){let l=S[e.charCodeAt(c)],u=S[e.charCodeAt(c+1)],p=S[e.charCodeAt(c+2)],d=S[e.charCodeAt(c+3)],h=l<<18|u<<12|p<<6|d;o<n&&(i[o++]=h>>16&255),o<n&&(i[o++]=h>>8&255),o<n&&(i[o++]=h&255);}return i}function F(s){let e=new TextEncoder;return f(e.encode(s))}function J(s){return new TextDecoder().decode(le(s))}var E="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",S=new Uint8Array(256);for(let s=0;s<E.length;s++)S[E.charCodeAt(s)]=s;var m={authState:(s,e,t)=>`authrim:${s}:${e}:auth:${t}`,tokens:(s,e)=>`authrim:${s}:${e}:tokens`,idToken:(s,e)=>`authrim:${s}:${e}:id_token`,authStatePrefix:(s,e)=>`authrim:${s}:${e}:auth:`},g=class g{constructor(e,t,r,n){this.crypto=e;this.storage=t;this.issuerHash=r;this.clientIdHash=n;this.cleanupInterval=null;}async generateAuthState(e){let t=e.ttlSeconds??g.DEFAULT_TTL_SECONDS,r;e.returnTo&&(r=this.validateReturnTo(e.returnTo,e.returnToOptions??{policy:"relative_only"}));let n=await this.crypto.randomBytes(g.ENTROPY_BYTES),i=await this.crypto.randomBytes(g.ENTROPY_BYTES),o=await this.crypto.randomBytes(g.OPERATION_ID_BYTES),c=f(n),l=f(i),u=f(o),p=Date.now(),d={state:c,nonce:l,codeVerifier:e.codeVerifier,redirectUri:e.redirectUri,scope:e.scope,createdAt:p,expiresAt:p+t*1e3,returnTo:r,operationId:u},h=m.authState(this.issuerHash,this.clientIdHash,c);return await this.storage.set(h,JSON.stringify(d)),d}validateReturnTo(e,t){switch(t.policy){case "relative_only":if(e.startsWith("/")&&!e.startsWith("//")&&!e.includes(":"))return e;throw new a("invalid_return_to","returnTo must be a relative path (e.g., /dashboard)");case "same_origin":try{let r=typeof globalThis<"u"?globalThis.window:void 0,n=t.currentOrigin??r?.location?.origin;if(!n)throw new a("invalid_return_to","currentOrigin is required for same_origin policy in non-browser environments");if(e.startsWith("/")&&!e.startsWith("//")||new URL(e).origin===n)return e}catch(r){if(r instanceof a)throw r}throw new a("invalid_return_to","returnTo must be same origin or a relative path");case "allowlist":if(!t.allowedOrigins||t.allowedOrigins.length===0)throw new a("invalid_return_to","allowedOrigins is required when using allowlist policy");if(e.startsWith("/")&&!e.startsWith("//"))return e;try{let r=new URL(e);if(t.allowedOrigins.includes(r.origin))return e}catch{}throw new a("invalid_return_to",`returnTo origin not in allowlist: ${t.allowedOrigins.join(", ")}`);default:throw new a("invalid_return_to",`Unknown returnTo policy: ${t.policy}`)}}async validateAndConsumeState(e){let t=m.authState(this.issuerHash,this.clientIdHash,e);try{let r=await this.storage.get(t);if(!r)throw new a("invalid_state","State not found or already used");let n;try{n=JSON.parse(r);}catch{throw new a("invalid_state","Malformed state data")}if(Date.now()>n.expiresAt)throw new a("expired_state","State has expired");return n}finally{await this.storage.remove(t);}}async cleanupExpiredStates(){if(!this.storage.getAll)return;let e=m.authStatePrefix(this.issuerHash,this.clientIdHash),t=await this.storage.getAll(),r=Date.now();for(let[n,i]of Object.entries(t))if(n.startsWith(e))try{let o=JSON.parse(i);r>o.expiresAt&&await this.storage.remove(n);}catch{await this.storage.remove(n);}}startAutoCleanup(e=g.DEFAULT_CLEANUP_INTERVAL_MS){this.stopAutoCleanup(),this.cleanupInterval=setInterval(()=>{this.cleanupExpiredStates().catch(()=>{});},e),this.cleanupExpiredStates().catch(()=>{});}stopAutoCleanup(){this.cleanupInterval&&(clearInterval(this.cleanupInterval),this.cleanupInterval=null);}async getStoredStateCount(){if(!this.storage.getAll)return -1;let e=m.authStatePrefix(this.issuerHash,this.clientIdHash),t=await this.storage.getAll(),r=0;for(let n of Object.keys(t))n.startsWith(e)&&r++;return r}};g.DEFAULT_TTL_SECONDS=600,g.ENTROPY_BYTES=32,g.OPERATION_ID_BYTES=16,g.DEFAULT_CLEANUP_INTERVAL_MS=3e5;var D=g;function ue(s){let e=s.split(".");if(e.length!==3)throw new Error("Invalid JWT format: expected 3 parts");let[t,r,n]=e;try{let i=JSON.parse(J(t)),o=JSON.parse(J(r));return {header:i,payload:o,signature:n}}catch{throw new Error("Invalid JWT format: failed to decode")}}function de(s){return ue(s).payload}function Ae(s,e=0){if(s.exp===void 0)return false;let t=Math.floor(Date.now()/1e3);return s.exp+e<t}function G(s){try{return de(s).nonce}catch{return}}function v(s,e){let t=new TextEncoder,r=t.encode(s),n=t.encode(e),i=r.length,o=n.length,c=Math.max(i,o),l=i^o;for(let u=0;u<c;u++){let p=u<i?r[u]:0,d=u<o?n[u]:0;l|=p^d;}return l===0}var I=class{constructor(e,t){this.http=e;this.clientId=t;}buildAuthorizationUrl(e,t,r,n){if(e.require_pushed_authorization_requests&&!n.usePar)throw new a("par_required","Server requires PAR (Pushed Authorization Request) but usePar option is not enabled");if(e.require_signed_request_object&&!n.useJar)throw new a("jar_required","Server requires JAR (JWT Secured Authorization Request) but useJar option is not enabled");let i=e.authorization_endpoint,o=new URLSearchParams;o.set("client_id",this.clientId),o.set("response_type",n.responseType??"code"),o.set("redirect_uri",n.redirectUri),o.set("state",t.state),o.set("nonce",t.nonce),o.set("code_challenge",r.codeChallenge),o.set("code_challenge_method",r.codeChallengeMethod);let c=n.scope??"openid profile";if(o.set("scope",c),n.prompt&&o.set("prompt",n.prompt),n.loginHint&&o.set("login_hint",n.loginHint),n.acrValues&&o.set("acr_values",n.acrValues),n.extraParams){let p=new Set(["client_id","response_type","redirect_uri","state","nonce","code_challenge","code_challenge_method","scope"]);for(let[d,h]of Object.entries(n.extraParams))p.has(d.toLowerCase())||o.set(d,h);}let u={url:`${i}?${o.toString()}`};return n.exposeState&&(u.state=t.state,u.nonce=t.nonce),u}parseCallback(e){let t;e.includes("?")?t=(e.startsWith("http")?new URL(e):new URL(e,"https://dummy.local")).searchParams:t=new URLSearchParams(e);let r=t.get("error");if(r){let o=t.get("error_description")??"Authorization failed";throw new a("oauth_error",o,{details:{error:r,error_description:o,error_uri:t.get("error_uri")}})}let n=t.get("code"),i=t.get("state");if(!n)throw new a("missing_code","Authorization code not found in callback");if(!i)throw new a("missing_state","State parameter not found in callback");return {code:n,state:i}}async exchangeCode(e,t){let r=e.token_endpoint,n=new URLSearchParams({grant_type:"authorization_code",client_id:this.clientId,code:t.code,redirect_uri:t.redirectUri,code_verifier:t.codeVerifier}),i;try{i=await this.http.fetch(r,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n.toString()});}catch(d){throw new a("network_error","Token request failed",{cause:d instanceof Error?d:void 0})}if(!i.ok){let d=i.data;throw new a("token_error","Token exchange failed",{details:{status:i.status,error:d?.error,error_description:d?.error_description}})}let o=i.data;if(t.scope.split(" ").includes("openid")&&!o.id_token)throw new a("missing_id_token","ID token required when openid scope is requested but was not returned by the server");if(o.id_token){let d=G(o.id_token);if(d===void 0)throw new a("missing_nonce","ID token nonce claim is missing but was sent in authorization request");if(!v(d,t.nonce))throw new a("nonce_mismatch","ID token nonce does not match expected value")}let l=Math.floor(Date.now()/1e3),u=o.expires_in?l+o.expires_in:l+3600;return {accessToken:o.access_token,tokenType:o.token_type??"Bearer",expiresAt:u,refreshToken:o.refresh_token,idToken:o.id_token,scope:o.scope}}};var O=class{constructor(e,t,r){this.http=e;this.clientId=t;this.options=r;}async pushAuthorizationRequest(e,t){let r=e.pushed_authorization_request_endpoint;if(!r)throw new a("no_par_endpoint","PAR endpoint not available in discovery document");let n=new URLSearchParams;if(n.set("client_id",this.clientId),n.set("response_type",t.responseType??"code"),n.set("redirect_uri",t.redirectUri),n.set("state",t.state),n.set("nonce",t.nonce),n.set("code_challenge",t.codeChallenge),n.set("code_challenge_method",t.codeChallengeMethod),n.set("scope",t.scope??"openid profile"),t.prompt&&n.set("prompt",t.prompt),t.loginHint&&n.set("login_hint",t.loginHint),t.acrValues&&n.set("acr_values",t.acrValues),t.extraParams){let p=new Set(["client_id","response_type","redirect_uri","state","nonce","code_challenge","code_challenge_method","scope"]);for(let[d,h]of Object.entries(t.extraParams))p.has(d.toLowerCase())||n.set(d,h);}let i={"Content-Type":"application/x-www-form-urlencoded",...this.options?.headers},o;try{o=await this.http.fetch(r,{method:"POST",headers:i,body:n.toString()});}catch(p){throw new a("network_error","PAR request failed",{cause:p instanceof Error?p:void 0})}if(!o.ok){let p=o.data;throw new a("par_error","PAR request failed",{details:{status:o.status,error:p?.error,error_description:p?.error_description}})}let c=o.data;if(!c.request_uri)throw new a("par_error","PAR response missing request_uri");if(typeof c.expires_in!="number")throw new a("par_error","PAR response missing or invalid expires_in");let u=Math.floor(Date.now()/1e3)+c.expires_in;return {requestUri:c.request_uri,expiresAt:u}}buildAuthorizationUrlWithPar(e,t){let r=new URLSearchParams;return r.set("client_id",this.clientId),r.set("request_uri",t),`${e.authorization_endpoint}?${r.toString()}`}};var Te=5,M=class{constructor(e,t){this.http=e;this.clientId=t;}async startDeviceAuthorization(e,t){let r=e.device_authorization_endpoint;if(!r)throw new a("no_device_authorization_endpoint","Device authorization endpoint not available in discovery document");let n=new URLSearchParams({client_id:this.clientId});if(t?.scope&&n.set("scope",t.scope),t?.extraParams){let u=new Set(["client_id","scope"]);for(let[p,d]of Object.entries(t.extraParams))u.has(p.toLowerCase())||n.set(p,d);}let i;try{i=await this.http.fetch(r,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n.toString()});}catch(u){throw new a("network_error","Device authorization request failed",{cause:u instanceof Error?u:void 0})}if(!i.ok){let u=i.data;throw new a("device_authorization_error","Device authorization request failed",{details:{status:i.status,error:u?.error,error_description:u?.error_description}})}let o=i.data;if(!o.device_code||!o.user_code||!o.verification_uri)throw new a("device_authorization_error","Invalid device authorization response: missing required fields");let l=Math.floor(Date.now()/1e3)+o.expires_in;return {deviceCode:o.device_code,userCode:o.user_code,verificationUri:o.verification_uri,verificationUriComplete:o.verification_uri_complete,expiresAt:l,interval:o.interval??Te}}async pollOnce(e,t){let r=Math.floor(Date.now()/1e3);if(r>=t.expiresAt)return {status:"expired"};let n=e.token_endpoint,i=new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:t.deviceCode,client_id:this.clientId}),o;try{o=await this.http.fetch(n,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i.toString()});}catch(p){throw new a("network_error","Device flow token request failed",{cause:p instanceof Error?p:void 0})}if(!o.ok){let p=o.data,d=p?.error;switch(d){case "authorization_pending":return {status:"pending",retryAfter:t.interval};case "slow_down":return {status:"slow_down",retryAfter:t.interval+5};case "expired_token":return {status:"expired"};case "access_denied":return {status:"access_denied"};default:throw new a("device_authorization_error","Device flow token request failed",{details:{status:o.status,error:d,error_description:p?.error_description}})}}let c=o.data,l=c.expires_in?r+c.expires_in:r+3600;return {status:"completed",tokens:{accessToken:c.access_token,tokenType:c.token_type??"Bearer",expiresAt:l,refreshToken:c.refresh_token,idToken:c.id_token,scope:c.scope}}}async pollUntilComplete(e,t,r){let n=t.interval;for(;;){if(r?.signal?.aborted)throw new a("device_authorization_error","Device flow polling aborted");let i=await this.pollOnce(e,t);switch(i.status){case "completed":return i.tokens;case "pending":await this.sleep(i.retryAfter*1e3,r?.signal);continue;case "slow_down":n=i.retryAfter,t.interval=n,await this.sleep(n*1e3,r?.signal);continue;case "expired":throw new a("device_authorization_expired","Device authorization has expired. Please start a new authorization.");case "access_denied":throw new a("device_access_denied","User denied the device authorization request")}}}sleep(e,t){return new Promise((r,n)=>{let i=setTimeout(r,e);t&&t.addEventListener("abort",()=>{clearTimeout(i),n(new a("device_authorization_error","Device flow polling aborted"));},{once:true});})}};var L=class{constructor(e,t){this.keyPair=null;this.serverNonce=null;this.crypto=e,this.config=t??{};}async initialize(){if(!this.crypto.generateDPoPKeyPair)throw new a("dpop_key_generation_error","CryptoProvider does not support DPoP key generation");if(this.crypto.getDPoPKeyPair){let e=await this.crypto.getDPoPKeyPair();if(e){this.keyPair=e;return}}try{this.keyPair=await this.crypto.generateDPoPKeyPair(this.config.algorithm??"ES256");}catch(e){throw new a("dpop_key_generation_error","Failed to generate DPoP key pair",{cause:e instanceof Error?e:void 0})}}isInitialized(){return this.keyPair!==null}async generateProof(e,t,r){if(!this.keyPair)throw new a("dpop_proof_generation_error","DPoP manager not initialized. Call initialize() first.");let n=new URL(t),i=`${n.protocol}//${n.host}${n.pathname}`,o={typ:"dpop+jwt",alg:this.keyPair.algorithm,jwk:this.keyPair.publicKeyJwk},c=Math.floor(Date.now()/1e3),l={jti:this.generateJti(),htm:e.toUpperCase(),htu:i,iat:c};r?.accessTokenHash&&(l.ath=r.accessTokenHash),(r?.nonce??this.serverNonce)&&(l.nonce=r?.nonce??this.serverNonce??void 0);try{let u=F(JSON.stringify(o)),p=F(JSON.stringify(l)),d=`${u}.${p}`,h=await this.keyPair.sign(new TextEncoder().encode(d)),y=f(h);return `${d}.${y}`}catch(u){throw new a("dpop_proof_generation_error","Failed to generate DPoP proof",{cause:u instanceof Error?u:void 0})}}handleNonceResponse(e){this.serverNonce=e;}getServerNonce(){return this.serverNonce}clearServerNonce(){this.serverNonce=null;}getPublicKeyJwk(){return this.keyPair?.publicKeyJwk??null}getThumbprint(){return this.keyPair?.thumbprint??null}async calculateAccessTokenHash(e){let t=await this.crypto.sha256(e);return f(t)}async clear(){this.crypto.clearDPoPKeyPair&&await this.crypto.clearDPoPKeyPair(),this.keyPair=null,this.serverNonce=null;}generateJti(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).substring(2,15)}`}};var Y={access_token:"urn:ietf:params:oauth:token-type:access_token",refresh_token:"urn:ietf:params:oauth:token-type:refresh_token",id_token:"urn:ietf:params:oauth:token-type:id_token"};var _=class _{constructor(e){this.refreshPromise=null;this.discovery=null;this.expiringTimeout=null;this.isLeaderTab=true;this.currentOperationId=null;this.http=e.http,this.storage=e.storage,this.clientId=e.clientId,this.issuerHash=e.issuerHash,this.clientIdHash=e.clientIdHash,this.refreshSkewSeconds=e.refreshSkewSeconds??_.DEFAULT_REFRESH_SKEW_SECONDS,this.eventEmitter=e.eventEmitter,this.expiringThresholdMs=(e.expiringThresholdSeconds??_.DEFAULT_EXPIRING_THRESHOLD_SECONDS)*1e3,this.expiringJitterMs=e.expiringJitterMs??_.DEFAULT_EXPIRING_JITTER_MS;}setDiscovery(e){this.discovery=e;}get tokenKey(){return m.tokens(this.issuerHash,this.clientIdHash)}get idTokenKey(){return m.idToken(this.issuerHash,this.clientIdHash)}async getTokens(){let e=await this.storage.get(this.tokenKey);if(!e)return null;try{return JSON.parse(e)}catch{return await this.clearTokens(),null}}async saveTokens(e){await this.storage.set(this.tokenKey,JSON.stringify(e)),e.idToken&&await this.storage.set(this.idTokenKey,e.idToken),this.scheduleExpiringEvent(e.expiresAt);}scheduleExpiringEvent(e){if(this.expiringTimeout&&(clearTimeout(this.expiringTimeout),this.expiringTimeout=null),!this.isLeaderTab)return;let t=e*1e3,r=t-this.expiringThresholdMs,n=Math.random()*this.expiringJitterMs*2-this.expiringJitterMs,i=r-Date.now()+n;i>0&&(this.expiringTimeout=setTimeout(()=>{let o=Date.now(),c=Math.max(0,Math.floor((t-o)/1e3));this.eventEmitter?.emit("token:expiring",{expiresAt:e,expiresIn:c,timestamp:o,source:"core"});},i));}setLeaderTab(e){this.isLeaderTab=e,!e&&this.expiringTimeout&&(clearTimeout(this.expiringTimeout),this.expiringTimeout=null);}setOperationId(e){this.currentOperationId=e;}getOperationId(){return this.currentOperationId}async clearTokens(){await this.storage.remove(this.tokenKey),await this.storage.remove(this.idTokenKey);}async getAccessToken(){let e=await this.getTokens();if(!e)throw new a("no_tokens","No tokens available. Please authenticate first.");if(this.shouldRefresh(e)){if(!e.refreshToken)throw new a("token_expired","Access token expired and no refresh token available");return this.refreshWithLock(e.refreshToken)}return e.accessToken}async getIdToken(){return (await this.getTokens())?.idToken??null}shouldRefresh(e){let t=Math.floor(Date.now()/1e3);return e.expiresAt-this.refreshSkewSeconds<=t}async refreshWithLock(e,t="on_demand"){if(this.refreshPromise)return (await this.refreshPromise).accessToken;this.refreshPromise=this.doRefreshWithRetry(e,t);try{return (await this.refreshPromise).accessToken}finally{this.refreshPromise=null;}}async refresh(){let e=await this.getTokens();if(!e?.refreshToken)throw new a("no_tokens","No refresh token available");if(this.refreshPromise)return this.refreshPromise;this.refreshPromise=this.doRefreshWithRetry(e.refreshToken,"manual");try{return await this.refreshPromise}finally{this.refreshPromise=null;}}async doRefreshWithRetry(e,t="on_demand",r=0){let i=Date.now();r===0&&this.eventEmitter?.emit("token:refreshing",{reason:t,timestamp:i,source:"core",operationId:this.currentOperationId??void 0});try{return await this.doRefresh(e)}catch(o){let c=o instanceof a?o:new a("refresh_error","Token refresh failed",{cause:o instanceof Error?o:void 0}),l=r<1&&w(c);if(this.eventEmitter?.emit("token:refresh:failed",{error:c,willRetry:l,attempt:r,timestamp:Date.now(),source:"core",operationId:this.currentOperationId??void 0}),l)return this.doRefreshWithRetry(e,t,r+1);throw w(c)||this.eventEmitter?.emit("auth:required",{reason:"refresh_failed",timestamp:Date.now(),source:"core",operationId:this.currentOperationId??void 0}),o}}async doRefresh(e){if(!this.discovery)throw new a("no_discovery","Discovery document not set");let t=this.discovery.token_endpoint,r=new URLSearchParams({grant_type:"refresh_token",client_id:this.clientId,refresh_token:e}),n;try{n=await this.http.fetch(t,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:r.toString()});}catch(u){let p=new a("network_error","Token refresh request failed",{cause:u instanceof Error?u:void 0});throw this.eventEmitter?.emit("token:error",{error:p,context:"refresh",timestamp:Date.now(),source:"core"}),this.eventEmitter&&A(this.eventEmitter,p,{context:"refresh"}),p}if(!n.ok){let u=n.data,p=new a("refresh_error","Token refresh failed",{details:{status:n.status,error:u?.error,error_description:u?.error_description}});throw this.eventEmitter?.emit("token:error",{error:p,context:"refresh",timestamp:Date.now(),source:"core"}),this.eventEmitter&&A(this.eventEmitter,p,{context:"refresh"}),p}let i=n.data,o=Math.floor(Date.now()/1e3),c=i.expires_in?o+i.expires_in:o+3600,l={accessToken:i.access_token,tokenType:i.token_type??"Bearer",expiresAt:c,refreshToken:i.refresh_token??e,idToken:i.id_token,scope:i.scope};return await this.saveTokens(l),this.eventEmitter?.emit("token:refreshed",{hasAccessToken:!!l.accessToken,hasRefreshToken:!!l.refreshToken,hasIdToken:!!l.idToken,expiresAt:l.expiresAt,timestamp:Date.now(),source:"core",operationId:this.currentOperationId??void 0}),l}async isAuthenticated(){let e=await this.getTokens();if(!e)return false;let t=Math.floor(Date.now()/1e3);return e.expiresAt<=t?!!e.refreshToken:true}async exchangeToken(e){if(!this.discovery)throw new a("no_discovery","Discovery document not set");let t=this.discovery.token_endpoint,r=this.mapTokenTypeToUri(e.subjectTokenType??"access_token"),n=new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:token-exchange",client_id:this.clientId,subject_token:e.subjectToken,subject_token_type:r});e.audience&&n.set("audience",e.audience),e.scope&&n.set("scope",e.scope),e.requestedTokenType&&n.set("requested_token_type",this.mapTokenTypeToUri(e.requestedTokenType)),e.actorToken&&(n.set("actor_token",e.actorToken),e.actorTokenType&&n.set("actor_token_type",this.mapTokenTypeToUri(e.actorTokenType)));let i;try{i=await this.http.fetch(t,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n.toString()});}catch(d){let h=new a("network_error","Token exchange request failed",{cause:d instanceof Error?d:void 0});throw this.eventEmitter?.emit("token:error",{error:h,context:"exchange",timestamp:Date.now(),source:"core"}),this.eventEmitter&&A(this.eventEmitter,h,{context:"exchange"}),h}if(!i.ok){let d=i.data,h=new a("token_exchange_error","Token exchange failed",{details:{status:i.status,error:d?.error,error_description:d?.error_description}});throw this.eventEmitter?.emit("token:error",{error:h,context:"exchange",timestamp:Date.now(),source:"core"}),this.eventEmitter&&A(this.eventEmitter,h,{context:"exchange"}),h}let o=i.data,c=Math.floor(Date.now()/1e3),l=o.expires_in?c+o.expires_in:c+3600,u={accessToken:o.access_token,tokenType:o.token_type??"Bearer",expiresAt:l,refreshToken:o.refresh_token,idToken:o.id_token,scope:o.scope},p={tokens:u,issuedTokenType:o.issued_token_type};return this.eventEmitter?.emit("token:exchanged",{hasAccessToken:!!u.accessToken,hasRefreshToken:!!u.refreshToken,issuedTokenType:o.issued_token_type,timestamp:Date.now(),source:"core",operationId:this.currentOperationId??void 0}),p}mapTokenTypeToUri(e){return Y[e]}destroy(){this.expiringTimeout&&(clearTimeout(this.expiringTimeout),this.expiringTimeout=null);}};_.DEFAULT_REFRESH_SKEW_SECONDS=30,_.DEFAULT_EXPIRING_THRESHOLD_SECONDS=300,_.DEFAULT_EXPIRING_JITTER_MS=3e4;var H=_;var U=class{constructor(e){this.http=e.http,this.clientId=e.clientId;}async introspect(e,t){let r=e.introspection_endpoint;if(!r)throw new a("no_introspection_endpoint","Authorization server does not support token introspection");return this.introspectWithEndpoint(r,t)}async introspectWithEndpoint(e,t){let r=new URLSearchParams({client_id:this.clientId,token:t.token});t.tokenTypeHint&&r.set("token_type_hint",t.tokenTypeHint);let n;try{n=await this.http.fetch(e,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:r.toString()});}catch(i){throw new a("network_error","Token introspection request failed",{cause:i instanceof Error?i:void 0})}if(!n.ok){let i=n.data;throw new a("introspection_error","Token introspection failed",{details:{status:n.status,error:i?.error,error_description:i?.error_description}})}return n.data}async isActive(e,t){return (await this.introspect(e,{token:t})).active}};var k=class{constructor(e){this.http=e.http,this.clientId=e.clientId;}async revoke(e,t){let r=e.revocation_endpoint;if(!r)throw new a("no_revocation_endpoint","Authorization server does not support token revocation");let n=new URLSearchParams({client_id:this.clientId,token:t.token});t.tokenTypeHint&&n.set("token_type_hint",t.tokenTypeHint);let i;try{i=await this.http.fetch(r,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n.toString()});}catch(c){throw new a("network_error","Token revocation request failed",{cause:c instanceof Error?c:void 0})}if(i.ok)return;let o=i.data;throw new a("revocation_error","Token revocation failed",{details:{status:i.status,error:o?.error,error_description:o?.error_description}})}async revokeWithEndpoint(e,t){let r=new URLSearchParams({client_id:this.clientId,token:t.token});t.tokenTypeHint&&r.set("token_type_hint",t.tokenTypeHint);let n;try{n=await this.http.fetch(e,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:r.toString()});}catch(o){throw new a("network_error","Token revocation request failed",{cause:o instanceof Error?o:void 0})}if(n.ok)return;let i=n.data;throw new a("revocation_error","Token revocation failed",{details:{status:n.status,error:i?.error,error_description:i?.error_description}})}};var j=class{constructor(e){this.storage=e.storage,this.clientId=e.clientId,this.issuerHash=e.issuerHash,this.clientIdHash=e.clientIdHash,this.eventEmitter=e.eventEmitter,this.endpoints=e.endpoints,this.tokenRevoker=new k({http:e.http,clientId:e.clientId});}async logout(e,t){let r=await this.getStoredIdToken(),n=await this.getStoredTokens(),i;t?.revokeTokens&&e?.revocation_endpoint&&n&&(i=await this.revokeTokens(e,n)),await this.clearTokens(),this.eventEmitter?.emit("session:ended",{reason:"logout",timestamp:Date.now(),source:"core"});let o;if(this.endpoints?.endSession!==void 0?o=this.endpoints.endSession:e&&(o=e.end_session_endpoint),!o)return {localOnly:true,revocation:i};let c=t?.idTokenHint??r,l=new URLSearchParams({client_id:this.clientId});return c&&l.set("id_token_hint",c),t?.postLogoutRedirectUri&&l.set("post_logout_redirect_uri",t.postLogoutRedirectUri),t?.state&&l.set("state",t.state),{logoutUrl:`${o}?${l.toString()}`,localOnly:false,revocation:i}}async revokeTokens(e,t){let r={attempted:true};try{t.refreshToken&&(await this.tokenRevoker.revoke(e,{token:t.refreshToken,tokenTypeHint:"refresh_token"}),r.refreshTokenRevoked=!0),await this.tokenRevoker.revoke(e,{token:t.accessToken,tokenTypeHint:"access_token"}),r.accessTokenRevoked=!0;}catch(n){r.error=n instanceof Error?n:new Error(String(n));}return r}async clearTokens(){let e=m.tokens(this.issuerHash,this.clientIdHash),t=m.idToken(this.issuerHash,this.clientIdHash);await this.storage.remove(e),await this.storage.remove(t);}async getStoredIdToken(){let e=m.idToken(this.issuerHash,this.clientIdHash);return this.storage.get(e)}async getStoredTokens(){let e=m.tokens(this.issuerHash,this.clientIdHash),t=await this.storage.get(e);if(!t)return null;try{return JSON.parse(t)}catch{return null}}};var q=class{constructor(e){this.http=e.http;}async checkSession(e,t){let r=e.userinfo_endpoint;if(!r)return {valid:false,error:new a("no_userinfo_endpoint","UserInfo endpoint not available")};try{let n=await this.http.fetch(r,{method:"GET",headers:{Authorization:`Bearer ${t}`}});return n.ok?{valid:!0,user:n.data}:n.status===401?{valid:!1,error:new a("session_expired","Session has expired")}:{valid:!1,error:new a("session_check_failed","Session check failed",{details:{status:n.status}})}}catch(n){return {valid:false,error:new a("network_error","Failed to check session",{cause:n instanceof Error?n:void 0})}}}async getUserInfo(e,t){let r=e.userinfo_endpoint;if(!r)throw new a("no_userinfo_endpoint","UserInfo endpoint not available");let n;try{n=await this.http.fetch(r,{method:"GET",headers:{Authorization:`Bearer ${t}`}});}catch(i){throw new a("network_error","Failed to fetch user info",{cause:i instanceof Error?i:void 0})}if(!n.ok)throw new a("userinfo_error","Failed to get user info",{details:{status:n.status}});return n.data}};var z=class{constructor(e){this.discovery=null;this.tokenManager=e.tokenManager,this.tokenApiClient=e.tokenApiClient;}setDiscovery(e){this.discovery=e;}async isAuthenticated(){return this.tokenManager.isAuthenticated()}async checkSession(){if(!this.discovery)return {valid:false,error:new a("no_discovery","Discovery document not available")};try{let e=await this.tokenManager.getAccessToken();return this.tokenApiClient.checkSession(this.discovery,e)}catch(e){return e instanceof a?{valid:false,error:e}:{valid:false,error:new a("session_check_failed","Failed to check session",{cause:e instanceof Error?e:void 0})}}}async getUser(){if(!this.discovery)throw new a("no_discovery","Discovery document not available");let e=await this.tokenManager.getAccessToken();return this.tokenApiClient.getUserInfo(this.discovery,e)}};async function pe(s,e,t=16){let r=await s.sha256(e);return f(r).slice(0,t)}var K=class{constructor(e){this.dpopManager=null;this.initialized=false;this.config=$(e),this.normalizedIssuer=T(e.issuer),this.events=new b,this.discoveryClient=new x({http:this.config.http,cacheTtlMs:this.config.discoveryCacheTtlMs}),this.pkce=new P(this.config.crypto),this.authCodeFlow=new I(this.config.http,this.config.clientId),this.parClient=new O(this.config.http,this.config.clientId),this.deviceFlowClient=new M(this.config.http,this.config.clientId);}get eventEmitter(){return this.events}async initialize(){if(this.initialized)return;let e=this.config.hashOptions.hashLength;this.issuerHash=await pe(this.config.crypto,this.normalizedIssuer,e),this.clientIdHash=await pe(this.config.crypto,this.config.clientId,e),this.stateManager=new D(this.config.crypto,this.config.storage,this.issuerHash,this.clientIdHash),this.tokenManager=new H({http:this.config.http,storage:this.config.storage,clientId:this.config.clientId,issuerHash:this.issuerHash,clientIdHash:this.clientIdHash,refreshSkewSeconds:this.config.refreshSkewSeconds,eventEmitter:this.events}),this.logoutHandler=new j({storage:this.config.storage,http:this.config.http,clientId:this.config.clientId,issuerHash:this.issuerHash,clientIdHash:this.clientIdHash,eventEmitter:this.events,endpoints:this.config.endpoints}),this.tokenIntrospector=new U({http:this.config.http,clientId:this.config.clientId}),this.tokenRevoker=new k({http:this.config.http,clientId:this.config.clientId});let t=new q({http:this.config.http});this.sessionManager=new z({tokenManager:this.tokenManager,tokenApiClient:t}),await this.stateManager.cleanupExpiredStates(),this.initialized=true;}ensureInitialized(){if(!this.initialized)throw new a("not_initialized","Client not initialized. Use createAuthrimClient().")}async discover(){let e=await this.discoveryClient.discover(this.normalizedIssuer);return this.tokenManager.setDiscovery(e),this.sessionManager.setDiscovery(e),e}async buildAuthorizationUrl(e){this.ensureInitialized();let t=await this.discover(),r=await this.pkce.generatePKCE(),n=e.scope??"openid profile",i=await this.stateManager.generateAuthState({redirectUri:e.redirectUri,codeVerifier:r.codeVerifier,scope:n,ttlSeconds:this.config.stateTtlSeconds}),o=this.authCodeFlow.buildAuthorizationUrl(t,i,r,e);return this.events.emit("auth:redirecting",{url:o.url,timestamp:Date.now(),source:"core",operationId:i.operationId}),o}async handleCallback(e){this.ensureInitialized();let{code:t,state:r}=this.authCodeFlow.parseCallback(e),n=await this.stateManager.validateAndConsumeState(r),i=n.operationId;this.events.emit("auth:callback",{code:t,state:r,timestamp:Date.now(),source:"core",operationId:i}),this.events.emit("auth:callback:processing",{state:r,timestamp:Date.now(),source:"core",operationId:i});try{let o=await this.discover(),c=await this.authCodeFlow.exchangeCode(o,{code:t,state:r,redirectUri:n.redirectUri,codeVerifier:n.codeVerifier,nonce:n.nonce,scope:n.scope});return await this.tokenManager.saveTokens(c),this.events.emit("auth:callback:complete",{success:!0,timestamp:Date.now(),source:"core",operationId:i}),c}catch(o){throw this.events.emit("auth:callback:complete",{success:false,timestamp:Date.now(),source:"core",operationId:i}),o}}get par(){return {push:async e=>{this.ensureInitialized();let t=await this.discover(),r=await this.pkce.generatePKCE(),n=e.scope??"openid profile",i=await this.stateManager.generateAuthState({redirectUri:e.redirectUri,codeVerifier:r.codeVerifier,scope:n,ttlSeconds:this.config.stateTtlSeconds});return this.parClient.pushAuthorizationRequest(t,{redirectUri:e.redirectUri,scope:n,state:i.state,nonce:i.nonce,codeChallenge:r.codeChallenge,codeChallengeMethod:"S256",prompt:e.prompt,loginHint:e.loginHint,acrValues:e.acrValues,extraParams:e.extraParams})},buildAuthorizationUrl:async e=>{let t=await this.discover();return this.parClient.buildAuthorizationUrlWithPar(t,e)},isAvailable:async()=>!!(await this.discover()).pushed_authorization_request_endpoint,isRequired:async()=>(await this.discover()).require_pushed_authorization_requests===true}}get deviceFlow(){return {start:async e=>{this.ensureInitialized();let t=await this.discover();return this.deviceFlowClient.startDeviceAuthorization(t,e)},pollOnce:async e=>{let t=await this.discover();return this.deviceFlowClient.pollOnce(t,e)},pollUntilComplete:async(e,t)=>{let r=await this.discover(),n=await this.deviceFlowClient.pollUntilComplete(r,e,t);return await this.tokenManager.saveTokens(n),n},isAvailable:async()=>!!(await this.discover()).device_authorization_endpoint}}get dpop(){if(!this.config.crypto.generateDPoPKeyPair)return;this.dpopManager||(this.dpopManager=new L(this.config.crypto));let t=this.dpopManager;return {initialize:()=>t.initialize(),isInitialized:()=>t.isInitialized(),generateProof:(r,n,i)=>t.generateProof(r,n,i),handleNonceResponse:r=>t.handleNonceResponse(r),calculateAccessTokenHash:r=>t.calculateAccessTokenHash(r),getPublicKeyJwk:()=>t.getPublicKeyJwk(),getThumbprint:()=>t.getThumbprint(),clear:()=>t.clear(),isServerSupported:async()=>{let r=await this.discover();return Array.isArray(r.dpop_signing_alg_values_supported)&&r.dpop_signing_alg_values_supported.length>0}}}get token(){return this.ensureInitialized(),{getAccessToken:()=>this.tokenManager.getAccessToken(),getTokens:()=>this.tokenManager.getTokens(),getIdToken:()=>this.tokenManager.getIdToken(),isAuthenticated:()=>this.tokenManager.isAuthenticated(),exchange:async e=>(await this.discover(),this.tokenManager.exchangeToken(e)),introspect:async e=>{let t=await this.discover();return this.tokenIntrospector.introspect(t,e)},revoke:async e=>{let t=await this.discover();return this.tokenRevoker.revoke(t,e)}}}get session(){return this.ensureInitialized(),{isAuthenticated:()=>this.sessionManager.isAuthenticated(),check:()=>this.sessionManager.checkSession()}}async isAuthenticated(){return this.ensureInitialized(),this.tokenManager.isAuthenticated()}async getUser(){return this.ensureInitialized(),this.sessionManager.getUser()}async logout(e){this.ensureInitialized();let t=null;try{t=await this.discover();}catch{}return this.logoutHandler.logout(t,e)}on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}off(e,t){this.events.off(e,t);}};async function Ee(s){let e=new K(s);return await e.initialize(),e}var he=new Set(["login_required","interaction_required","consent_required","account_selection_required"]),X=class{constructor(e){this.clientId=e;}buildSilentAuthUrl(e,t,r,n){let i=e.authorization_endpoint,o=new URLSearchParams;o.set("client_id",this.clientId),o.set("response_type",n.responseType??"code"),o.set("redirect_uri",n.redirectUri),o.set("state",t.state),o.set("nonce",t.nonce),o.set("prompt","none"),o.set("code_challenge",r.codeChallenge),o.set("code_challenge_method",r.codeChallengeMethod);let c=n.scope??"openid";if(o.set("scope",c),n.loginHint&&o.set("login_hint",n.loginHint),n.idTokenHint&&o.set("id_token_hint",n.idTokenHint),n.extraParams){let p=new Set(["client_id","response_type","redirect_uri","state","nonce","code_challenge","code_challenge_method","scope","prompt"]);for(let[d,h]of Object.entries(n.extraParams))p.has(d.toLowerCase())||o.set(d,h);}let u={url:`${i}?${o.toString()}`};return n.exposeState&&(u.state=t.state,u.nonce=t.nonce),u}parseSilentAuthResponse(e){let t;e.includes("?")?t=(e.startsWith("http")?new URL(e):new URL(e,"https://dummy.local")).searchParams:t=new URLSearchParams(e);let r=t.get("error");if(r){let o=t.get("error_description"),c=this.mapSilentAuthError(r);return {success:false,error:new a(c,o??this.getDefaultErrorMessage(r),{details:{error:r,error_description:o,error_uri:t.get("error_uri")}})}}let n=t.get("code"),i=t.get("state");return n?i?{success:true,code:n,state:i}:{success:false,error:new a("missing_state","State parameter not found in silent auth response")}:{success:false,error:new a("missing_code","Authorization code not found in silent auth response")}}isInteractiveLoginRequired(e){return he.has(e.code)}mapSilentAuthError(e){return he.has(e)?e:"oauth_error"}getDefaultErrorMessage(e){switch(e){case "login_required":return "User must log in - no active session found";case "interaction_required":return "User interaction required";case "consent_required":return "User consent required";case "account_selection_required":return "User must select an account";default:return "Silent authentication failed"}}};async function Z(s,e,t){let r={},n={};switch(s.method){case "client_secret_basic":{let i=btoa(`${e}:${s.clientSecret}`);r.Authorization=`Basic ${i}`;break}case "client_secret_post":{n.client_id=e,n.client_secret=s.clientSecret;break}case "private_key_jwt":{let i=Math.floor(Date.now()/1e3),o={iss:e,sub:e,aud:t,jti:Re(),exp:i+300,iat:i},c;try{c=await s.signJwt(o);}catch(l){throw new a("invalid_client_authentication","Failed to sign client assertion JWT",{cause:l instanceof Error?l:void 0})}n.client_id=e,n.client_assertion_type="urn:ietf:params:oauth:client-assertion-type:jwt-bearer",n.client_assertion=c;break}case "none":{if(!("dangerouslyAllowInsecure"in s)||s.dangerouslyAllowInsecure!==true)throw new a("insecure_client_auth",'Client authentication method "none" requires dangerouslyAllowInsecure: true');n.client_id=e;break}default:{let i=s;throw new a("invalid_client_authentication",`Unknown client authentication method: ${i.method}`)}}return {headers:r,bodyParams:n}}function Re(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).substring(2,15)}`}var Q=class{constructor(e){this.http=e.http,this.clientId=e.clientId,this.credentials=e.credentials;}async getToken(e,t){let r=e.token_endpoint,{headers:n,bodyParams:i}=await Z(this.credentials,this.clientId,r),o=new URLSearchParams({grant_type:"client_credentials",...i});if(t?.scope&&o.set("scope",t.scope),t?.audience&&o.set("audience",t.audience),t?.extraParams){let y=new Set(["grant_type","client_id","client_secret","client_assertion","client_assertion_type","scope","audience"]);for(let[C,_e]of Object.entries(t.extraParams))y.has(C.toLowerCase())||o.set(C,_e);}let c={"Content-Type":"application/x-www-form-urlencoded",...n},l;try{l=await this.http.fetch(r,{method:"POST",headers:c,body:o.toString()});}catch(y){throw new a("network_error","Client credentials token request failed",{cause:y instanceof Error?y:void 0})}if(!l.ok){let y=l.data;throw new a("client_credentials_error","Client credentials token request failed",{details:{status:l.status,error:y?.error,error_description:y?.error_description}})}let u=l.data,p=Math.floor(Date.now()/1e3),d=u.expires_in?p+u.expires_in:p+3600;return {accessToken:u.access_token,tokenType:u.token_type??"Bearer",expiresAt:d,refreshToken:u.refresh_token,scope:u.scope}}};var ee=class{constructor(e){this.config=e;}async buildRequestObject(e){let t=Math.floor(Date.now()/1e3),r=this.config.lifetime??300,n={alg:this.config.algorithm??"RS256",typ:"oauth-authz-req+jwt"};this.config.keyId&&(n.kid=this.config.keyId);let i={iss:e.clientId,aud:e.issuer,response_type:e.responseType??"code",client_id:e.clientId,redirect_uri:e.redirectUri,scope:e.scope,state:e.state,nonce:e.nonce,code_challenge:e.codeChallenge,code_challenge_method:e.codeChallengeMethod,iat:t,exp:t+r,jti:this.generateJti()};if(e.prompt&&(i.prompt=e.prompt),e.loginHint&&(i.login_hint=e.loginHint),e.acrValues&&(i.acr_values=e.acrValues),e.extraClaims){let o=new Set(["iss","aud","response_type","client_id","redirect_uri","scope","state","nonce","code_challenge","code_challenge_method","iat","exp","jti","nbf"]);for(let[c,l]of Object.entries(e.extraClaims))o.has(c)||(i[c]=l);}try{return await this.config.signJwt(n,i)}catch(o){throw new a("jar_signing_error","Failed to sign JAR request object",{cause:o instanceof Error?o:void 0})}}generateJti(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).substring(2,15)}`}};function Ce(s){return s.require_signed_request_object===true}var te=class{constructor(e){this.config=e;}async validateResponse(e,t,r){let n=r.clockSkewSeconds??60,i;try{i=await this.config.verifyJwt(t,e.issuer);}catch(l){throw new a("jarm_signature_invalid","Failed to verify JARM response signature",{cause:l instanceof Error?l:void 0})}if(i.iss!==e.issuer)throw new a("jarm_validation_error","JARM response issuer does not match discovery issuer",{details:{expected:e.issuer,actual:i.iss}});if(!(Array.isArray(i.aud)?i.aud:[i.aud]).includes(r.clientId))throw new a("jarm_validation_error","JARM response audience does not match client_id",{details:{expected:r.clientId,actual:i.aud}});let c=Math.floor(Date.now()/1e3);if(i.exp&&i.exp+n<c)throw new a("jarm_validation_error","JARM response has expired");if(i.iat&&i.iat-n>c)throw new a("jarm_validation_error","JARM response iat is in the future");if(i.error)throw new a("oauth_error",i.error_description??i.error,{details:{error:i.error,error_description:i.error_description,error_uri:i.error_uri}});if(!i.state)throw new a("jarm_validation_error","JARM response is missing state claim");if(!v(i.state,r.expectedState))throw new a("jarm_validation_error","JARM response state does not match expected state");if(!i.code)throw new a("jarm_validation_error","JARM response is missing authorization code");return {code:i.code,state:i.state}}static extractResponseFromCallback(e){let t;return e.includes("?")?t=(e.startsWith("http")?new URL(e):new URL(e,"https://dummy.local")).searchParams:t=new URLSearchParams(e),t.get("response")}};var R=class R{constructor(e){this.tokenManager=null;this.checkInterval=null;this.abortController=null;this.isRunning=false;this.options={thresholdSeconds:e?.thresholdSeconds??R.DEFAULT_THRESHOLD_SECONDS,checkIntervalMs:e?.checkIntervalMs??R.DEFAULT_CHECK_INTERVAL_MS,eventEmitter:e?.eventEmitter};}start(e){this.isRunning||(this.tokenManager=e,this.abortController=new AbortController,this.isRunning=true,this.checkInterval=setInterval(()=>{this.checkAndRefresh().catch(()=>{});},this.options.checkIntervalMs),this.checkAndRefresh().catch(()=>{}));}stop(){this.isRunning&&(this.isRunning=false,this.checkInterval&&(clearInterval(this.checkInterval),this.checkInterval=null),this.abortController&&(this.abortController.abort(),this.abortController=null),this.tokenManager=null);}get running(){return this.isRunning}get signal(){return this.abortController?.signal??null}async checkAndRefresh(){if(!(!this.tokenManager||!this.isRunning))try{let e=await this.tokenManager.getTokens();if(!e)return;let t=Math.floor(Date.now()/1e3);e.expiresAt-t<=this.options.thresholdSeconds&&e.refreshToken&&await this.tokenManager.refresh();}catch{}}async forceCheck(){await this.checkAndRefresh();}};R.DEFAULT_THRESHOLD_SECONDS=60,R.DEFAULT_CHECK_INTERVAL_MS=3e4;var re=R;var ne=class{constructor(e){this.crypto=e.crypto;}async calculate(e){let t=e.salt;if(!t){let c=await this.crypto.randomBytes(16);t=f(c);}let r=e.clientId+" "+e.origin+" "+e.opBrowserState+t,n=await this.crypto.sha256(r),i=f(n);return {sessionState:i+"."+t,hash:i,salt:t}}async validate(e,t){let r=this.parse(e);if(!r)return false;let n=await this.calculate({...t,salt:r.salt});return v(n.sessionState,e)}parse(e){if(!e||typeof e!="string"||e.length>512)return null;let i=e.lastIndexOf(".");if(i===-1||i===0||i===e.length-1)return null;let o=e.substring(0,i),c=e.substring(i+1);if(!o||!c||o.length>256||c.length>128)return null;let l=/^[A-Za-z0-9_-]+$/;return !l.test(o)||!l.test(c)?null:{hash:o,salt:c}}};var ie=class{build(e,t){let r=new URL(e.logoutUri),n={};return e.includeIssuer&&t.iss&&(r.searchParams.set("iss",t.iss),n.iss=t.iss),e.includeSessionId&&t.sid&&(r.searchParams.set("sid",t.sid),n.sid=t.sid),{url:r.toString(),params:n}}parseParams(e){let t=typeof e=="string"?new URL(e):e,r={},n=t.searchParams.get("iss");n&&(r.iss=n);let i=t.searchParams.get("sid");return i&&(r.sid=i),r}validateRequest(e,t={}){let r;try{r=this.parseParams(e);}catch{return {valid:false,error:"Invalid URL format"}}return t.requireIss&&!r.iss?{valid:false,error:"Missing required iss parameter"}:t.requireSid&&!r.sid?{valid:false,error:"Missing required sid parameter"}:t.issuer&&r.iss&&!v(r.iss,t.issuer)?{valid:false,error:"Issuer validation failed"}:t.sessionId&&r.sid&&!v(r.sid,t.sessionId)?{valid:false,error:"Session ID validation failed"}:{valid:true,params:r}}};var xe=["accessToken","refreshToken","idToken","token","code","password","secret","credentials","authorization","bearer","codeVerifier","code_verifier","client_secret"],fe=["code","state","nonce","id_token","access_token","refresh_token","token"],B=class{constructor(e){this.entries=[];this.maxEvents=e?.maxEvents??100,this.redactLevel=e?.redactLevel??"default";}record(e,t,r){let n=r?.redact??this.redactLevel,i=this.redactData(t,n),o={type:e,timestamp:Date.now(),operationId:r?.operationId,data:i};for(this.entries.push(o);this.entries.length>this.maxEvents;)this.entries.shift();}getRecent(e){return e===void 0?[...this.entries]:this.entries.slice(-e)}getByOperationId(e){return this.entries.filter(t=>t.operationId===e)}getByType(e){return this.entries.filter(t=>t.type===e)}clear(){this.entries=[];}get length(){return this.entries.length}toJSON(){return JSON.stringify(this.entries,null,2)}setRedactLevel(e){this.redactLevel=e;}redactData(e,t){return t==="none"||e===void 0||e===null||typeof e!="object"?e:this.deepRedact(e,t)}deepRedact(e,t){let r={};for(let[n,i]of Object.entries(e)){let o=n.toLowerCase();if(this.isSensitiveKey(o)){let c=n.charAt(0).toUpperCase()+n.slice(1);r[`has${c}`]=i!=null,r[n]="[REDACTED]";continue}if(t==="aggressive"&&o==="url"&&typeof i=="string"){r[n]=this.redactUrl(i);continue}if(i!==null&&typeof i=="object"&&!Array.isArray(i)){r[n]=this.deepRedact(i,t);continue}if(Array.isArray(i)){r[n]=i.map(c=>c!==null&&typeof c=="object"?this.deepRedact(c,t):c);continue}r[n]=i;}return r}isSensitiveKey(e){return xe.some(t=>e===t.toLowerCase()||e.includes(t.toLowerCase()))}redactUrl(e){try{let t=new URL(e);for(let r of fe)t.searchParams.has(r)&&t.searchParams.set(r,"[REDACTED]");if(t.hash){let r=new URLSearchParams(t.hash.slice(1)),n=!1;for(let i of fe)r.has(i)&&(r.set(i,"[REDACTED]"),n=!0);n&&(t.hash="#"+r.toString());}return t.toString()}catch{return e.replace(/([?&])(code|token|state|nonce)=[^&]*/gi,"$1$2=[REDACTED]")}}};function oe(s){let e=s?.timestamps??false;return {log(t,r,n){let i=e?`[Authrim:${t.toUpperCase()} ${new Date().toISOString()}]`:`[Authrim:${t.toUpperCase()}]`,o=t==="debug"?"log":t,c=typeof console<"u"?console:null;c&&(n!==void 0?c[o]?.(i,r,n):c[o]?.(i,r));}}}var se={log(){}};function me(s){return s.enabled?s.logger?s.logger:oe({timestamps:s.logTimestamps}):se}var V=class{constructor(e,t){this.operationId=null;this.logger=e,this.verbose=t?.verbose??false;}setOperationId(e){this.operationId=e;}getOperationId(){return this.operationId}debug(e,t){this.verbose&&this.logger.log("debug",this.formatMessage(e),t);}info(e,t){this.logger.log("info",this.formatMessage(e),t);}warn(e,t){this.logger.log("warn",this.formatMessage(e),t);}error(e,t){this.logger.log("error",this.formatMessage(e),t);}formatMessage(e){return this.operationId?`[${this.operationId.slice(0,8)}] ${e}`:e}};async function be(s,e){let t=await e.sha256(s),r=t.slice(0,t.length/2);return f(r)}function Pe(s,e){return new Promise((t,r)=>{let n=new a("operation_cancelled","Operation was cancelled");if(e.aborted){r(n);return}let i=()=>{r(n);};e.addEventListener("abort",i,{once:true}),s.then(t).catch(r).finally(()=>{e.removeEventListener("abort",i);});})}function Se(s){let e=new AbortController;return {promise:s(e.signal),cancel:()=>e.abort(),signal:e.signal}}function ae(s){return s instanceof a&&s.code==="operation_cancelled"}async function De(s){try{let e=await Promise.race(s.map(t=>t.promise));return s.forEach(t=>t.cancel()),e}catch(e){throw s.forEach(t=>t.cancel()),e}}var Ie={maxRetries:3,baseDelayMs:1e3,maxDelayMs:3e4,jitter:true};function ye(s,e,t,r){let n=e*Math.pow(2,s),i=Math.min(n,t);if(r){let o=i*.5,c=Math.random()*o-o/2;return Math.max(0,Math.floor(i+c))}return i}function ge(s,e){return new Promise((t,r)=>{if(e?.aborted){r(new a("operation_cancelled","Sleep was cancelled"));return}let n=setTimeout(t,s);if(e){let i=()=>{clearTimeout(n),r(new a("operation_cancelled","Sleep was cancelled"));};e.addEventListener("abort",i,{once:true});}})}async function ve(s,e){let t={...Ie,...e},{maxRetries:r,baseDelayMs:n,maxDelayMs:i,jitter:o,signal:c,shouldRetry:l,onRetry:u}=t,p;for(let d=0;d<=r;d++)try{if(c?.aborted)throw new a("operation_cancelled","Operation was cancelled");return await s()}catch(h){if(p=h,ae(h))throw h;let y=l?l(h,d):h instanceof a&&w(h);if(d>=r||!y)throw h;let C=ye(d,n,i,o);u?.(h,d+1,C),await ge(C,c);}throw p}function Oe(s){return (e,t)=>ve(e,{...s,...t})}function Me(s){let e=s instanceof Headers?s.get("retry-after"):s["retry-after"]??s["Retry-After"];if(!e)return null;let t=parseInt(e,10);if(!isNaN(t))return t*1e3;let r=new Date(e);if(!isNaN(r.getTime())){let n=r.getTime()-Date.now();return Math.max(0,n)}return null}
|
|
2
|
-
exports.AuthorizationCodeFlow=I;exports.AuthrimClient=K;exports.AuthrimError=a;exports.AutoRefreshScheduler=re;exports.ClientCredentialsClient=Q;exports.DPoPManager=L;exports.DebugContext=V;exports.DeviceFlowClient=M;exports.DiscoveryClient=x;exports.EventEmitter=b;exports.EventTimeline=B;exports.FrontChannelLogoutUrlBuilder=ie;exports.JARBuilder=ee;exports.JARMValidator=te;exports.LogoutHandler=j;exports.PARClient=O;exports.PKCEHelper=
|
|
1
|
+
'use strict';function $(s){return {...s,scopes:s.scopes??["openid","profile"],flowEngine:s.flowEngine??false,discoveryCacheTtlMs:s.discoveryCacheTtlMs??3600*1e3,refreshSkewSeconds:s.refreshSkewSeconds??30,stateTtlSeconds:s.stateTtlSeconds??600,hashOptions:{hashLength:s.hashOptions?.hashLength??16}}}var a=class s extends Error{constructor(e,t,r){super(t),this.name="AuthrimError",this.code=e,this.details=r?.details,this.errorUri=r?.errorUri,this.cause=r?.cause;}static fromOAuthError(e){let r=["invalid_request","unauthorized_client","access_denied","unsupported_response_type","invalid_scope","server_error","temporarily_unavailable","invalid_grant","invalid_token"].includes(e.error)?e.error:"invalid_request";return new s(r,e.error_description??e.error,{errorUri:e.error_uri,details:{originalError:e.error}})}isRetryable(){return this.code==="network_error"||this.code==="timeout_error"}get meta(){return ce(this.code)}},ke={invalid_request:{transient:false,retryable:false,userAction:"contact_support",severity:"error"},unauthorized_client:{transient:false,retryable:false,userAction:"contact_support",severity:"fatal"},access_denied:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},unsupported_response_type:{transient:false,retryable:false,userAction:"contact_support",severity:"fatal"},invalid_scope:{transient:false,retryable:false,userAction:"contact_support",severity:"error"},server_error:{transient:true,retryable:true,retryAfterMs:5e3,maxRetries:3,userAction:"retry",severity:"error"},temporarily_unavailable:{transient:true,retryable:true,retryAfterMs:1e4,maxRetries:3,userAction:"retry",severity:"warning"},invalid_grant:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},invalid_token:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},invalid_state:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},expired_state:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},invalid_nonce:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},nonce_mismatch:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},missing_nonce:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},missing_id_token:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},session_expired:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},session_check_failed:{transient:true,retryable:true,retryAfterMs:3e3,maxRetries:2,userAction:"retry",severity:"warning"},network_error:{transient:true,retryable:true,retryAfterMs:2e3,maxRetries:3,userAction:"check_network",severity:"error"},timeout_error:{transient:true,retryable:true,retryAfterMs:3e3,maxRetries:3,userAction:"retry",severity:"warning"},discovery_error:{transient:true,retryable:true,retryAfterMs:5e3,maxRetries:2,userAction:"retry",severity:"error"},discovery_mismatch:{transient:false,retryable:false,userAction:"contact_support",severity:"fatal"},configuration_error:{transient:false,retryable:false,userAction:"contact_support",severity:"fatal"},storage_error:{transient:true,retryable:true,retryAfterMs:1e3,maxRetries:2,userAction:"retry",severity:"error"},flow_engine_error:{transient:false,retryable:false,userAction:"contact_support",severity:"error"},no_tokens:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},token_expired:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},token_error:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},refresh_error:{transient:false,retryable:false,retryAfterMs:0,maxRetries:0,userAction:"reauthenticate",severity:"error"},token_exchange_error:{transient:false,retryable:false,retryAfterMs:0,maxRetries:0,userAction:"reauthenticate",severity:"error"},oauth_error:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},missing_code:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},missing_state:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},not_initialized:{transient:false,retryable:false,userAction:"none",severity:"fatal"},no_discovery:{transient:true,retryable:true,retryAfterMs:3e3,maxRetries:2,userAction:"retry",severity:"error"},no_userinfo_endpoint:{transient:false,retryable:false,userAction:"none",severity:"warning"},userinfo_error:{transient:true,retryable:true,retryAfterMs:2e3,maxRetries:2,userAction:"retry",severity:"error"},introspection_error:{transient:true,retryable:true,retryAfterMs:2e3,maxRetries:2,userAction:"retry",severity:"error"},revocation_error:{transient:true,retryable:true,retryAfterMs:2e3,maxRetries:2,userAction:"retry",severity:"error"},no_introspection_endpoint:{transient:false,retryable:false,userAction:"none",severity:"warning"},no_revocation_endpoint:{transient:false,retryable:false,userAction:"none",severity:"warning"},login_required:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},interaction_required:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},consent_required:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},account_selection_required:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},dom_not_ready:{transient:true,retryable:true,retryAfterMs:100,maxRetries:3,userAction:"retry",severity:"error"},state_mismatch:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},popup_blocked:{transient:false,retryable:false,userAction:"none",severity:"warning"},popup_closed:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},invalid_response:{transient:false,retryable:false,userAction:"contact_support",severity:"error"},invalid_callback:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},passkey_not_found:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},passkey_verification_failed:{transient:false,retryable:true,retryAfterMs:1e3,maxRetries:3,userAction:"retry",severity:"error"},passkey_not_supported:{transient:false,retryable:false,userAction:"none",severity:"warning"},passkey_cancelled:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},passkey_invalid_credential:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},email_code_invalid:{transient:false,retryable:true,retryAfterMs:0,maxRetries:5,userAction:"retry",severity:"warning"},email_code_expired:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},email_code_too_many_attempts:{transient:false,retryable:false,retryAfterMs:3e5,userAction:"retry",severity:"error"},challenge_expired:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},challenge_invalid:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},auth_code_invalid:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},auth_code_expired:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},pkce_mismatch:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},origin_not_allowed:{transient:false,retryable:false,userAction:"contact_support",severity:"fatal"},mfa_required:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},email_verification_required:{transient:false,retryable:false,userAction:"none",severity:"warning"},consent_required_direct:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},rate_limited:{transient:true,retryable:true,retryAfterMs:6e4,maxRetries:3,userAction:"retry",severity:"warning"},event_handler_error:{transient:false,retryable:false,userAction:"none",severity:"warning"},par_required:{transient:false,retryable:false,userAction:"none",severity:"fatal"},no_par_endpoint:{transient:false,retryable:false,userAction:"contact_support",severity:"fatal"},par_error:{transient:true,retryable:true,retryAfterMs:2e3,maxRetries:2,userAction:"retry",severity:"error"},par_request_uri_expired:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},no_device_authorization_endpoint:{transient:false,retryable:false,userAction:"contact_support",severity:"fatal"},device_authorization_error:{transient:true,retryable:true,retryAfterMs:2e3,maxRetries:2,userAction:"retry",severity:"error"},device_authorization_pending:{transient:true,retryable:true,retryAfterMs:5e3,maxRetries:60,userAction:"none",severity:"warning"},device_slow_down:{transient:true,retryable:true,retryAfterMs:1e4,maxRetries:60,userAction:"none",severity:"warning"},device_authorization_expired:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},device_access_denied:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},client_credentials_error:{transient:true,retryable:true,retryAfterMs:2e3,maxRetries:2,userAction:"retry",severity:"error"},invalid_client_authentication:{transient:false,retryable:false,userAction:"contact_support",severity:"fatal"},insecure_client_auth:{transient:false,retryable:false,userAction:"none",severity:"fatal"},dpop_key_generation_error:{transient:true,retryable:true,retryAfterMs:1e3,maxRetries:2,userAction:"retry",severity:"error"},dpop_proof_generation_error:{transient:false,retryable:false,userAction:"none",severity:"error"},dpop_nonce_required:{transient:true,retryable:true,retryAfterMs:0,maxRetries:1,userAction:"none",severity:"warning"},jar_signing_error:{transient:false,retryable:false,userAction:"contact_support",severity:"error"},jar_required:{transient:false,retryable:false,userAction:"none",severity:"fatal"},jarm_validation_error:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},jarm_signature_invalid:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},operation_cancelled:{transient:false,retryable:true,retryAfterMs:0,maxRetries:1,userAction:"retry",severity:"warning"},invalid_return_to:{transient:false,retryable:false,userAction:"none",severity:"error"}};function ce(s){return ke[s]}function W(s){let e=s.meta;if(!e.retryable&&e.userAction==="contact_support")return {severity:"fatal",remediation:"contact_support"};if(e.severity==="fatal")return {severity:"fatal",remediation:we(e.userAction)};let t="none";return e.retryable?t="retry":e.userAction==="reauthenticate"?t="reauthenticate":s.code==="popup_blocked"?t="switch_flow":e.userAction==="contact_support"&&(t="contact_support"),{severity:"recoverable",remediation:t}}function we(s){switch(s){case "retry":case "check_network":return "retry";case "reauthenticate":return "reauthenticate";case "contact_support":return "contact_support";default:return "none"}}function w(s){let e=W(s);return e.severity==="recoverable"&&e.remediation==="retry"}function A(s,e,t){let{severity:r,remediation:n}=W(e),i=Date.now(),o=t.source??"core",c={error:e,severity:r,remediation:n,context:t.context,timestamp:i,source:o,operationId:t.operationId};s.emit("error",c),r==="recoverable"?s.emit("error:recoverable",{...c,severity:"recoverable"}):s.emit("error:fatal",{...c,severity:"fatal"});}function T(s){return s.replace(/\/+$/,"")}var N=class N{constructor(e){this.cache=new Map;this.http=e.http,this.cacheTtlMs=e.cacheTtlMs??N.DEFAULT_CACHE_TTL_MS;}async discover(e){let t=T(e),r=this.cache.get(t);if(r&&!this.isExpired(r))return r.doc;let n=`${t}/.well-known/openid-configuration`,i;try{let c=await this.http.fetch(n);if(!c.ok)throw new a("discovery_error",`Discovery request failed: ${c.status}`,{details:{status:c.status,statusText:c.statusText}});i=c.data;}catch(c){throw c instanceof a?c:new a("discovery_error","Failed to fetch discovery document",{cause:c instanceof Error?c:void 0,details:{url:n}})}let o=T(i.issuer);if(o!==t)throw new a("discovery_mismatch",`Issuer mismatch in discovery document: expected "${t}", got "${o}"`,{details:{expected:t,actual:o}});return this.cache.set(t,{doc:i,fetchedAt:Date.now()}),i}isExpired(e){return Date.now()-e.fetchedAt>this.cacheTtlMs}clearCache(){this.cache.clear();}clearIssuer(e){this.cache.delete(T(e));}};N.DEFAULT_CACHE_TTL_MS=3600*1e3;var x=N;var b=class{constructor(){this.listeners=new Map;}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>{this.off(e,t);}}once(e,t){let r=(n=>{this.off(e,r),t(n);});return this.on(e,r)}off(e,t){let r=this.listeners.get(e);r&&(r.delete(t),r.size===0&&this.listeners.delete(e));}emit(e,t){let r=this.listeners.get(e);if(r)for(let n of r)try{n(t);}catch(i){if(e!=="error"){let o=i instanceof a?i:new a("event_handler_error","Event handler threw an error",{cause:i instanceof Error?i:void 0});this.emit("error",{error:o,context:`Error in event handler for '${e}'`});}}}removeAllListeners(e){e?this.listeners.delete(e):this.listeners.clear();}listenerCount(e){return this.listeners.get(e)?.size??0}};var S=class{constructor(e){this.crypto=e;}async generatePKCE(){let e=await this.crypto.generateCodeVerifier(),t=await this.crypto.generateCodeChallenge(e);return {codeVerifier:e,codeChallenge:t,codeChallengeMethod:"S256"}}async generateCodeVerifier(){return this.crypto.generateCodeVerifier()}async generateCodeChallenge(e){return this.crypto.generateCodeChallenge(e)}};function f(s){let e="",t=s.length;for(let r=0;r<t;r+=3){let n=s[r],i=r+1<t?s[r+1]:0,o=r+2<t?s[r+2]:0,c=n<<16|i<<8|o;e+=E[c>>18&63],e+=E[c>>12&63],e+=r+1<t?E[c>>6&63]:"",e+=r+2<t?E[c&63]:"";}return e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function le(s){if(!/^[A-Za-z0-9_-]*$/.test(s))throw new Error("Invalid base64url string: contains invalid characters");let e=s.replace(/-/g,"+").replace(/_/g,"/");for(;e.length%4;)e+="=";let t=e.length,r=e.endsWith("==")?2:e.endsWith("=")?1:0,n=t*3/4-r,i=new Uint8Array(n),o=0;for(let c=0;c<t;c+=4){let l=P[e.charCodeAt(c)],u=P[e.charCodeAt(c+1)],p=P[e.charCodeAt(c+2)],d=P[e.charCodeAt(c+3)],h=l<<18|u<<12|p<<6|d;o<n&&(i[o++]=h>>16&255),o<n&&(i[o++]=h>>8&255),o<n&&(i[o++]=h&255);}return i}function F(s){let e=new TextEncoder;return f(e.encode(s))}function J(s){return new TextDecoder().decode(le(s))}var E="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",P=new Uint8Array(256);for(let s=0;s<E.length;s++)P[E.charCodeAt(s)]=s;var m={authState:(s,e,t)=>`authrim:${s}:${e}:auth:${t}`,tokens:(s,e)=>`authrim:${s}:${e}:tokens`,idToken:(s,e)=>`authrim:${s}:${e}:id_token`,authStatePrefix:(s,e)=>`authrim:${s}:${e}:auth:`},g=class g{constructor(e,t,r,n){this.crypto=e;this.storage=t;this.issuerHash=r;this.clientIdHash=n;this.cleanupInterval=null;}async generateAuthState(e){let t=e.ttlSeconds??g.DEFAULT_TTL_SECONDS,r;e.returnTo&&(r=this.validateReturnTo(e.returnTo,e.returnToOptions??{policy:"relative_only"}));let n=await this.crypto.randomBytes(g.ENTROPY_BYTES),i=await this.crypto.randomBytes(g.ENTROPY_BYTES),o=await this.crypto.randomBytes(g.OPERATION_ID_BYTES),c=f(n),l=f(i),u=f(o),p=Date.now(),d={state:c,nonce:l,codeVerifier:e.codeVerifier,redirectUri:e.redirectUri,scope:e.scope,createdAt:p,expiresAt:p+t*1e3,returnTo:r,operationId:u},h=m.authState(this.issuerHash,this.clientIdHash,c);return await this.storage.set(h,JSON.stringify(d)),d}validateReturnTo(e,t){switch(t.policy){case "relative_only":if(e.startsWith("/")&&!e.startsWith("//")&&!e.includes(":"))return e;throw new a("invalid_return_to","returnTo must be a relative path (e.g., /dashboard)");case "same_origin":try{let r=typeof globalThis<"u"?globalThis.window:void 0,n=t.currentOrigin??r?.location?.origin;if(!n)throw new a("invalid_return_to","currentOrigin is required for same_origin policy in non-browser environments");if(e.startsWith("/")&&!e.startsWith("//")||new URL(e).origin===n)return e}catch(r){if(r instanceof a)throw r}throw new a("invalid_return_to","returnTo must be same origin or a relative path");case "allowlist":if(!t.allowedOrigins||t.allowedOrigins.length===0)throw new a("invalid_return_to","allowedOrigins is required when using allowlist policy");if(e.startsWith("/")&&!e.startsWith("//"))return e;try{let r=new URL(e);if(t.allowedOrigins.includes(r.origin))return e}catch{}throw new a("invalid_return_to",`returnTo origin not in allowlist: ${t.allowedOrigins.join(", ")}`);default:throw new a("invalid_return_to",`Unknown returnTo policy: ${t.policy}`)}}async validateAndConsumeState(e){let t=m.authState(this.issuerHash,this.clientIdHash,e);try{let r=await this.storage.get(t);if(!r)throw new a("invalid_state","State not found or already used");let n;try{n=JSON.parse(r);}catch{throw new a("invalid_state","Malformed state data")}if(Date.now()>n.expiresAt)throw new a("expired_state","State has expired");return n}finally{await this.storage.remove(t);}}async cleanupExpiredStates(){if(!this.storage.getAll)return;let e=m.authStatePrefix(this.issuerHash,this.clientIdHash),t=await this.storage.getAll(),r=Date.now();for(let[n,i]of Object.entries(t))if(n.startsWith(e))try{let o=JSON.parse(i);r>o.expiresAt&&await this.storage.remove(n);}catch{await this.storage.remove(n);}}startAutoCleanup(e=g.DEFAULT_CLEANUP_INTERVAL_MS){this.stopAutoCleanup(),this.cleanupInterval=setInterval(()=>{this.cleanupExpiredStates().catch(()=>{});},e),this.cleanupExpiredStates().catch(()=>{});}stopAutoCleanup(){this.cleanupInterval&&(clearInterval(this.cleanupInterval),this.cleanupInterval=null);}async getStoredStateCount(){if(!this.storage.getAll)return -1;let e=m.authStatePrefix(this.issuerHash,this.clientIdHash),t=await this.storage.getAll(),r=0;for(let n of Object.keys(t))n.startsWith(e)&&r++;return r}};g.DEFAULT_TTL_SECONDS=600,g.ENTROPY_BYTES=32,g.OPERATION_ID_BYTES=16,g.DEFAULT_CLEANUP_INTERVAL_MS=3e5;var D=g;function ue(s){let e=s.split(".");if(e.length!==3)throw new Error("Invalid JWT format: expected 3 parts");let[t,r,n]=e;try{let i=JSON.parse(J(t)),o=JSON.parse(J(r));return {header:i,payload:o,signature:n}}catch{throw new Error("Invalid JWT format: failed to decode")}}function de(s){return ue(s).payload}function Ae(s,e=0){if(s.exp===void 0)return false;let t=Math.floor(Date.now()/1e3);return s.exp+e<t}function G(s){try{return de(s).nonce}catch{return}}function v(s,e){let t=new TextEncoder,r=t.encode(s),n=t.encode(e),i=r.length,o=n.length,c=Math.max(i,o),l=i^o;for(let u=0;u<c;u++){let p=u<i?r[u]:0,d=u<o?n[u]:0;l|=p^d;}return l===0}var I=class{constructor(e,t){this.http=e;this.clientId=t;}buildAuthorizationUrl(e,t,r,n){if(e.require_pushed_authorization_requests&&!n.usePar)throw new a("par_required","Server requires PAR (Pushed Authorization Request) but usePar option is not enabled");if(e.require_signed_request_object&&!n.useJar)throw new a("jar_required","Server requires JAR (JWT Secured Authorization Request) but useJar option is not enabled");let i=e.authorization_endpoint,o=new URLSearchParams;o.set("client_id",this.clientId),o.set("response_type",n.responseType??"code"),o.set("redirect_uri",n.redirectUri),o.set("state",t.state),o.set("nonce",t.nonce),o.set("code_challenge",r.codeChallenge),o.set("code_challenge_method",r.codeChallengeMethod);let c=n.scope??"openid profile";if(o.set("scope",c),n.prompt&&o.set("prompt",n.prompt),n.loginHint&&o.set("login_hint",n.loginHint),n.acrValues&&o.set("acr_values",n.acrValues),n.extraParams){let p=new Set(["client_id","response_type","redirect_uri","state","nonce","code_challenge","code_challenge_method","scope"]);for(let[d,h]of Object.entries(n.extraParams))p.has(d.toLowerCase())||o.set(d,h);}let u={url:`${i}?${o.toString()}`};return n.exposeState&&(u.state=t.state,u.nonce=t.nonce),u}parseCallback(e){let t;e.includes("?")?t=(e.startsWith("http")?new URL(e):new URL(e,"https://dummy.local")).searchParams:t=new URLSearchParams(e);let r=t.get("error");if(r){let o=t.get("error_description")??"Authorization failed";throw new a("oauth_error",o,{details:{error:r,error_description:o,error_uri:t.get("error_uri")}})}let n=t.get("code"),i=t.get("state");if(!n)throw new a("missing_code","Authorization code not found in callback");if(!i)throw new a("missing_state","State parameter not found in callback");return {code:n,state:i}}async exchangeCode(e,t){let r=e.token_endpoint,n=new URLSearchParams({grant_type:"authorization_code",client_id:this.clientId,code:t.code,redirect_uri:t.redirectUri,code_verifier:t.codeVerifier}),i;try{i=await this.http.fetch(r,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n.toString()});}catch(d){throw new a("network_error","Token request failed",{cause:d instanceof Error?d:void 0})}if(!i.ok){let d=i.data;throw new a("token_error","Token exchange failed",{details:{status:i.status,error:d?.error,error_description:d?.error_description}})}let o=i.data;if(t.scope.split(" ").includes("openid")&&!o.id_token)throw new a("missing_id_token","ID token required when openid scope is requested but was not returned by the server");if(o.id_token){let d=G(o.id_token);if(d===void 0)throw new a("missing_nonce","ID token nonce claim is missing but was sent in authorization request");if(!v(d,t.nonce))throw new a("nonce_mismatch","ID token nonce does not match expected value")}let l=Math.floor(Date.now()/1e3),u=o.expires_in?l+o.expires_in:l+3600;return {accessToken:o.access_token,tokenType:o.token_type??"Bearer",expiresAt:u,refreshToken:o.refresh_token,idToken:o.id_token,scope:o.scope}}};var O=class{constructor(e,t,r){this.http=e;this.clientId=t;this.options=r;}async pushAuthorizationRequest(e,t){let r=e.pushed_authorization_request_endpoint;if(!r)throw new a("no_par_endpoint","PAR endpoint not available in discovery document");let n=new URLSearchParams;if(n.set("client_id",this.clientId),n.set("response_type",t.responseType??"code"),n.set("redirect_uri",t.redirectUri),n.set("state",t.state),n.set("nonce",t.nonce),n.set("code_challenge",t.codeChallenge),n.set("code_challenge_method",t.codeChallengeMethod),n.set("scope",t.scope??"openid profile"),t.prompt&&n.set("prompt",t.prompt),t.loginHint&&n.set("login_hint",t.loginHint),t.acrValues&&n.set("acr_values",t.acrValues),t.extraParams){let p=new Set(["client_id","response_type","redirect_uri","state","nonce","code_challenge","code_challenge_method","scope"]);for(let[d,h]of Object.entries(t.extraParams))p.has(d.toLowerCase())||n.set(d,h);}let i={"Content-Type":"application/x-www-form-urlencoded",...this.options?.headers},o;try{o=await this.http.fetch(r,{method:"POST",headers:i,body:n.toString()});}catch(p){throw new a("network_error","PAR request failed",{cause:p instanceof Error?p:void 0})}if(!o.ok){let p=o.data;throw new a("par_error","PAR request failed",{details:{status:o.status,error:p?.error,error_description:p?.error_description}})}let c=o.data;if(!c.request_uri)throw new a("par_error","PAR response missing request_uri");if(typeof c.expires_in!="number")throw new a("par_error","PAR response missing or invalid expires_in");let u=Math.floor(Date.now()/1e3)+c.expires_in;return {requestUri:c.request_uri,expiresAt:u}}buildAuthorizationUrlWithPar(e,t){let r=new URLSearchParams;return r.set("client_id",this.clientId),r.set("request_uri",t),`${e.authorization_endpoint}?${r.toString()}`}};var Te=5,M=class{constructor(e,t){this.http=e;this.clientId=t;}async startDeviceAuthorization(e,t){let r=e.device_authorization_endpoint;if(!r)throw new a("no_device_authorization_endpoint","Device authorization endpoint not available in discovery document");let n=new URLSearchParams({client_id:this.clientId});if(t?.scope&&n.set("scope",t.scope),t?.extraParams){let u=new Set(["client_id","scope"]);for(let[p,d]of Object.entries(t.extraParams))u.has(p.toLowerCase())||n.set(p,d);}let i;try{i=await this.http.fetch(r,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n.toString()});}catch(u){throw new a("network_error","Device authorization request failed",{cause:u instanceof Error?u:void 0})}if(!i.ok){let u=i.data;throw new a("device_authorization_error","Device authorization request failed",{details:{status:i.status,error:u?.error,error_description:u?.error_description}})}let o=i.data;if(!o.device_code||!o.user_code||!o.verification_uri)throw new a("device_authorization_error","Invalid device authorization response: missing required fields");let l=Math.floor(Date.now()/1e3)+o.expires_in;return {deviceCode:o.device_code,userCode:o.user_code,verificationUri:o.verification_uri,verificationUriComplete:o.verification_uri_complete,expiresAt:l,interval:o.interval??Te}}async pollOnce(e,t){let r=Math.floor(Date.now()/1e3);if(r>=t.expiresAt)return {status:"expired"};let n=e.token_endpoint,i=new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:t.deviceCode,client_id:this.clientId}),o;try{o=await this.http.fetch(n,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i.toString()});}catch(p){throw new a("network_error","Device flow token request failed",{cause:p instanceof Error?p:void 0})}if(!o.ok){let p=o.data,d=p?.error;switch(d){case "authorization_pending":return {status:"pending",retryAfter:t.interval};case "slow_down":return {status:"slow_down",retryAfter:t.interval+5};case "expired_token":return {status:"expired"};case "access_denied":return {status:"access_denied"};default:throw new a("device_authorization_error","Device flow token request failed",{details:{status:o.status,error:d,error_description:p?.error_description}})}}let c=o.data,l=c.expires_in?r+c.expires_in:r+3600;return {status:"completed",tokens:{accessToken:c.access_token,tokenType:c.token_type??"Bearer",expiresAt:l,refreshToken:c.refresh_token,idToken:c.id_token,scope:c.scope}}}async pollUntilComplete(e,t,r){let n=t.interval;for(;;){if(r?.signal?.aborted)throw new a("device_authorization_error","Device flow polling aborted");let i=await this.pollOnce(e,t);switch(i.status){case "completed":return i.tokens;case "pending":await this.sleep(i.retryAfter*1e3,r?.signal);continue;case "slow_down":n=i.retryAfter,t.interval=n,await this.sleep(n*1e3,r?.signal);continue;case "expired":throw new a("device_authorization_expired","Device authorization has expired. Please start a new authorization.");case "access_denied":throw new a("device_access_denied","User denied the device authorization request")}}}sleep(e,t){return new Promise((r,n)=>{let i=setTimeout(r,e);t&&t.addEventListener("abort",()=>{clearTimeout(i),n(new a("device_authorization_error","Device flow polling aborted"));},{once:true});})}};var L=class{constructor(e,t){this.keyPair=null;this.serverNonce=null;this.crypto=e,this.config=t??{};}async initialize(){if(!this.crypto.generateDPoPKeyPair)throw new a("dpop_key_generation_error","CryptoProvider does not support DPoP key generation");if(this.crypto.getDPoPKeyPair){let e=await this.crypto.getDPoPKeyPair();if(e){this.keyPair=e;return}}try{this.keyPair=await this.crypto.generateDPoPKeyPair(this.config.algorithm??"ES256");}catch(e){throw new a("dpop_key_generation_error","Failed to generate DPoP key pair",{cause:e instanceof Error?e:void 0})}}isInitialized(){return this.keyPair!==null}async generateProof(e,t,r){if(!this.keyPair)throw new a("dpop_proof_generation_error","DPoP manager not initialized. Call initialize() first.");let n=new URL(t),i=`${n.protocol}//${n.host}${n.pathname}`,o={typ:"dpop+jwt",alg:this.keyPair.algorithm,jwk:this.keyPair.publicKeyJwk},c=Math.floor(Date.now()/1e3),l={jti:this.generateJti(),htm:e.toUpperCase(),htu:i,iat:c};r?.accessTokenHash&&(l.ath=r.accessTokenHash),(r?.nonce??this.serverNonce)&&(l.nonce=r?.nonce??this.serverNonce??void 0);try{let u=F(JSON.stringify(o)),p=F(JSON.stringify(l)),d=`${u}.${p}`,h=await this.keyPair.sign(new TextEncoder().encode(d)),y=f(h);return `${d}.${y}`}catch(u){throw new a("dpop_proof_generation_error","Failed to generate DPoP proof",{cause:u instanceof Error?u:void 0})}}handleNonceResponse(e){this.serverNonce=e;}getServerNonce(){return this.serverNonce}clearServerNonce(){this.serverNonce=null;}getPublicKeyJwk(){return this.keyPair?.publicKeyJwk??null}getThumbprint(){return this.keyPair?.thumbprint??null}async calculateAccessTokenHash(e){let t=await this.crypto.sha256(e);return f(t)}async clear(){this.crypto.clearDPoPKeyPair&&await this.crypto.clearDPoPKeyPair(),this.keyPair=null,this.serverNonce=null;}generateJti(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).substring(2,15)}`}};var Y={access_token:"urn:ietf:params:oauth:token-type:access_token",refresh_token:"urn:ietf:params:oauth:token-type:refresh_token",id_token:"urn:ietf:params:oauth:token-type:id_token"};var _=class _{constructor(e){this.refreshPromise=null;this.discovery=null;this.expiringTimeout=null;this.isLeaderTab=true;this.currentOperationId=null;this.http=e.http,this.storage=e.storage,this.clientId=e.clientId,this.issuerHash=e.issuerHash,this.clientIdHash=e.clientIdHash,this.refreshSkewSeconds=e.refreshSkewSeconds??_.DEFAULT_REFRESH_SKEW_SECONDS,this.eventEmitter=e.eventEmitter,this.expiringThresholdMs=(e.expiringThresholdSeconds??_.DEFAULT_EXPIRING_THRESHOLD_SECONDS)*1e3,this.expiringJitterMs=e.expiringJitterMs??_.DEFAULT_EXPIRING_JITTER_MS;}setDiscovery(e){this.discovery=e;}get tokenKey(){return m.tokens(this.issuerHash,this.clientIdHash)}get idTokenKey(){return m.idToken(this.issuerHash,this.clientIdHash)}async getTokens(){let e=await this.storage.get(this.tokenKey);if(!e)return null;try{return JSON.parse(e)}catch{return await this.clearTokens(),null}}async saveTokens(e){await this.storage.set(this.tokenKey,JSON.stringify(e)),e.idToken&&await this.storage.set(this.idTokenKey,e.idToken),this.scheduleExpiringEvent(e.expiresAt);}scheduleExpiringEvent(e){if(this.expiringTimeout&&(clearTimeout(this.expiringTimeout),this.expiringTimeout=null),!this.isLeaderTab)return;let t=e*1e3,r=t-this.expiringThresholdMs,n=Math.random()*this.expiringJitterMs*2-this.expiringJitterMs,i=r-Date.now()+n;i>0&&(this.expiringTimeout=setTimeout(()=>{let o=Date.now(),c=Math.max(0,Math.floor((t-o)/1e3));this.eventEmitter?.emit("token:expiring",{expiresAt:e,expiresIn:c,timestamp:o,source:"core"});},i));}setLeaderTab(e){this.isLeaderTab=e,!e&&this.expiringTimeout&&(clearTimeout(this.expiringTimeout),this.expiringTimeout=null);}setOperationId(e){this.currentOperationId=e;}getOperationId(){return this.currentOperationId}async clearTokens(){await this.storage.remove(this.tokenKey),await this.storage.remove(this.idTokenKey);}async getAccessToken(){let e=await this.getTokens();if(!e)throw new a("no_tokens","No tokens available. Please authenticate first.");if(this.shouldRefresh(e)){if(!e.refreshToken)throw new a("token_expired","Access token expired and no refresh token available");return this.refreshWithLock(e.refreshToken)}return e.accessToken}async getIdToken(){return (await this.getTokens())?.idToken??null}shouldRefresh(e){let t=Math.floor(Date.now()/1e3);return e.expiresAt-this.refreshSkewSeconds<=t}async refreshWithLock(e,t="on_demand"){if(this.refreshPromise)return (await this.refreshPromise).accessToken;this.refreshPromise=this.doRefreshWithRetry(e,t);try{return (await this.refreshPromise).accessToken}finally{this.refreshPromise=null;}}async refresh(){let e=await this.getTokens();if(!e?.refreshToken)throw new a("no_tokens","No refresh token available");if(this.refreshPromise)return this.refreshPromise;this.refreshPromise=this.doRefreshWithRetry(e.refreshToken,"manual");try{return await this.refreshPromise}finally{this.refreshPromise=null;}}async doRefreshWithRetry(e,t="on_demand",r=0){let i=Date.now();r===0&&this.eventEmitter?.emit("token:refreshing",{reason:t,timestamp:i,source:"core",operationId:this.currentOperationId??void 0});try{return await this.doRefresh(e)}catch(o){let c=o instanceof a?o:new a("refresh_error","Token refresh failed",{cause:o instanceof Error?o:void 0}),l=r<1&&w(c);if(this.eventEmitter?.emit("token:refresh:failed",{error:c,willRetry:l,attempt:r,timestamp:Date.now(),source:"core",operationId:this.currentOperationId??void 0}),l)return this.doRefreshWithRetry(e,t,r+1);throw w(c)||this.eventEmitter?.emit("auth:required",{reason:"refresh_failed",timestamp:Date.now(),source:"core",operationId:this.currentOperationId??void 0}),o}}async doRefresh(e){if(!this.discovery)throw new a("no_discovery","Discovery document not set");let t=this.discovery.token_endpoint,r=new URLSearchParams({grant_type:"refresh_token",client_id:this.clientId,refresh_token:e}),n;try{n=await this.http.fetch(t,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:r.toString()});}catch(u){let p=new a("network_error","Token refresh request failed",{cause:u instanceof Error?u:void 0});throw this.eventEmitter?.emit("token:error",{error:p,context:"refresh",timestamp:Date.now(),source:"core"}),this.eventEmitter&&A(this.eventEmitter,p,{context:"refresh"}),p}if(!n.ok){let u=n.data,p=new a("refresh_error","Token refresh failed",{details:{status:n.status,error:u?.error,error_description:u?.error_description}});throw this.eventEmitter?.emit("token:error",{error:p,context:"refresh",timestamp:Date.now(),source:"core"}),this.eventEmitter&&A(this.eventEmitter,p,{context:"refresh"}),p}let i=n.data,o=Math.floor(Date.now()/1e3),c=i.expires_in?o+i.expires_in:o+3600,l={accessToken:i.access_token,tokenType:i.token_type??"Bearer",expiresAt:c,refreshToken:i.refresh_token??e,idToken:i.id_token,scope:i.scope};return await this.saveTokens(l),this.eventEmitter?.emit("token:refreshed",{hasAccessToken:!!l.accessToken,hasRefreshToken:!!l.refreshToken,hasIdToken:!!l.idToken,expiresAt:l.expiresAt,timestamp:Date.now(),source:"core",operationId:this.currentOperationId??void 0}),l}async isAuthenticated(){let e=await this.getTokens();if(!e)return false;let t=Math.floor(Date.now()/1e3);return e.expiresAt<=t?!!e.refreshToken:true}async exchangeToken(e){if(!this.discovery)throw new a("no_discovery","Discovery document not set");let t=this.discovery.token_endpoint,r=this.mapTokenTypeToUri(e.subjectTokenType??"access_token"),n=new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:token-exchange",client_id:this.clientId,subject_token:e.subjectToken,subject_token_type:r});e.audience&&n.set("audience",e.audience),e.scope&&n.set("scope",e.scope),e.requestedTokenType&&n.set("requested_token_type",this.mapTokenTypeToUri(e.requestedTokenType)),e.actorToken&&(n.set("actor_token",e.actorToken),e.actorTokenType&&n.set("actor_token_type",this.mapTokenTypeToUri(e.actorTokenType)));let i;try{i=await this.http.fetch(t,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n.toString()});}catch(d){let h=new a("network_error","Token exchange request failed",{cause:d instanceof Error?d:void 0});throw this.eventEmitter?.emit("token:error",{error:h,context:"exchange",timestamp:Date.now(),source:"core"}),this.eventEmitter&&A(this.eventEmitter,h,{context:"exchange"}),h}if(!i.ok){let d=i.data,h=new a("token_exchange_error","Token exchange failed",{details:{status:i.status,error:d?.error,error_description:d?.error_description}});throw this.eventEmitter?.emit("token:error",{error:h,context:"exchange",timestamp:Date.now(),source:"core"}),this.eventEmitter&&A(this.eventEmitter,h,{context:"exchange"}),h}let o=i.data,c=Math.floor(Date.now()/1e3),l=o.expires_in?c+o.expires_in:c+3600,u={accessToken:o.access_token,tokenType:o.token_type??"Bearer",expiresAt:l,refreshToken:o.refresh_token,idToken:o.id_token,scope:o.scope},p={tokens:u,issuedTokenType:o.issued_token_type};return this.eventEmitter?.emit("token:exchanged",{hasAccessToken:!!u.accessToken,hasRefreshToken:!!u.refreshToken,issuedTokenType:o.issued_token_type,timestamp:Date.now(),source:"core",operationId:this.currentOperationId??void 0}),p}mapTokenTypeToUri(e){return Y[e]}destroy(){this.expiringTimeout&&(clearTimeout(this.expiringTimeout),this.expiringTimeout=null);}};_.DEFAULT_REFRESH_SKEW_SECONDS=30,_.DEFAULT_EXPIRING_THRESHOLD_SECONDS=300,_.DEFAULT_EXPIRING_JITTER_MS=3e4;var H=_;var U=class{constructor(e){this.http=e.http,this.clientId=e.clientId;}async introspect(e,t){let r=e.introspection_endpoint;if(!r)throw new a("no_introspection_endpoint","Authorization server does not support token introspection");return this.introspectWithEndpoint(r,t)}async introspectWithEndpoint(e,t){let r=new URLSearchParams({client_id:this.clientId,token:t.token});t.tokenTypeHint&&r.set("token_type_hint",t.tokenTypeHint);let n;try{n=await this.http.fetch(e,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:r.toString()});}catch(i){throw new a("network_error","Token introspection request failed",{cause:i instanceof Error?i:void 0})}if(!n.ok){let i=n.data;throw new a("introspection_error","Token introspection failed",{details:{status:n.status,error:i?.error,error_description:i?.error_description}})}return n.data}async isActive(e,t){return (await this.introspect(e,{token:t})).active}};var k=class{constructor(e){this.http=e.http,this.clientId=e.clientId;}async revoke(e,t){let r=e.revocation_endpoint;if(!r)throw new a("no_revocation_endpoint","Authorization server does not support token revocation");let n=new URLSearchParams({client_id:this.clientId,token:t.token});t.tokenTypeHint&&n.set("token_type_hint",t.tokenTypeHint);let i;try{i=await this.http.fetch(r,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n.toString()});}catch(c){throw new a("network_error","Token revocation request failed",{cause:c instanceof Error?c:void 0})}if(i.ok)return;let o=i.data;throw new a("revocation_error","Token revocation failed",{details:{status:i.status,error:o?.error,error_description:o?.error_description}})}async revokeWithEndpoint(e,t){let r=new URLSearchParams({client_id:this.clientId,token:t.token});t.tokenTypeHint&&r.set("token_type_hint",t.tokenTypeHint);let n;try{n=await this.http.fetch(e,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:r.toString()});}catch(o){throw new a("network_error","Token revocation request failed",{cause:o instanceof Error?o:void 0})}if(n.ok)return;let i=n.data;throw new a("revocation_error","Token revocation failed",{details:{status:n.status,error:i?.error,error_description:i?.error_description}})}};var j=class{constructor(e){this.storage=e.storage,this.clientId=e.clientId,this.issuerHash=e.issuerHash,this.clientIdHash=e.clientIdHash,this.eventEmitter=e.eventEmitter,this.endpoints=e.endpoints,this.tokenRevoker=new k({http:e.http,clientId:e.clientId});}async logout(e,t){let r=await this.getStoredIdToken(),n=await this.getStoredTokens(),i;t?.revokeTokens&&e?.revocation_endpoint&&n&&(i=await this.revokeTokens(e,n)),await this.clearTokens(),this.eventEmitter?.emit("session:ended",{reason:"logout",timestamp:Date.now(),source:"core"});let o;if(this.endpoints?.endSession!==void 0?o=this.endpoints.endSession:e&&(o=e.end_session_endpoint),!o)return {localOnly:true,revocation:i};let c=t?.idTokenHint??r,l=new URLSearchParams({client_id:this.clientId});return c&&l.set("id_token_hint",c),t?.postLogoutRedirectUri&&l.set("post_logout_redirect_uri",t.postLogoutRedirectUri),t?.state&&l.set("state",t.state),{logoutUrl:`${o}?${l.toString()}`,localOnly:false,revocation:i}}async revokeTokens(e,t){let r={attempted:true};try{t.refreshToken&&(await this.tokenRevoker.revoke(e,{token:t.refreshToken,tokenTypeHint:"refresh_token"}),r.refreshTokenRevoked=!0),await this.tokenRevoker.revoke(e,{token:t.accessToken,tokenTypeHint:"access_token"}),r.accessTokenRevoked=!0;}catch(n){r.error=n instanceof Error?n:new Error(String(n));}return r}async clearTokens(){let e=m.tokens(this.issuerHash,this.clientIdHash),t=m.idToken(this.issuerHash,this.clientIdHash);await this.storage.remove(e),await this.storage.remove(t);}async getStoredIdToken(){let e=m.idToken(this.issuerHash,this.clientIdHash);return this.storage.get(e)}async getStoredTokens(){let e=m.tokens(this.issuerHash,this.clientIdHash),t=await this.storage.get(e);if(!t)return null;try{return JSON.parse(t)}catch{return null}}};var q=class{constructor(e){this.http=e.http;}async checkSession(e,t){let r=e.userinfo_endpoint;if(!r)return {valid:false,error:new a("no_userinfo_endpoint","UserInfo endpoint not available")};try{let n=await this.http.fetch(r,{method:"GET",headers:{Authorization:`Bearer ${t}`}});return n.ok?{valid:!0,user:n.data}:n.status===401?{valid:!1,error:new a("session_expired","Session has expired")}:{valid:!1,error:new a("session_check_failed","Session check failed",{details:{status:n.status}})}}catch(n){return {valid:false,error:new a("network_error","Failed to check session",{cause:n instanceof Error?n:void 0})}}}async getUserInfo(e,t){let r=e.userinfo_endpoint;if(!r)throw new a("no_userinfo_endpoint","UserInfo endpoint not available");let n;try{n=await this.http.fetch(r,{method:"GET",headers:{Authorization:`Bearer ${t}`}});}catch(i){throw new a("network_error","Failed to fetch user info",{cause:i instanceof Error?i:void 0})}if(!n.ok)throw new a("userinfo_error","Failed to get user info",{details:{status:n.status}});return n.data}};var z=class{constructor(e){this.discovery=null;this.tokenManager=e.tokenManager,this.tokenApiClient=e.tokenApiClient;}setDiscovery(e){this.discovery=e;}async isAuthenticated(){return this.tokenManager.isAuthenticated()}async checkSession(){if(!this.discovery)return {valid:false,error:new a("no_discovery","Discovery document not available")};try{let e=await this.tokenManager.getAccessToken();return this.tokenApiClient.checkSession(this.discovery,e)}catch(e){return e instanceof a?{valid:false,error:e}:{valid:false,error:new a("session_check_failed","Failed to check session",{cause:e instanceof Error?e:void 0})}}}async getUser(){if(!this.discovery)throw new a("no_discovery","Discovery document not available");let e=await this.tokenManager.getAccessToken();return this.tokenApiClient.getUserInfo(this.discovery,e)}};async function pe(s,e,t=16){let r=await s.sha256(e);return f(r).slice(0,t)}var K=class{constructor(e){this.dpopManager=null;this.initialized=false;this.config=$(e),this.normalizedIssuer=T(e.issuer),this.events=new b,this.discoveryClient=new x({http:this.config.http,cacheTtlMs:this.config.discoveryCacheTtlMs}),this.pkce=new S(this.config.crypto),this.authCodeFlow=new I(this.config.http,this.config.clientId),this.parClient=new O(this.config.http,this.config.clientId),this.deviceFlowClient=new M(this.config.http,this.config.clientId);}get eventEmitter(){return this.events}async initialize(){if(this.initialized)return;let e=this.config.hashOptions.hashLength;this.issuerHash=await pe(this.config.crypto,this.normalizedIssuer,e),this.clientIdHash=await pe(this.config.crypto,this.config.clientId,e),this.stateManager=new D(this.config.crypto,this.config.storage,this.issuerHash,this.clientIdHash),this.tokenManager=new H({http:this.config.http,storage:this.config.storage,clientId:this.config.clientId,issuerHash:this.issuerHash,clientIdHash:this.clientIdHash,refreshSkewSeconds:this.config.refreshSkewSeconds,eventEmitter:this.events}),this.logoutHandler=new j({storage:this.config.storage,http:this.config.http,clientId:this.config.clientId,issuerHash:this.issuerHash,clientIdHash:this.clientIdHash,eventEmitter:this.events,endpoints:this.config.endpoints}),this.tokenIntrospector=new U({http:this.config.http,clientId:this.config.clientId}),this.tokenRevoker=new k({http:this.config.http,clientId:this.config.clientId});let t=new q({http:this.config.http});this.sessionManager=new z({tokenManager:this.tokenManager,tokenApiClient:t}),await this.stateManager.cleanupExpiredStates(),this.initialized=true;}ensureInitialized(){if(!this.initialized)throw new a("not_initialized","Client not initialized. Use createAuthrimClient().")}async discover(){let e=await this.discoveryClient.discover(this.normalizedIssuer);return this.tokenManager.setDiscovery(e),this.sessionManager.setDiscovery(e),e}async buildAuthorizationUrl(e){this.ensureInitialized();let t=await this.discover(),r=await this.pkce.generatePKCE(),n=e.scope??"openid profile",i=await this.stateManager.generateAuthState({redirectUri:e.redirectUri,codeVerifier:r.codeVerifier,scope:n,ttlSeconds:this.config.stateTtlSeconds}),o=this.authCodeFlow.buildAuthorizationUrl(t,i,r,e);return this.events.emit("auth:redirecting",{url:o.url,timestamp:Date.now(),source:"core",operationId:i.operationId}),o}async handleCallback(e){this.ensureInitialized();let{code:t,state:r}=this.authCodeFlow.parseCallback(e),n=await this.stateManager.validateAndConsumeState(r),i=n.operationId;this.events.emit("auth:callback",{code:t,state:r,timestamp:Date.now(),source:"core",operationId:i}),this.events.emit("auth:callback:processing",{state:r,timestamp:Date.now(),source:"core",operationId:i});try{let o=await this.discover(),c=await this.authCodeFlow.exchangeCode(o,{code:t,state:r,redirectUri:n.redirectUri,codeVerifier:n.codeVerifier,nonce:n.nonce,scope:n.scope});return await this.tokenManager.saveTokens(c),this.events.emit("auth:callback:complete",{success:!0,timestamp:Date.now(),source:"core",operationId:i}),c}catch(o){throw this.events.emit("auth:callback:complete",{success:false,timestamp:Date.now(),source:"core",operationId:i}),o}}get par(){return {push:async e=>{this.ensureInitialized();let t=await this.discover(),r=await this.pkce.generatePKCE(),n=e.scope??"openid profile",i=await this.stateManager.generateAuthState({redirectUri:e.redirectUri,codeVerifier:r.codeVerifier,scope:n,ttlSeconds:this.config.stateTtlSeconds});return this.parClient.pushAuthorizationRequest(t,{redirectUri:e.redirectUri,scope:n,state:i.state,nonce:i.nonce,codeChallenge:r.codeChallenge,codeChallengeMethod:"S256",prompt:e.prompt,loginHint:e.loginHint,acrValues:e.acrValues,extraParams:e.extraParams})},buildAuthorizationUrl:async e=>{let t=await this.discover();return this.parClient.buildAuthorizationUrlWithPar(t,e)},isAvailable:async()=>!!(await this.discover()).pushed_authorization_request_endpoint,isRequired:async()=>(await this.discover()).require_pushed_authorization_requests===true}}get deviceFlow(){return {start:async e=>{this.ensureInitialized();let t=await this.discover();return this.deviceFlowClient.startDeviceAuthorization(t,e)},pollOnce:async e=>{let t=await this.discover();return this.deviceFlowClient.pollOnce(t,e)},pollUntilComplete:async(e,t)=>{let r=await this.discover(),n=await this.deviceFlowClient.pollUntilComplete(r,e,t);return await this.tokenManager.saveTokens(n),n},isAvailable:async()=>!!(await this.discover()).device_authorization_endpoint}}get dpop(){if(!this.config.crypto.generateDPoPKeyPair)return;this.dpopManager||(this.dpopManager=new L(this.config.crypto));let t=this.dpopManager;return {initialize:()=>t.initialize(),isInitialized:()=>t.isInitialized(),generateProof:(r,n,i)=>t.generateProof(r,n,i),handleNonceResponse:r=>t.handleNonceResponse(r),calculateAccessTokenHash:r=>t.calculateAccessTokenHash(r),getPublicKeyJwk:()=>t.getPublicKeyJwk(),getThumbprint:()=>t.getThumbprint(),clear:()=>t.clear(),isServerSupported:async()=>{let r=await this.discover();return Array.isArray(r.dpop_signing_alg_values_supported)&&r.dpop_signing_alg_values_supported.length>0}}}get token(){return this.ensureInitialized(),{getAccessToken:()=>this.tokenManager.getAccessToken(),getTokens:()=>this.tokenManager.getTokens(),getIdToken:()=>this.tokenManager.getIdToken(),isAuthenticated:()=>this.tokenManager.isAuthenticated(),exchange:async e=>(await this.discover(),this.tokenManager.exchangeToken(e)),introspect:async e=>{let t=await this.discover();return this.tokenIntrospector.introspect(t,e)},revoke:async e=>{let t=await this.discover();return this.tokenRevoker.revoke(t,e)}}}get session(){return this.ensureInitialized(),{isAuthenticated:()=>this.sessionManager.isAuthenticated(),check:()=>this.sessionManager.checkSession()}}async isAuthenticated(){return this.ensureInitialized(),this.tokenManager.isAuthenticated()}async getUser(){return this.ensureInitialized(),this.sessionManager.getUser()}async logout(e){this.ensureInitialized();let t=null;try{t=await this.discover();}catch{}return this.logoutHandler.logout(t,e)}on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}off(e,t){this.events.off(e,t);}};async function Ee(s){let e=new K(s);return await e.initialize(),e}var he=new Set(["login_required","interaction_required","consent_required","account_selection_required"]),X=class{constructor(e){this.clientId=e;}buildSilentAuthUrl(e,t,r,n){let i=e.authorization_endpoint,o=new URLSearchParams;o.set("client_id",this.clientId),o.set("response_type",n.responseType??"code"),o.set("redirect_uri",n.redirectUri),o.set("state",t.state),o.set("nonce",t.nonce),o.set("prompt","none"),o.set("code_challenge",r.codeChallenge),o.set("code_challenge_method",r.codeChallengeMethod);let c=n.scope??"openid";if(o.set("scope",c),n.loginHint&&o.set("login_hint",n.loginHint),n.idTokenHint&&o.set("id_token_hint",n.idTokenHint),n.extraParams){let p=new Set(["client_id","response_type","redirect_uri","state","nonce","code_challenge","code_challenge_method","scope","prompt"]);for(let[d,h]of Object.entries(n.extraParams))p.has(d.toLowerCase())||o.set(d,h);}let u={url:`${i}?${o.toString()}`};return n.exposeState&&(u.state=t.state,u.nonce=t.nonce),u}parseSilentAuthResponse(e){let t;e.includes("?")?t=(e.startsWith("http")?new URL(e):new URL(e,"https://dummy.local")).searchParams:t=new URLSearchParams(e);let r=t.get("error");if(r){let o=t.get("error_description"),c=this.mapSilentAuthError(r);return {success:false,error:new a(c,o??this.getDefaultErrorMessage(r),{details:{error:r,error_description:o,error_uri:t.get("error_uri")}})}}let n=t.get("code"),i=t.get("state");return n?i?{success:true,code:n,state:i}:{success:false,error:new a("missing_state","State parameter not found in silent auth response")}:{success:false,error:new a("missing_code","Authorization code not found in silent auth response")}}isInteractiveLoginRequired(e){return he.has(e.code)}mapSilentAuthError(e){return he.has(e)?e:"oauth_error"}getDefaultErrorMessage(e){switch(e){case "login_required":return "User must log in - no active session found";case "interaction_required":return "User interaction required";case "consent_required":return "User consent required";case "account_selection_required":return "User must select an account";default:return "Silent authentication failed"}}};async function Z(s,e,t){let r={},n={};switch(s.method){case "client_secret_basic":{let i=btoa(`${e}:${s.clientSecret}`);r.Authorization=`Basic ${i}`;break}case "client_secret_post":{n.client_id=e,n.client_secret=s.clientSecret;break}case "private_key_jwt":{let i=Math.floor(Date.now()/1e3),o={iss:e,sub:e,aud:t,jti:Re(),exp:i+300,iat:i},c;try{c=await s.signJwt(o);}catch(l){throw new a("invalid_client_authentication","Failed to sign client assertion JWT",{cause:l instanceof Error?l:void 0})}n.client_id=e,n.client_assertion_type="urn:ietf:params:oauth:client-assertion-type:jwt-bearer",n.client_assertion=c;break}case "none":{if(!("dangerouslyAllowInsecure"in s)||s.dangerouslyAllowInsecure!==true)throw new a("insecure_client_auth",'Client authentication method "none" requires dangerouslyAllowInsecure: true');n.client_id=e;break}default:{let i=s;throw new a("invalid_client_authentication",`Unknown client authentication method: ${i.method}`)}}return {headers:r,bodyParams:n}}function Re(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).substring(2,15)}`}var Q=class{constructor(e){this.http=e.http,this.clientId=e.clientId,this.credentials=e.credentials;}async getToken(e,t){let r=e.token_endpoint,{headers:n,bodyParams:i}=await Z(this.credentials,this.clientId,r),o=new URLSearchParams({grant_type:"client_credentials",...i});if(t?.scope&&o.set("scope",t.scope),t?.audience&&o.set("audience",t.audience),t?.extraParams){let y=new Set(["grant_type","client_id","client_secret","client_assertion","client_assertion_type","scope","audience"]);for(let[C,_e]of Object.entries(t.extraParams))y.has(C.toLowerCase())||o.set(C,_e);}let c={"Content-Type":"application/x-www-form-urlencoded",...n},l;try{l=await this.http.fetch(r,{method:"POST",headers:c,body:o.toString()});}catch(y){throw new a("network_error","Client credentials token request failed",{cause:y instanceof Error?y:void 0})}if(!l.ok){let y=l.data;throw new a("client_credentials_error","Client credentials token request failed",{details:{status:l.status,error:y?.error,error_description:y?.error_description}})}let u=l.data,p=Math.floor(Date.now()/1e3),d=u.expires_in?p+u.expires_in:p+3600;return {accessToken:u.access_token,tokenType:u.token_type??"Bearer",expiresAt:d,refreshToken:u.refresh_token,scope:u.scope}}};var ee=class{constructor(e){this.config=e;}async buildRequestObject(e){let t=Math.floor(Date.now()/1e3),r=this.config.lifetime??300,n={alg:this.config.algorithm??"RS256",typ:"oauth-authz-req+jwt"};this.config.keyId&&(n.kid=this.config.keyId);let i={iss:e.clientId,aud:e.issuer,response_type:e.responseType??"code",client_id:e.clientId,redirect_uri:e.redirectUri,scope:e.scope,state:e.state,nonce:e.nonce,code_challenge:e.codeChallenge,code_challenge_method:e.codeChallengeMethod,iat:t,exp:t+r,jti:this.generateJti()};if(e.prompt&&(i.prompt=e.prompt),e.loginHint&&(i.login_hint=e.loginHint),e.acrValues&&(i.acr_values=e.acrValues),e.extraClaims){let o=new Set(["iss","aud","response_type","client_id","redirect_uri","scope","state","nonce","code_challenge","code_challenge_method","iat","exp","jti","nbf"]);for(let[c,l]of Object.entries(e.extraClaims))o.has(c)||(i[c]=l);}try{return await this.config.signJwt(n,i)}catch(o){throw new a("jar_signing_error","Failed to sign JAR request object",{cause:o instanceof Error?o:void 0})}}generateJti(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).substring(2,15)}`}};function Ce(s){return s.require_signed_request_object===true}var te=class{constructor(e){this.config=e;}async validateResponse(e,t,r){let n=r.clockSkewSeconds??60,i;try{i=await this.config.verifyJwt(t,e.issuer);}catch(l){throw new a("jarm_signature_invalid","Failed to verify JARM response signature",{cause:l instanceof Error?l:void 0})}if(i.iss!==e.issuer)throw new a("jarm_validation_error","JARM response issuer does not match discovery issuer",{details:{expected:e.issuer,actual:i.iss}});if(!(Array.isArray(i.aud)?i.aud:[i.aud]).includes(r.clientId))throw new a("jarm_validation_error","JARM response audience does not match client_id",{details:{expected:r.clientId,actual:i.aud}});let c=Math.floor(Date.now()/1e3);if(i.exp&&i.exp+n<c)throw new a("jarm_validation_error","JARM response has expired");if(i.iat&&i.iat-n>c)throw new a("jarm_validation_error","JARM response iat is in the future");if(i.error)throw new a("oauth_error",i.error_description??i.error,{details:{error:i.error,error_description:i.error_description,error_uri:i.error_uri}});if(!i.state)throw new a("jarm_validation_error","JARM response is missing state claim");if(!v(i.state,r.expectedState))throw new a("jarm_validation_error","JARM response state does not match expected state");if(!i.code)throw new a("jarm_validation_error","JARM response is missing authorization code");return {code:i.code,state:i.state}}static extractResponseFromCallback(e){let t;return e.includes("?")?t=(e.startsWith("http")?new URL(e):new URL(e,"https://dummy.local")).searchParams:t=new URLSearchParams(e),t.get("response")}};var R=class R{constructor(e){this.tokenManager=null;this.checkInterval=null;this.abortController=null;this.isRunning=false;this.options={thresholdSeconds:e?.thresholdSeconds??R.DEFAULT_THRESHOLD_SECONDS,checkIntervalMs:e?.checkIntervalMs??R.DEFAULT_CHECK_INTERVAL_MS,eventEmitter:e?.eventEmitter};}start(e){this.isRunning||(this.tokenManager=e,this.abortController=new AbortController,this.isRunning=true,this.checkInterval=setInterval(()=>{this.checkAndRefresh().catch(()=>{});},this.options.checkIntervalMs),this.checkAndRefresh().catch(()=>{}));}stop(){this.isRunning&&(this.isRunning=false,this.checkInterval&&(clearInterval(this.checkInterval),this.checkInterval=null),this.abortController&&(this.abortController.abort(),this.abortController=null),this.tokenManager=null);}get running(){return this.isRunning}get signal(){return this.abortController?.signal??null}async checkAndRefresh(){if(!(!this.tokenManager||!this.isRunning))try{let e=await this.tokenManager.getTokens();if(!e)return;let t=Math.floor(Date.now()/1e3);e.expiresAt-t<=this.options.thresholdSeconds&&e.refreshToken&&await this.tokenManager.refresh();}catch{}}async forceCheck(){await this.checkAndRefresh();}};R.DEFAULT_THRESHOLD_SECONDS=60,R.DEFAULT_CHECK_INTERVAL_MS=3e4;var re=R;var ne=class{constructor(e){this.crypto=e.crypto;}async calculate(e){let t=e.salt;if(!t){let c=await this.crypto.randomBytes(16);t=f(c);}let r=e.clientId+" "+e.origin+" "+e.opBrowserState+t,n=await this.crypto.sha256(r),i=f(n);return {sessionState:i+"."+t,hash:i,salt:t}}async validate(e,t){let r=this.parse(e);if(!r)return false;let n=await this.calculate({...t,salt:r.salt});return v(n.sessionState,e)}parse(e){if(!e||typeof e!="string"||e.length>512)return null;let i=e.lastIndexOf(".");if(i===-1||i===0||i===e.length-1)return null;let o=e.substring(0,i),c=e.substring(i+1);if(!o||!c||o.length>256||c.length>128)return null;let l=/^[A-Za-z0-9_-]+$/;return !l.test(o)||!l.test(c)?null:{hash:o,salt:c}}};var ie=class{build(e,t){let r=new URL(e.logoutUri),n={};return e.includeIssuer&&t.iss&&(r.searchParams.set("iss",t.iss),n.iss=t.iss),e.includeSessionId&&t.sid&&(r.searchParams.set("sid",t.sid),n.sid=t.sid),{url:r.toString(),params:n}}parseParams(e){let t=typeof e=="string"?new URL(e):e,r={},n=t.searchParams.get("iss");n&&(r.iss=n);let i=t.searchParams.get("sid");return i&&(r.sid=i),r}validateRequest(e,t={}){let r;try{r=this.parseParams(e);}catch{return {valid:false,error:"Invalid URL format"}}return t.requireIss&&!r.iss?{valid:false,error:"Missing required iss parameter"}:t.requireSid&&!r.sid?{valid:false,error:"Missing required sid parameter"}:t.issuer&&r.iss&&!v(r.iss,t.issuer)?{valid:false,error:"Issuer validation failed"}:t.sessionId&&r.sid&&!v(r.sid,t.sessionId)?{valid:false,error:"Session ID validation failed"}:{valid:true,params:r}}};var xe=["accessToken","refreshToken","idToken","token","code","password","secret","credentials","authorization","bearer","codeVerifier","code_verifier","client_secret"],fe=["code","state","nonce","id_token","access_token","refresh_token","token"],B=class{constructor(e){this.entries=[];this.maxEvents=e?.maxEvents??100,this.redactLevel=e?.redactLevel??"default";}record(e,t,r){let n=r?.redact??this.redactLevel,i=this.redactData(t,n),o={type:e,timestamp:Date.now(),operationId:r?.operationId,data:i};for(this.entries.push(o);this.entries.length>this.maxEvents;)this.entries.shift();}getRecent(e){return e===void 0?[...this.entries]:this.entries.slice(-e)}getByOperationId(e){return this.entries.filter(t=>t.operationId===e)}getByType(e){return this.entries.filter(t=>t.type===e)}clear(){this.entries=[];}get length(){return this.entries.length}toJSON(){return JSON.stringify(this.entries,null,2)}setRedactLevel(e){this.redactLevel=e;}redactData(e,t){return t==="none"||e===void 0||e===null||typeof e!="object"?e:this.deepRedact(e,t)}deepRedact(e,t){let r={};for(let[n,i]of Object.entries(e)){let o=n.toLowerCase();if(this.isSensitiveKey(o)){let c=n.charAt(0).toUpperCase()+n.slice(1);r[`has${c}`]=i!=null,r[n]="[REDACTED]";continue}if(t==="aggressive"&&o==="url"&&typeof i=="string"){r[n]=this.redactUrl(i);continue}if(i!==null&&typeof i=="object"&&!Array.isArray(i)){r[n]=this.deepRedact(i,t);continue}if(Array.isArray(i)){r[n]=i.map(c=>c!==null&&typeof c=="object"?this.deepRedact(c,t):c);continue}r[n]=i;}return r}isSensitiveKey(e){return xe.some(t=>e===t.toLowerCase()||e.includes(t.toLowerCase()))}redactUrl(e){try{let t=new URL(e);for(let r of fe)t.searchParams.has(r)&&t.searchParams.set(r,"[REDACTED]");if(t.hash){let r=new URLSearchParams(t.hash.slice(1)),n=!1;for(let i of fe)r.has(i)&&(r.set(i,"[REDACTED]"),n=!0);n&&(t.hash="#"+r.toString());}return t.toString()}catch{return e.replace(/([?&])(code|token|state|nonce)=[^&]*/gi,"$1$2=[REDACTED]")}}};function oe(s){let e=s?.timestamps??false;return {log(t,r,n){let i=e?`[Authrim:${t.toUpperCase()} ${new Date().toISOString()}]`:`[Authrim:${t.toUpperCase()}]`,o=t==="debug"?"log":t,c=typeof console<"u"?console:null;c&&(n!==void 0?c[o]?.(i,r,n):c[o]?.(i,r));}}}var se={log(){}};function me(s){return s.enabled?s.logger?s.logger:oe({timestamps:s.logTimestamps}):se}var V=class{constructor(e,t){this.operationId=null;this.logger=e,this.verbose=t?.verbose??false;}setOperationId(e){this.operationId=e;}getOperationId(){return this.operationId}debug(e,t){this.verbose&&this.logger.log("debug",this.formatMessage(e),t);}info(e,t){this.logger.log("info",this.formatMessage(e),t);}warn(e,t){this.logger.log("warn",this.formatMessage(e),t);}error(e,t){this.logger.log("error",this.formatMessage(e),t);}formatMessage(e){return this.operationId?`[${this.operationId.slice(0,8)}] ${e}`:e}};async function be(s,e){let t=await e.sha256(s),r=t.slice(0,t.length/2);return f(r)}function Se(s,e){return new Promise((t,r)=>{let n=new a("operation_cancelled","Operation was cancelled");if(e.aborted){r(n);return}let i=()=>{r(n);};e.addEventListener("abort",i,{once:true}),s.then(t).catch(r).finally(()=>{e.removeEventListener("abort",i);});})}function Pe(s){let e=new AbortController;return {promise:s(e.signal),cancel:()=>e.abort(),signal:e.signal}}function ae(s){return s instanceof a&&s.code==="operation_cancelled"}async function De(s){try{let e=await Promise.race(s.map(t=>t.promise));return s.forEach(t=>t.cancel()),e}catch(e){throw s.forEach(t=>t.cancel()),e}}var Ie={maxRetries:3,baseDelayMs:1e3,maxDelayMs:3e4,jitter:true};function ye(s,e,t,r){let n=e*Math.pow(2,s),i=Math.min(n,t);if(r){let o=i*.5,c=Math.random()*o-o/2;return Math.max(0,Math.floor(i+c))}return i}function ge(s,e){return new Promise((t,r)=>{if(e?.aborted){r(new a("operation_cancelled","Sleep was cancelled"));return}let n=setTimeout(t,s);if(e){let i=()=>{clearTimeout(n),r(new a("operation_cancelled","Sleep was cancelled"));};e.addEventListener("abort",i,{once:true});}})}async function ve(s,e){let t={...Ie,...e},{maxRetries:r,baseDelayMs:n,maxDelayMs:i,jitter:o,signal:c,shouldRetry:l,onRetry:u}=t,p;for(let d=0;d<=r;d++)try{if(c?.aborted)throw new a("operation_cancelled","Operation was cancelled");return await s()}catch(h){if(p=h,ae(h))throw h;let y=l?l(h,d):h instanceof a&&w(h);if(d>=r||!y)throw h;let C=ye(d,n,i,o);u?.(h,d+1,C),await ge(C,c);}throw p}function Oe(s){return (e,t)=>ve(e,{...s,...t})}function Me(s){let e=s instanceof Headers?s.get("retry-after"):s["retry-after"]??s["Retry-After"];if(!e)return null;let t=parseInt(e,10);if(!isNaN(t))return t*1e3;let r=new Date(e);if(!isNaN(r.getTime())){let n=r.getTime()-Date.now();return Math.max(0,n)}return null}
|
|
2
|
+
exports.AuthorizationCodeFlow=I;exports.AuthrimClient=K;exports.AuthrimError=a;exports.AutoRefreshScheduler=re;exports.ClientCredentialsClient=Q;exports.DPoPManager=L;exports.DebugContext=V;exports.DeviceFlowClient=M;exports.DiscoveryClient=x;exports.EventEmitter=b;exports.EventTimeline=B;exports.FrontChannelLogoutUrlBuilder=ie;exports.JARBuilder=ee;exports.JARMValidator=te;exports.LogoutHandler=j;exports.PARClient=O;exports.PKCEHelper=S;exports.STORAGE_KEYS=m;exports.SessionManager=z;exports.SessionStateCalculator=ne;exports.SilentAuthHandler=X;exports.StateManager=D;exports.TOKEN_TYPE_URIS=Y;exports.TokenApiClient=q;exports.TokenIntrospector=U;exports.TokenManager=H;exports.TokenRevoker=k;exports.base64urlDecode=le;exports.base64urlEncode=f;exports.base64urlToString=J;exports.buildClientAuthentication=Z;exports.calculateBackoffDelay=ye;exports.calculateDsHash=be;exports.classifyError=W;exports.createAuthrimClient=Ee;exports.createCancellableOperation=Pe;exports.createConsoleLogger=oe;exports.createDebugLogger=me;exports.createRetryFunction=Oe;exports.decodeIdToken=de;exports.decodeJwt=ue;exports.emitClassifiedError=A;exports.getErrorMeta=ce;exports.getIdTokenNonce=G;exports.isCancellationError=ae;exports.isJarRequired=Ce;exports.isJwtExpired=Ae;exports.isRetryableError=w;exports.noopLogger=se;exports.normalizeIssuer=T;exports.parseRetryAfterHeader=Me;exports.raceWithCancellation=De;exports.resolveConfig=$;exports.sleep=ge;exports.stringToBase64url=F;exports.timingSafeEqual=v;exports.withAbortSignal=Se;exports.withRetry=ve;//# sourceMappingURL=index.cjs.map
|
|
3
3
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.d.cts
CHANGED
|
@@ -5060,5 +5060,61 @@ interface DirectAuthClient {
|
|
|
5060
5060
|
/** Session management */
|
|
5061
5061
|
session: SessionAuth;
|
|
5062
5062
|
}
|
|
5063
|
+
/**
|
|
5064
|
+
* Silent Login options for cross-domain SSO
|
|
5065
|
+
*
|
|
5066
|
+
* Executes prompt=none via top-level navigation to check IdP session.
|
|
5067
|
+
* Works with Safari ITP and Chrome Third-Party Cookie Phaseout.
|
|
5068
|
+
*/
|
|
5069
|
+
interface TrySilentLoginOptions {
|
|
5070
|
+
/**
|
|
5071
|
+
* Behavior when IdP has no session (login_required error)
|
|
5072
|
+
*
|
|
5073
|
+
* - 'return': Return to original page (show login button, etc.)
|
|
5074
|
+
* - 'login': Show login screen for user authentication
|
|
5075
|
+
*
|
|
5076
|
+
* Default: 'return'
|
|
5077
|
+
*/
|
|
5078
|
+
onLoginRequired?: 'return' | 'login';
|
|
5079
|
+
/**
|
|
5080
|
+
* Return URL (used for both success and return scenarios)
|
|
5081
|
+
* Default: current URL
|
|
5082
|
+
*/
|
|
5083
|
+
returnTo?: string;
|
|
5084
|
+
/**
|
|
5085
|
+
* OAuth scopes (if additional scopes are needed)
|
|
5086
|
+
*/
|
|
5087
|
+
scope?: string;
|
|
5088
|
+
}
|
|
5089
|
+
/**
|
|
5090
|
+
* Silent Login result (used in callback page)
|
|
5091
|
+
*
|
|
5092
|
+
* error values follow OIDC standard error codes:
|
|
5093
|
+
* - 'login_required': IdP has no session
|
|
5094
|
+
* - 'interaction_required': User interaction needed
|
|
5095
|
+
* - 'consent_required': Re-consent needed
|
|
5096
|
+
* - 'invalid_return_to': Invalid returnTo URL (SDK-specific)
|
|
5097
|
+
*/
|
|
5098
|
+
type SilentLoginResult = {
|
|
5099
|
+
status: 'success';
|
|
5100
|
+
} | {
|
|
5101
|
+
status: 'login_required';
|
|
5102
|
+
} | {
|
|
5103
|
+
status: 'error';
|
|
5104
|
+
error: string;
|
|
5105
|
+
errorDescription?: string;
|
|
5106
|
+
};
|
|
5107
|
+
/**
|
|
5108
|
+
* Silent Login state data (stored in state parameter)
|
|
5109
|
+
* @internal
|
|
5110
|
+
*/
|
|
5111
|
+
interface SilentLoginStateData {
|
|
5112
|
+
/** Type identifier: 'sl' = silent_login */
|
|
5113
|
+
t: 'sl';
|
|
5114
|
+
/** onLoginRequired: 'l' = login, 'r' = return */
|
|
5115
|
+
lr: 'l' | 'r';
|
|
5116
|
+
/** Return URL */
|
|
5117
|
+
rt: string;
|
|
5118
|
+
}
|
|
5063
5119
|
|
|
5064
|
-
export { type AddressClaim, type AttestationConveyancePreferenceType, type AuthCallbackCompleteEvent, type AuthCallbackEvent, type AuthCallbackProcessingEvent, type AuthFallbackEvent, type AuthInitEvent, type AuthLoginCompleteEvent, type AuthLogoutCompleteEvent, type AuthPopupBlockedEvent, type AuthRedirectingEvent, type AuthRequiredEvent, type AuthResult, type AuthState, type AuthStateSnapshot, type AuthState$1 as AuthStateType, type AuthenticationExtensionsClientInputsType, type AuthenticationResponseJSON, type AuthenticatorAssertionResponseJSON, type AuthenticatorAttachmentType, type AuthenticatorAttestationResponseJSON, type AuthenticatorSelectionCriteriaType, type AuthenticatorTransportType, AuthorizationCodeFlow, type AuthorizationContext, type AuthorizationUrlResult, AuthrimClient, type AuthrimClientConfig, AuthrimError, type AuthrimErrorCode, type AuthrimErrorMeta, type AuthrimErrorOptions, type AuthrimErrorRemediation, type AuthrimErrorSeverity, type AuthrimErrorUserAction, type AuthrimEventHandler, type AuthrimEventName, type AuthrimEvents, type AuthrimStorage, type AutoRefreshOptions, AutoRefreshScheduler, type BaseEventPayload, type BuildAuthorizationUrlOptions, type COSEAlgorithmIdentifier, type CheckSessionMessage, type CheckSessionResponse, type ClientAssertionClaims, type ClientAuthMethod, type ClientAuthResult, type ClientCredentials, ClientCredentialsClient, type ClientCredentialsClientOptions, type ClientCredentialsTokenOptions, type ClientSecretCredentials, type CodeChallengeMethod, type CoreEventName, type CryptoProvider, type DPoPCryptoProvider, type DPoPKeyPair, DPoPManager, type DPoPManagerConfig, type DPoPProofClaims, type DPoPProofHeader, type DPoPProofOptions, DebugContext, type DebugLogLevel, type DebugLogger, type DebugOptions, type DebugTimelineEvent, type DecodedJwt, type DeviceAuthorizationResponse, type DeviceFlowAccessDeniedResult, DeviceFlowClient, type DeviceFlowCompletedResult, type DeviceFlowExpiredResult, type DeviceFlowPendingResult, type DeviceFlowPollResult, type DeviceFlowSlowDownResult, type DeviceFlowStartOptions, type DeviceFlowState, type DirectAuthClient, type DirectAuthClientConfig, type DirectAuthError, type DirectAuthLogoutOptions, type DirectAuthTokenRequest, type DirectAuthTokenResponse, DiscoveryClient, type EmailCodeAuth, type EmailCodeSendOptions, type EmailCodeSendRequest, type EmailCodeSendResponse, type EmailCodeSendResult, type EmailCodeVerifyOptions, type EmailCodeVerifyRequest, type EmailCodeVerifyResponse, type EmitClassifiedErrorOptions, type EndpointOverrides, type ErrorClassification, type ErrorEvent, type ErrorEventEmitter, type ErrorEventPayload, type ErrorFatalEvent, type ErrorRecoverableEvent, type ErrorSeverity, EventEmitter, EventTimeline, type ExchangeCodeOptions, type FrontChannelLogoutBuildParams, type FrontChannelLogoutParams, FrontChannelLogoutUrlBuilder, type FrontChannelLogoutUrlOptions, type FrontChannelLogoutUrlResult, type FrontChannelLogoutValidationOptions, type FrontChannelLogoutValidationResult, type GenerateAuthStateOptions, type HashOptions, type HttpClient, type HttpOptions, type HttpResponse, type IntrospectTokenOptions, type IntrospectionResponse, type IntrospectionTokenTypeHint, JARBuilder, type JARBuilderConfig, type JARMResponseClaims, type JARMValidationOptions, type JARMValidationResult, JARMValidator, type JARMValidatorConfig, type JARRequestObjectClaims, type JARRequestOptions, type JWK, type JwtHeader, LogoutHandler, type LogoutHandlerOptions, type LogoutOptions, type LogoutResult, type LogoutTokenClaims, type MfaMethod, type NextAction, type NoClientCredentials, type OAuthErrorResponse, type OIDCDiscoveryDocument, PARClient, type PARClientOptions, type PARRequest, type PARResponse, type PARResult, PKCEHelper, type PKCEPair, type PasskeyAuth, type PasskeyCredential, type PasskeyLoginFinishRequest, type PasskeyLoginFinishResponse, type PasskeyLoginOptions, type PasskeyLoginStartRequest, type PasskeyLoginStartResponse, type PasskeyRegisterOptions, type PasskeySignUpOptions, type PasskeySignupFinishRequest, type PasskeySignupFinishResponse, type PasskeySignupStartRequest, type PasskeySignupStartResponse, type PrivateKeyJwtCredentials, type PublicKeyCredentialCreationOptionsJSON, type PublicKeyCredentialDescriptorJSON, type PublicKeyCredentialParametersType, type PublicKeyCredentialRequestOptionsJSON, type PublicKeyCredentialRpEntityType, type PublicKeyCredentialType, type PublicKeyCredentialUserEntityJSON, type RedactLevel, type RegistrationResponseJSON, type ResidentKeyRequirementType, type ResolvedConfig, type RetryOptions, type RevokeTokenOptions, STORAGE_KEYS, type Session, type SessionAuth, type SessionChangeEvent, type SessionChangedEvent, type SessionCheckResult, type SessionEndedEvent, type SessionLogoutBroadcastEvent, type SessionManagementConfig, SessionManager, type SessionManagerOptions, type SessionStartedEvent, type SessionState, SessionStateCalculator, type SessionStateCalculatorOptions, type SessionStateParams, type SessionStateResult, type SessionSyncEvent, SilentAuthHandler, type SilentAuthOptions, type SilentAuthResult, type SilentAuthUrlResult, type SocialAuth, type SocialLoginOptions, type SocialProvider, type StandardClaims, type StateChangeEvent, StateManager, TOKEN_TYPE_URIS, type TimelineEntry, TokenApiClient, type TokenApiClientOptions, type TokenErrorEvent, type TokenExchangeRequest, type TokenExchangeResponse, type TokenExchangeResult, type TokenExchangedEvent, type TokenExpiredEvent, type TokenExpiringEvent, TokenIntrospector, type TokenIntrospectorOptions, TokenManager, type TokenManagerOptions, type TokenRefreshFailedEvent, type TokenRefreshedEvent, type TokenRefreshingEvent, type TokenResponse, TokenRevoker, type TokenRevokerOptions, type TokenSet, type TokenTypeHint, type TokenTypeUri, type User, type UserInfo, type UserVerificationRequirementType, type WarningITPEvent, type WarningPrivateModeEvent, type WarningStorageFallbackEvent, type WebOnlyEventName, base64urlDecode, base64urlEncode, base64urlToString, buildClientAuthentication, calculateBackoffDelay, calculateDsHash, classifyError, createAuthrimClient, createCancellableOperation, createConsoleLogger, createDebugLogger, createRetryFunction, decodeIdToken, decodeJwt, emitClassifiedError, getErrorMeta, getIdTokenNonce, isCancellationError, isJarRequired, isJwtExpired, isRetryableError, noopLogger, normalizeIssuer, parseRetryAfterHeader, raceWithCancellation, resolveConfig, sleep, stringToBase64url, timingSafeEqual, withAbortSignal, withRetry };
|
|
5120
|
+
export { type AddressClaim, type AttestationConveyancePreferenceType, type AuthCallbackCompleteEvent, type AuthCallbackEvent, type AuthCallbackProcessingEvent, type AuthFallbackEvent, type AuthInitEvent, type AuthLoginCompleteEvent, type AuthLogoutCompleteEvent, type AuthPopupBlockedEvent, type AuthRedirectingEvent, type AuthRequiredEvent, type AuthResult, type AuthState, type AuthStateSnapshot, type AuthState$1 as AuthStateType, type AuthenticationExtensionsClientInputsType, type AuthenticationResponseJSON, type AuthenticatorAssertionResponseJSON, type AuthenticatorAttachmentType, type AuthenticatorAttestationResponseJSON, type AuthenticatorSelectionCriteriaType, type AuthenticatorTransportType, AuthorizationCodeFlow, type AuthorizationContext, type AuthorizationUrlResult, AuthrimClient, type AuthrimClientConfig, AuthrimError, type AuthrimErrorCode, type AuthrimErrorMeta, type AuthrimErrorOptions, type AuthrimErrorRemediation, type AuthrimErrorSeverity, type AuthrimErrorUserAction, type AuthrimEventHandler, type AuthrimEventName, type AuthrimEvents, type AuthrimStorage, type AutoRefreshOptions, AutoRefreshScheduler, type BaseEventPayload, type BuildAuthorizationUrlOptions, type COSEAlgorithmIdentifier, type CheckSessionMessage, type CheckSessionResponse, type ClientAssertionClaims, type ClientAuthMethod, type ClientAuthResult, type ClientCredentials, ClientCredentialsClient, type ClientCredentialsClientOptions, type ClientCredentialsTokenOptions, type ClientSecretCredentials, type CodeChallengeMethod, type CoreEventName, type CryptoProvider, type DPoPCryptoProvider, type DPoPKeyPair, DPoPManager, type DPoPManagerConfig, type DPoPProofClaims, type DPoPProofHeader, type DPoPProofOptions, DebugContext, type DebugLogLevel, type DebugLogger, type DebugOptions, type DebugTimelineEvent, type DecodedJwt, type DeviceAuthorizationResponse, type DeviceFlowAccessDeniedResult, DeviceFlowClient, type DeviceFlowCompletedResult, type DeviceFlowExpiredResult, type DeviceFlowPendingResult, type DeviceFlowPollResult, type DeviceFlowSlowDownResult, type DeviceFlowStartOptions, type DeviceFlowState, type DirectAuthClient, type DirectAuthClientConfig, type DirectAuthError, type DirectAuthLogoutOptions, type DirectAuthTokenRequest, type DirectAuthTokenResponse, DiscoveryClient, type EmailCodeAuth, type EmailCodeSendOptions, type EmailCodeSendRequest, type EmailCodeSendResponse, type EmailCodeSendResult, type EmailCodeVerifyOptions, type EmailCodeVerifyRequest, type EmailCodeVerifyResponse, type EmitClassifiedErrorOptions, type EndpointOverrides, type ErrorClassification, type ErrorEvent, type ErrorEventEmitter, type ErrorEventPayload, type ErrorFatalEvent, type ErrorRecoverableEvent, type ErrorSeverity, EventEmitter, EventTimeline, type ExchangeCodeOptions, type FrontChannelLogoutBuildParams, type FrontChannelLogoutParams, FrontChannelLogoutUrlBuilder, type FrontChannelLogoutUrlOptions, type FrontChannelLogoutUrlResult, type FrontChannelLogoutValidationOptions, type FrontChannelLogoutValidationResult, type GenerateAuthStateOptions, type HashOptions, type HttpClient, type HttpOptions, type HttpResponse, type IntrospectTokenOptions, type IntrospectionResponse, type IntrospectionTokenTypeHint, JARBuilder, type JARBuilderConfig, type JARMResponseClaims, type JARMValidationOptions, type JARMValidationResult, JARMValidator, type JARMValidatorConfig, type JARRequestObjectClaims, type JARRequestOptions, type JWK, type JwtHeader, LogoutHandler, type LogoutHandlerOptions, type LogoutOptions, type LogoutResult, type LogoutTokenClaims, type MfaMethod, type NextAction, type NoClientCredentials, type OAuthErrorResponse, type OIDCDiscoveryDocument, PARClient, type PARClientOptions, type PARRequest, type PARResponse, type PARResult, PKCEHelper, type PKCEPair, type PasskeyAuth, type PasskeyCredential, type PasskeyLoginFinishRequest, type PasskeyLoginFinishResponse, type PasskeyLoginOptions, type PasskeyLoginStartRequest, type PasskeyLoginStartResponse, type PasskeyRegisterOptions, type PasskeySignUpOptions, type PasskeySignupFinishRequest, type PasskeySignupFinishResponse, type PasskeySignupStartRequest, type PasskeySignupStartResponse, type PrivateKeyJwtCredentials, type PublicKeyCredentialCreationOptionsJSON, type PublicKeyCredentialDescriptorJSON, type PublicKeyCredentialParametersType, type PublicKeyCredentialRequestOptionsJSON, type PublicKeyCredentialRpEntityType, type PublicKeyCredentialType, type PublicKeyCredentialUserEntityJSON, type RedactLevel, type RegistrationResponseJSON, type ResidentKeyRequirementType, type ResolvedConfig, type RetryOptions, type RevokeTokenOptions, STORAGE_KEYS, type Session, type SessionAuth, type SessionChangeEvent, type SessionChangedEvent, type SessionCheckResult, type SessionEndedEvent, type SessionLogoutBroadcastEvent, type SessionManagementConfig, SessionManager, type SessionManagerOptions, type SessionStartedEvent, type SessionState, SessionStateCalculator, type SessionStateCalculatorOptions, type SessionStateParams, type SessionStateResult, type SessionSyncEvent, SilentAuthHandler, type SilentAuthOptions, type SilentAuthResult, type SilentAuthUrlResult, type SilentLoginResult, type SilentLoginStateData, type SocialAuth, type SocialLoginOptions, type SocialProvider, type StandardClaims, type StateChangeEvent, StateManager, TOKEN_TYPE_URIS, type TimelineEntry, TokenApiClient, type TokenApiClientOptions, type TokenErrorEvent, type TokenExchangeRequest, type TokenExchangeResponse, type TokenExchangeResult, type TokenExchangedEvent, type TokenExpiredEvent, type TokenExpiringEvent, TokenIntrospector, type TokenIntrospectorOptions, TokenManager, type TokenManagerOptions, type TokenRefreshFailedEvent, type TokenRefreshedEvent, type TokenRefreshingEvent, type TokenResponse, TokenRevoker, type TokenRevokerOptions, type TokenSet, type TokenTypeHint, type TokenTypeUri, type TrySilentLoginOptions, type User, type UserInfo, type UserVerificationRequirementType, type WarningITPEvent, type WarningPrivateModeEvent, type WarningStorageFallbackEvent, type WebOnlyEventName, base64urlDecode, base64urlEncode, base64urlToString, buildClientAuthentication, calculateBackoffDelay, calculateDsHash, classifyError, createAuthrimClient, createCancellableOperation, createConsoleLogger, createDebugLogger, createRetryFunction, decodeIdToken, decodeJwt, emitClassifiedError, getErrorMeta, getIdTokenNonce, isCancellationError, isJarRequired, isJwtExpired, isRetryableError, noopLogger, normalizeIssuer, parseRetryAfterHeader, raceWithCancellation, resolveConfig, sleep, stringToBase64url, timingSafeEqual, withAbortSignal, withRetry };
|
package/dist/index.d.ts
CHANGED
|
@@ -5060,5 +5060,61 @@ interface DirectAuthClient {
|
|
|
5060
5060
|
/** Session management */
|
|
5061
5061
|
session: SessionAuth;
|
|
5062
5062
|
}
|
|
5063
|
+
/**
|
|
5064
|
+
* Silent Login options for cross-domain SSO
|
|
5065
|
+
*
|
|
5066
|
+
* Executes prompt=none via top-level navigation to check IdP session.
|
|
5067
|
+
* Works with Safari ITP and Chrome Third-Party Cookie Phaseout.
|
|
5068
|
+
*/
|
|
5069
|
+
interface TrySilentLoginOptions {
|
|
5070
|
+
/**
|
|
5071
|
+
* Behavior when IdP has no session (login_required error)
|
|
5072
|
+
*
|
|
5073
|
+
* - 'return': Return to original page (show login button, etc.)
|
|
5074
|
+
* - 'login': Show login screen for user authentication
|
|
5075
|
+
*
|
|
5076
|
+
* Default: 'return'
|
|
5077
|
+
*/
|
|
5078
|
+
onLoginRequired?: 'return' | 'login';
|
|
5079
|
+
/**
|
|
5080
|
+
* Return URL (used for both success and return scenarios)
|
|
5081
|
+
* Default: current URL
|
|
5082
|
+
*/
|
|
5083
|
+
returnTo?: string;
|
|
5084
|
+
/**
|
|
5085
|
+
* OAuth scopes (if additional scopes are needed)
|
|
5086
|
+
*/
|
|
5087
|
+
scope?: string;
|
|
5088
|
+
}
|
|
5089
|
+
/**
|
|
5090
|
+
* Silent Login result (used in callback page)
|
|
5091
|
+
*
|
|
5092
|
+
* error values follow OIDC standard error codes:
|
|
5093
|
+
* - 'login_required': IdP has no session
|
|
5094
|
+
* - 'interaction_required': User interaction needed
|
|
5095
|
+
* - 'consent_required': Re-consent needed
|
|
5096
|
+
* - 'invalid_return_to': Invalid returnTo URL (SDK-specific)
|
|
5097
|
+
*/
|
|
5098
|
+
type SilentLoginResult = {
|
|
5099
|
+
status: 'success';
|
|
5100
|
+
} | {
|
|
5101
|
+
status: 'login_required';
|
|
5102
|
+
} | {
|
|
5103
|
+
status: 'error';
|
|
5104
|
+
error: string;
|
|
5105
|
+
errorDescription?: string;
|
|
5106
|
+
};
|
|
5107
|
+
/**
|
|
5108
|
+
* Silent Login state data (stored in state parameter)
|
|
5109
|
+
* @internal
|
|
5110
|
+
*/
|
|
5111
|
+
interface SilentLoginStateData {
|
|
5112
|
+
/** Type identifier: 'sl' = silent_login */
|
|
5113
|
+
t: 'sl';
|
|
5114
|
+
/** onLoginRequired: 'l' = login, 'r' = return */
|
|
5115
|
+
lr: 'l' | 'r';
|
|
5116
|
+
/** Return URL */
|
|
5117
|
+
rt: string;
|
|
5118
|
+
}
|
|
5063
5119
|
|
|
5064
|
-
export { type AddressClaim, type AttestationConveyancePreferenceType, type AuthCallbackCompleteEvent, type AuthCallbackEvent, type AuthCallbackProcessingEvent, type AuthFallbackEvent, type AuthInitEvent, type AuthLoginCompleteEvent, type AuthLogoutCompleteEvent, type AuthPopupBlockedEvent, type AuthRedirectingEvent, type AuthRequiredEvent, type AuthResult, type AuthState, type AuthStateSnapshot, type AuthState$1 as AuthStateType, type AuthenticationExtensionsClientInputsType, type AuthenticationResponseJSON, type AuthenticatorAssertionResponseJSON, type AuthenticatorAttachmentType, type AuthenticatorAttestationResponseJSON, type AuthenticatorSelectionCriteriaType, type AuthenticatorTransportType, AuthorizationCodeFlow, type AuthorizationContext, type AuthorizationUrlResult, AuthrimClient, type AuthrimClientConfig, AuthrimError, type AuthrimErrorCode, type AuthrimErrorMeta, type AuthrimErrorOptions, type AuthrimErrorRemediation, type AuthrimErrorSeverity, type AuthrimErrorUserAction, type AuthrimEventHandler, type AuthrimEventName, type AuthrimEvents, type AuthrimStorage, type AutoRefreshOptions, AutoRefreshScheduler, type BaseEventPayload, type BuildAuthorizationUrlOptions, type COSEAlgorithmIdentifier, type CheckSessionMessage, type CheckSessionResponse, type ClientAssertionClaims, type ClientAuthMethod, type ClientAuthResult, type ClientCredentials, ClientCredentialsClient, type ClientCredentialsClientOptions, type ClientCredentialsTokenOptions, type ClientSecretCredentials, type CodeChallengeMethod, type CoreEventName, type CryptoProvider, type DPoPCryptoProvider, type DPoPKeyPair, DPoPManager, type DPoPManagerConfig, type DPoPProofClaims, type DPoPProofHeader, type DPoPProofOptions, DebugContext, type DebugLogLevel, type DebugLogger, type DebugOptions, type DebugTimelineEvent, type DecodedJwt, type DeviceAuthorizationResponse, type DeviceFlowAccessDeniedResult, DeviceFlowClient, type DeviceFlowCompletedResult, type DeviceFlowExpiredResult, type DeviceFlowPendingResult, type DeviceFlowPollResult, type DeviceFlowSlowDownResult, type DeviceFlowStartOptions, type DeviceFlowState, type DirectAuthClient, type DirectAuthClientConfig, type DirectAuthError, type DirectAuthLogoutOptions, type DirectAuthTokenRequest, type DirectAuthTokenResponse, DiscoveryClient, type EmailCodeAuth, type EmailCodeSendOptions, type EmailCodeSendRequest, type EmailCodeSendResponse, type EmailCodeSendResult, type EmailCodeVerifyOptions, type EmailCodeVerifyRequest, type EmailCodeVerifyResponse, type EmitClassifiedErrorOptions, type EndpointOverrides, type ErrorClassification, type ErrorEvent, type ErrorEventEmitter, type ErrorEventPayload, type ErrorFatalEvent, type ErrorRecoverableEvent, type ErrorSeverity, EventEmitter, EventTimeline, type ExchangeCodeOptions, type FrontChannelLogoutBuildParams, type FrontChannelLogoutParams, FrontChannelLogoutUrlBuilder, type FrontChannelLogoutUrlOptions, type FrontChannelLogoutUrlResult, type FrontChannelLogoutValidationOptions, type FrontChannelLogoutValidationResult, type GenerateAuthStateOptions, type HashOptions, type HttpClient, type HttpOptions, type HttpResponse, type IntrospectTokenOptions, type IntrospectionResponse, type IntrospectionTokenTypeHint, JARBuilder, type JARBuilderConfig, type JARMResponseClaims, type JARMValidationOptions, type JARMValidationResult, JARMValidator, type JARMValidatorConfig, type JARRequestObjectClaims, type JARRequestOptions, type JWK, type JwtHeader, LogoutHandler, type LogoutHandlerOptions, type LogoutOptions, type LogoutResult, type LogoutTokenClaims, type MfaMethod, type NextAction, type NoClientCredentials, type OAuthErrorResponse, type OIDCDiscoveryDocument, PARClient, type PARClientOptions, type PARRequest, type PARResponse, type PARResult, PKCEHelper, type PKCEPair, type PasskeyAuth, type PasskeyCredential, type PasskeyLoginFinishRequest, type PasskeyLoginFinishResponse, type PasskeyLoginOptions, type PasskeyLoginStartRequest, type PasskeyLoginStartResponse, type PasskeyRegisterOptions, type PasskeySignUpOptions, type PasskeySignupFinishRequest, type PasskeySignupFinishResponse, type PasskeySignupStartRequest, type PasskeySignupStartResponse, type PrivateKeyJwtCredentials, type PublicKeyCredentialCreationOptionsJSON, type PublicKeyCredentialDescriptorJSON, type PublicKeyCredentialParametersType, type PublicKeyCredentialRequestOptionsJSON, type PublicKeyCredentialRpEntityType, type PublicKeyCredentialType, type PublicKeyCredentialUserEntityJSON, type RedactLevel, type RegistrationResponseJSON, type ResidentKeyRequirementType, type ResolvedConfig, type RetryOptions, type RevokeTokenOptions, STORAGE_KEYS, type Session, type SessionAuth, type SessionChangeEvent, type SessionChangedEvent, type SessionCheckResult, type SessionEndedEvent, type SessionLogoutBroadcastEvent, type SessionManagementConfig, SessionManager, type SessionManagerOptions, type SessionStartedEvent, type SessionState, SessionStateCalculator, type SessionStateCalculatorOptions, type SessionStateParams, type SessionStateResult, type SessionSyncEvent, SilentAuthHandler, type SilentAuthOptions, type SilentAuthResult, type SilentAuthUrlResult, type SocialAuth, type SocialLoginOptions, type SocialProvider, type StandardClaims, type StateChangeEvent, StateManager, TOKEN_TYPE_URIS, type TimelineEntry, TokenApiClient, type TokenApiClientOptions, type TokenErrorEvent, type TokenExchangeRequest, type TokenExchangeResponse, type TokenExchangeResult, type TokenExchangedEvent, type TokenExpiredEvent, type TokenExpiringEvent, TokenIntrospector, type TokenIntrospectorOptions, TokenManager, type TokenManagerOptions, type TokenRefreshFailedEvent, type TokenRefreshedEvent, type TokenRefreshingEvent, type TokenResponse, TokenRevoker, type TokenRevokerOptions, type TokenSet, type TokenTypeHint, type TokenTypeUri, type User, type UserInfo, type UserVerificationRequirementType, type WarningITPEvent, type WarningPrivateModeEvent, type WarningStorageFallbackEvent, type WebOnlyEventName, base64urlDecode, base64urlEncode, base64urlToString, buildClientAuthentication, calculateBackoffDelay, calculateDsHash, classifyError, createAuthrimClient, createCancellableOperation, createConsoleLogger, createDebugLogger, createRetryFunction, decodeIdToken, decodeJwt, emitClassifiedError, getErrorMeta, getIdTokenNonce, isCancellationError, isJarRequired, isJwtExpired, isRetryableError, noopLogger, normalizeIssuer, parseRetryAfterHeader, raceWithCancellation, resolveConfig, sleep, stringToBase64url, timingSafeEqual, withAbortSignal, withRetry };
|
|
5120
|
+
export { type AddressClaim, type AttestationConveyancePreferenceType, type AuthCallbackCompleteEvent, type AuthCallbackEvent, type AuthCallbackProcessingEvent, type AuthFallbackEvent, type AuthInitEvent, type AuthLoginCompleteEvent, type AuthLogoutCompleteEvent, type AuthPopupBlockedEvent, type AuthRedirectingEvent, type AuthRequiredEvent, type AuthResult, type AuthState, type AuthStateSnapshot, type AuthState$1 as AuthStateType, type AuthenticationExtensionsClientInputsType, type AuthenticationResponseJSON, type AuthenticatorAssertionResponseJSON, type AuthenticatorAttachmentType, type AuthenticatorAttestationResponseJSON, type AuthenticatorSelectionCriteriaType, type AuthenticatorTransportType, AuthorizationCodeFlow, type AuthorizationContext, type AuthorizationUrlResult, AuthrimClient, type AuthrimClientConfig, AuthrimError, type AuthrimErrorCode, type AuthrimErrorMeta, type AuthrimErrorOptions, type AuthrimErrorRemediation, type AuthrimErrorSeverity, type AuthrimErrorUserAction, type AuthrimEventHandler, type AuthrimEventName, type AuthrimEvents, type AuthrimStorage, type AutoRefreshOptions, AutoRefreshScheduler, type BaseEventPayload, type BuildAuthorizationUrlOptions, type COSEAlgorithmIdentifier, type CheckSessionMessage, type CheckSessionResponse, type ClientAssertionClaims, type ClientAuthMethod, type ClientAuthResult, type ClientCredentials, ClientCredentialsClient, type ClientCredentialsClientOptions, type ClientCredentialsTokenOptions, type ClientSecretCredentials, type CodeChallengeMethod, type CoreEventName, type CryptoProvider, type DPoPCryptoProvider, type DPoPKeyPair, DPoPManager, type DPoPManagerConfig, type DPoPProofClaims, type DPoPProofHeader, type DPoPProofOptions, DebugContext, type DebugLogLevel, type DebugLogger, type DebugOptions, type DebugTimelineEvent, type DecodedJwt, type DeviceAuthorizationResponse, type DeviceFlowAccessDeniedResult, DeviceFlowClient, type DeviceFlowCompletedResult, type DeviceFlowExpiredResult, type DeviceFlowPendingResult, type DeviceFlowPollResult, type DeviceFlowSlowDownResult, type DeviceFlowStartOptions, type DeviceFlowState, type DirectAuthClient, type DirectAuthClientConfig, type DirectAuthError, type DirectAuthLogoutOptions, type DirectAuthTokenRequest, type DirectAuthTokenResponse, DiscoveryClient, type EmailCodeAuth, type EmailCodeSendOptions, type EmailCodeSendRequest, type EmailCodeSendResponse, type EmailCodeSendResult, type EmailCodeVerifyOptions, type EmailCodeVerifyRequest, type EmailCodeVerifyResponse, type EmitClassifiedErrorOptions, type EndpointOverrides, type ErrorClassification, type ErrorEvent, type ErrorEventEmitter, type ErrorEventPayload, type ErrorFatalEvent, type ErrorRecoverableEvent, type ErrorSeverity, EventEmitter, EventTimeline, type ExchangeCodeOptions, type FrontChannelLogoutBuildParams, type FrontChannelLogoutParams, FrontChannelLogoutUrlBuilder, type FrontChannelLogoutUrlOptions, type FrontChannelLogoutUrlResult, type FrontChannelLogoutValidationOptions, type FrontChannelLogoutValidationResult, type GenerateAuthStateOptions, type HashOptions, type HttpClient, type HttpOptions, type HttpResponse, type IntrospectTokenOptions, type IntrospectionResponse, type IntrospectionTokenTypeHint, JARBuilder, type JARBuilderConfig, type JARMResponseClaims, type JARMValidationOptions, type JARMValidationResult, JARMValidator, type JARMValidatorConfig, type JARRequestObjectClaims, type JARRequestOptions, type JWK, type JwtHeader, LogoutHandler, type LogoutHandlerOptions, type LogoutOptions, type LogoutResult, type LogoutTokenClaims, type MfaMethod, type NextAction, type NoClientCredentials, type OAuthErrorResponse, type OIDCDiscoveryDocument, PARClient, type PARClientOptions, type PARRequest, type PARResponse, type PARResult, PKCEHelper, type PKCEPair, type PasskeyAuth, type PasskeyCredential, type PasskeyLoginFinishRequest, type PasskeyLoginFinishResponse, type PasskeyLoginOptions, type PasskeyLoginStartRequest, type PasskeyLoginStartResponse, type PasskeyRegisterOptions, type PasskeySignUpOptions, type PasskeySignupFinishRequest, type PasskeySignupFinishResponse, type PasskeySignupStartRequest, type PasskeySignupStartResponse, type PrivateKeyJwtCredentials, type PublicKeyCredentialCreationOptionsJSON, type PublicKeyCredentialDescriptorJSON, type PublicKeyCredentialParametersType, type PublicKeyCredentialRequestOptionsJSON, type PublicKeyCredentialRpEntityType, type PublicKeyCredentialType, type PublicKeyCredentialUserEntityJSON, type RedactLevel, type RegistrationResponseJSON, type ResidentKeyRequirementType, type ResolvedConfig, type RetryOptions, type RevokeTokenOptions, STORAGE_KEYS, type Session, type SessionAuth, type SessionChangeEvent, type SessionChangedEvent, type SessionCheckResult, type SessionEndedEvent, type SessionLogoutBroadcastEvent, type SessionManagementConfig, SessionManager, type SessionManagerOptions, type SessionStartedEvent, type SessionState, SessionStateCalculator, type SessionStateCalculatorOptions, type SessionStateParams, type SessionStateResult, type SessionSyncEvent, SilentAuthHandler, type SilentAuthOptions, type SilentAuthResult, type SilentAuthUrlResult, type SilentLoginResult, type SilentLoginStateData, type SocialAuth, type SocialLoginOptions, type SocialProvider, type StandardClaims, type StateChangeEvent, StateManager, TOKEN_TYPE_URIS, type TimelineEntry, TokenApiClient, type TokenApiClientOptions, type TokenErrorEvent, type TokenExchangeRequest, type TokenExchangeResponse, type TokenExchangeResult, type TokenExchangedEvent, type TokenExpiredEvent, type TokenExpiringEvent, TokenIntrospector, type TokenIntrospectorOptions, TokenManager, type TokenManagerOptions, type TokenRefreshFailedEvent, type TokenRefreshedEvent, type TokenRefreshingEvent, type TokenResponse, TokenRevoker, type TokenRevokerOptions, type TokenSet, type TokenTypeHint, type TokenTypeUri, type TrySilentLoginOptions, type User, type UserInfo, type UserVerificationRequirementType, type WarningITPEvent, type WarningPrivateModeEvent, type WarningStorageFallbackEvent, type WebOnlyEventName, base64urlDecode, base64urlEncode, base64urlToString, buildClientAuthentication, calculateBackoffDelay, calculateDsHash, classifyError, createAuthrimClient, createCancellableOperation, createConsoleLogger, createDebugLogger, createRetryFunction, decodeIdToken, decodeJwt, emitClassifiedError, getErrorMeta, getIdTokenNonce, isCancellationError, isJarRequired, isJwtExpired, isRetryableError, noopLogger, normalizeIssuer, parseRetryAfterHeader, raceWithCancellation, resolveConfig, sleep, stringToBase64url, timingSafeEqual, withAbortSignal, withRetry };
|
package/dist/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
function $(s){return {...s,scopes:s.scopes??["openid","profile"],flowEngine:s.flowEngine??false,discoveryCacheTtlMs:s.discoveryCacheTtlMs??3600*1e3,refreshSkewSeconds:s.refreshSkewSeconds??30,stateTtlSeconds:s.stateTtlSeconds??600,hashOptions:{hashLength:s.hashOptions?.hashLength??16}}}var a=class s extends Error{constructor(e,t,r){super(t),this.name="AuthrimError",this.code=e,this.details=r?.details,this.errorUri=r?.errorUri,this.cause=r?.cause;}static fromOAuthError(e){let r=["invalid_request","unauthorized_client","access_denied","unsupported_response_type","invalid_scope","server_error","temporarily_unavailable","invalid_grant","invalid_token"].includes(e.error)?e.error:"invalid_request";return new s(r,e.error_description??e.error,{errorUri:e.error_uri,details:{originalError:e.error}})}isRetryable(){return this.code==="network_error"||this.code==="timeout_error"}get meta(){return ce(this.code)}},ke={invalid_request:{transient:false,retryable:false,userAction:"contact_support",severity:"error"},unauthorized_client:{transient:false,retryable:false,userAction:"contact_support",severity:"fatal"},access_denied:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},unsupported_response_type:{transient:false,retryable:false,userAction:"contact_support",severity:"fatal"},invalid_scope:{transient:false,retryable:false,userAction:"contact_support",severity:"error"},server_error:{transient:true,retryable:true,retryAfterMs:5e3,maxRetries:3,userAction:"retry",severity:"error"},temporarily_unavailable:{transient:true,retryable:true,retryAfterMs:1e4,maxRetries:3,userAction:"retry",severity:"warning"},invalid_grant:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},invalid_token:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},invalid_state:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},expired_state:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},invalid_nonce:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},nonce_mismatch:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},missing_nonce:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},missing_id_token:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},session_expired:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},session_check_failed:{transient:true,retryable:true,retryAfterMs:3e3,maxRetries:2,userAction:"retry",severity:"warning"},network_error:{transient:true,retryable:true,retryAfterMs:2e3,maxRetries:3,userAction:"check_network",severity:"error"},timeout_error:{transient:true,retryable:true,retryAfterMs:3e3,maxRetries:3,userAction:"retry",severity:"warning"},discovery_error:{transient:true,retryable:true,retryAfterMs:5e3,maxRetries:2,userAction:"retry",severity:"error"},discovery_mismatch:{transient:false,retryable:false,userAction:"contact_support",severity:"fatal"},configuration_error:{transient:false,retryable:false,userAction:"contact_support",severity:"fatal"},storage_error:{transient:true,retryable:true,retryAfterMs:1e3,maxRetries:2,userAction:"retry",severity:"error"},flow_engine_error:{transient:false,retryable:false,userAction:"contact_support",severity:"error"},no_tokens:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},token_expired:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},token_error:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},refresh_error:{transient:false,retryable:false,retryAfterMs:0,maxRetries:0,userAction:"reauthenticate",severity:"error"},token_exchange_error:{transient:false,retryable:false,retryAfterMs:0,maxRetries:0,userAction:"reauthenticate",severity:"error"},oauth_error:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},missing_code:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},missing_state:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},not_initialized:{transient:false,retryable:false,userAction:"none",severity:"fatal"},no_discovery:{transient:true,retryable:true,retryAfterMs:3e3,maxRetries:2,userAction:"retry",severity:"error"},no_userinfo_endpoint:{transient:false,retryable:false,userAction:"none",severity:"warning"},userinfo_error:{transient:true,retryable:true,retryAfterMs:2e3,maxRetries:2,userAction:"retry",severity:"error"},introspection_error:{transient:true,retryable:true,retryAfterMs:2e3,maxRetries:2,userAction:"retry",severity:"error"},revocation_error:{transient:true,retryable:true,retryAfterMs:2e3,maxRetries:2,userAction:"retry",severity:"error"},no_introspection_endpoint:{transient:false,retryable:false,userAction:"none",severity:"warning"},no_revocation_endpoint:{transient:false,retryable:false,userAction:"none",severity:"warning"},login_required:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},interaction_required:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},consent_required:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},account_selection_required:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},dom_not_ready:{transient:true,retryable:true,retryAfterMs:100,maxRetries:3,userAction:"retry",severity:"error"},state_mismatch:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},popup_blocked:{transient:false,retryable:false,userAction:"none",severity:"warning"},popup_closed:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},invalid_response:{transient:false,retryable:false,userAction:"contact_support",severity:"error"},invalid_callback:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},passkey_not_found:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},passkey_verification_failed:{transient:false,retryable:true,retryAfterMs:1e3,maxRetries:3,userAction:"retry",severity:"error"},passkey_not_supported:{transient:false,retryable:false,userAction:"none",severity:"warning"},passkey_cancelled:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},passkey_invalid_credential:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},email_code_invalid:{transient:false,retryable:true,retryAfterMs:0,maxRetries:5,userAction:"retry",severity:"warning"},email_code_expired:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},email_code_too_many_attempts:{transient:false,retryable:false,retryAfterMs:3e5,userAction:"retry",severity:"error"},challenge_expired:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},challenge_invalid:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},auth_code_invalid:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},auth_code_expired:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},pkce_mismatch:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},origin_not_allowed:{transient:false,retryable:false,userAction:"contact_support",severity:"fatal"},mfa_required:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},email_verification_required:{transient:false,retryable:false,userAction:"none",severity:"warning"},consent_required_direct:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},rate_limited:{transient:true,retryable:true,retryAfterMs:6e4,maxRetries:3,userAction:"retry",severity:"warning"},event_handler_error:{transient:false,retryable:false,userAction:"none",severity:"warning"},par_required:{transient:false,retryable:false,userAction:"none",severity:"fatal"},no_par_endpoint:{transient:false,retryable:false,userAction:"contact_support",severity:"fatal"},par_error:{transient:true,retryable:true,retryAfterMs:2e3,maxRetries:2,userAction:"retry",severity:"error"},par_request_uri_expired:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},no_device_authorization_endpoint:{transient:false,retryable:false,userAction:"contact_support",severity:"fatal"},device_authorization_error:{transient:true,retryable:true,retryAfterMs:2e3,maxRetries:2,userAction:"retry",severity:"error"},device_authorization_pending:{transient:true,retryable:true,retryAfterMs:5e3,maxRetries:60,userAction:"none",severity:"warning"},device_slow_down:{transient:true,retryable:true,retryAfterMs:1e4,maxRetries:60,userAction:"none",severity:"warning"},device_authorization_expired:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},device_access_denied:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},client_credentials_error:{transient:true,retryable:true,retryAfterMs:2e3,maxRetries:2,userAction:"retry",severity:"error"},invalid_client_authentication:{transient:false,retryable:false,userAction:"contact_support",severity:"fatal"},insecure_client_auth:{transient:false,retryable:false,userAction:"none",severity:"fatal"},dpop_key_generation_error:{transient:true,retryable:true,retryAfterMs:1e3,maxRetries:2,userAction:"retry",severity:"error"},dpop_proof_generation_error:{transient:false,retryable:false,userAction:"none",severity:"error"},dpop_nonce_required:{transient:true,retryable:true,retryAfterMs:0,maxRetries:1,userAction:"none",severity:"warning"},jar_signing_error:{transient:false,retryable:false,userAction:"contact_support",severity:"error"},jar_required:{transient:false,retryable:false,userAction:"none",severity:"fatal"},jarm_validation_error:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},jarm_signature_invalid:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},operation_cancelled:{transient:false,retryable:true,retryAfterMs:0,maxRetries:1,userAction:"retry",severity:"warning"},invalid_return_to:{transient:false,retryable:false,userAction:"none",severity:"error"}};function ce(s){return ke[s]}function W(s){let e=s.meta;if(!e.retryable&&e.userAction==="contact_support")return {severity:"fatal",remediation:"contact_support"};if(e.severity==="fatal")return {severity:"fatal",remediation:we(e.userAction)};let t="none";return e.retryable?t="retry":e.userAction==="reauthenticate"?t="reauthenticate":s.code==="popup_blocked"?t="switch_flow":e.userAction==="contact_support"&&(t="contact_support"),{severity:"recoverable",remediation:t}}function we(s){switch(s){case "retry":case "check_network":return "retry";case "reauthenticate":return "reauthenticate";case "contact_support":return "contact_support";default:return "none"}}function w(s){let e=W(s);return e.severity==="recoverable"&&e.remediation==="retry"}function A(s,e,t){let{severity:r,remediation:n}=W(e),i=Date.now(),o=t.source??"core",c={error:e,severity:r,remediation:n,context:t.context,timestamp:i,source:o,operationId:t.operationId};s.emit("error",c),r==="recoverable"?s.emit("error:recoverable",{...c,severity:"recoverable"}):s.emit("error:fatal",{...c,severity:"fatal"});}function T(s){return s.replace(/\/+$/,"")}var N=class N{constructor(e){this.cache=new Map;this.http=e.http,this.cacheTtlMs=e.cacheTtlMs??N.DEFAULT_CACHE_TTL_MS;}async discover(e){let t=T(e),r=this.cache.get(t);if(r&&!this.isExpired(r))return r.doc;let n=`${t}/.well-known/openid-configuration`,i;try{let c=await this.http.fetch(n);if(!c.ok)throw new a("discovery_error",`Discovery request failed: ${c.status}`,{details:{status:c.status,statusText:c.statusText}});i=c.data;}catch(c){throw c instanceof a?c:new a("discovery_error","Failed to fetch discovery document",{cause:c instanceof Error?c:void 0,details:{url:n}})}let o=T(i.issuer);if(o!==t)throw new a("discovery_mismatch",`Issuer mismatch in discovery document: expected "${t}", got "${o}"`,{details:{expected:t,actual:o}});return this.cache.set(t,{doc:i,fetchedAt:Date.now()}),i}isExpired(e){return Date.now()-e.fetchedAt>this.cacheTtlMs}clearCache(){this.cache.clear();}clearIssuer(e){this.cache.delete(T(e));}};N.DEFAULT_CACHE_TTL_MS=3600*1e3;var x=N;var b=class{constructor(){this.listeners=new Map;}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>{this.off(e,t);}}once(e,t){let r=(n=>{this.off(e,r),t(n);});return this.on(e,r)}off(e,t){let r=this.listeners.get(e);r&&(r.delete(t),r.size===0&&this.listeners.delete(e));}emit(e,t){let r=this.listeners.get(e);if(r)for(let n of r)try{n(t);}catch(i){if(e!=="error"){let o=i instanceof a?i:new a("event_handler_error","Event handler threw an error",{cause:i instanceof Error?i:void 0});this.emit("error",{error:o,context:`Error in event handler for '${e}'`});}}}removeAllListeners(e){e?this.listeners.delete(e):this.listeners.clear();}listenerCount(e){return this.listeners.get(e)?.size??0}};var P=class{constructor(e){this.crypto=e;}async generatePKCE(){let e=await this.crypto.generateCodeVerifier(),t=await this.crypto.generateCodeChallenge(e);return {codeVerifier:e,codeChallenge:t,codeChallengeMethod:"S256"}}async generateCodeVerifier(){return this.crypto.generateCodeVerifier()}async generateCodeChallenge(e){return this.crypto.generateCodeChallenge(e)}};function f(s){let e="",t=s.length;for(let r=0;r<t;r+=3){let n=s[r],i=r+1<t?s[r+1]:0,o=r+2<t?s[r+2]:0,c=n<<16|i<<8|o;e+=E[c>>18&63],e+=E[c>>12&63],e+=r+1<t?E[c>>6&63]:"",e+=r+2<t?E[c&63]:"";}return e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function le(s){if(!/^[A-Za-z0-9_-]*$/.test(s))throw new Error("Invalid base64url string: contains invalid characters");let e=s.replace(/-/g,"+").replace(/_/g,"/");for(;e.length%4;)e+="=";let t=e.length,r=e.endsWith("==")?2:e.endsWith("=")?1:0,n=t*3/4-r,i=new Uint8Array(n),o=0;for(let c=0;c<t;c+=4){let l=S[e.charCodeAt(c)],u=S[e.charCodeAt(c+1)],p=S[e.charCodeAt(c+2)],d=S[e.charCodeAt(c+3)],h=l<<18|u<<12|p<<6|d;o<n&&(i[o++]=h>>16&255),o<n&&(i[o++]=h>>8&255),o<n&&(i[o++]=h&255);}return i}function F(s){let e=new TextEncoder;return f(e.encode(s))}function J(s){return new TextDecoder().decode(le(s))}var E="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",S=new Uint8Array(256);for(let s=0;s<E.length;s++)S[E.charCodeAt(s)]=s;var m={authState:(s,e,t)=>`authrim:${s}:${e}:auth:${t}`,tokens:(s,e)=>`authrim:${s}:${e}:tokens`,idToken:(s,e)=>`authrim:${s}:${e}:id_token`,authStatePrefix:(s,e)=>`authrim:${s}:${e}:auth:`},g=class g{constructor(e,t,r,n){this.crypto=e;this.storage=t;this.issuerHash=r;this.clientIdHash=n;this.cleanupInterval=null;}async generateAuthState(e){let t=e.ttlSeconds??g.DEFAULT_TTL_SECONDS,r;e.returnTo&&(r=this.validateReturnTo(e.returnTo,e.returnToOptions??{policy:"relative_only"}));let n=await this.crypto.randomBytes(g.ENTROPY_BYTES),i=await this.crypto.randomBytes(g.ENTROPY_BYTES),o=await this.crypto.randomBytes(g.OPERATION_ID_BYTES),c=f(n),l=f(i),u=f(o),p=Date.now(),d={state:c,nonce:l,codeVerifier:e.codeVerifier,redirectUri:e.redirectUri,scope:e.scope,createdAt:p,expiresAt:p+t*1e3,returnTo:r,operationId:u},h=m.authState(this.issuerHash,this.clientIdHash,c);return await this.storage.set(h,JSON.stringify(d)),d}validateReturnTo(e,t){switch(t.policy){case "relative_only":if(e.startsWith("/")&&!e.startsWith("//")&&!e.includes(":"))return e;throw new a("invalid_return_to","returnTo must be a relative path (e.g., /dashboard)");case "same_origin":try{let r=typeof globalThis<"u"?globalThis.window:void 0,n=t.currentOrigin??r?.location?.origin;if(!n)throw new a("invalid_return_to","currentOrigin is required for same_origin policy in non-browser environments");if(e.startsWith("/")&&!e.startsWith("//")||new URL(e).origin===n)return e}catch(r){if(r instanceof a)throw r}throw new a("invalid_return_to","returnTo must be same origin or a relative path");case "allowlist":if(!t.allowedOrigins||t.allowedOrigins.length===0)throw new a("invalid_return_to","allowedOrigins is required when using allowlist policy");if(e.startsWith("/")&&!e.startsWith("//"))return e;try{let r=new URL(e);if(t.allowedOrigins.includes(r.origin))return e}catch{}throw new a("invalid_return_to",`returnTo origin not in allowlist: ${t.allowedOrigins.join(", ")}`);default:throw new a("invalid_return_to",`Unknown returnTo policy: ${t.policy}`)}}async validateAndConsumeState(e){let t=m.authState(this.issuerHash,this.clientIdHash,e);try{let r=await this.storage.get(t);if(!r)throw new a("invalid_state","State not found or already used");let n;try{n=JSON.parse(r);}catch{throw new a("invalid_state","Malformed state data")}if(Date.now()>n.expiresAt)throw new a("expired_state","State has expired");return n}finally{await this.storage.remove(t);}}async cleanupExpiredStates(){if(!this.storage.getAll)return;let e=m.authStatePrefix(this.issuerHash,this.clientIdHash),t=await this.storage.getAll(),r=Date.now();for(let[n,i]of Object.entries(t))if(n.startsWith(e))try{let o=JSON.parse(i);r>o.expiresAt&&await this.storage.remove(n);}catch{await this.storage.remove(n);}}startAutoCleanup(e=g.DEFAULT_CLEANUP_INTERVAL_MS){this.stopAutoCleanup(),this.cleanupInterval=setInterval(()=>{this.cleanupExpiredStates().catch(()=>{});},e),this.cleanupExpiredStates().catch(()=>{});}stopAutoCleanup(){this.cleanupInterval&&(clearInterval(this.cleanupInterval),this.cleanupInterval=null);}async getStoredStateCount(){if(!this.storage.getAll)return -1;let e=m.authStatePrefix(this.issuerHash,this.clientIdHash),t=await this.storage.getAll(),r=0;for(let n of Object.keys(t))n.startsWith(e)&&r++;return r}};g.DEFAULT_TTL_SECONDS=600,g.ENTROPY_BYTES=32,g.OPERATION_ID_BYTES=16,g.DEFAULT_CLEANUP_INTERVAL_MS=3e5;var D=g;function ue(s){let e=s.split(".");if(e.length!==3)throw new Error("Invalid JWT format: expected 3 parts");let[t,r,n]=e;try{let i=JSON.parse(J(t)),o=JSON.parse(J(r));return {header:i,payload:o,signature:n}}catch{throw new Error("Invalid JWT format: failed to decode")}}function de(s){return ue(s).payload}function Ae(s,e=0){if(s.exp===void 0)return false;let t=Math.floor(Date.now()/1e3);return s.exp+e<t}function G(s){try{return de(s).nonce}catch{return}}function v(s,e){let t=new TextEncoder,r=t.encode(s),n=t.encode(e),i=r.length,o=n.length,c=Math.max(i,o),l=i^o;for(let u=0;u<c;u++){let p=u<i?r[u]:0,d=u<o?n[u]:0;l|=p^d;}return l===0}var I=class{constructor(e,t){this.http=e;this.clientId=t;}buildAuthorizationUrl(e,t,r,n){if(e.require_pushed_authorization_requests&&!n.usePar)throw new a("par_required","Server requires PAR (Pushed Authorization Request) but usePar option is not enabled");if(e.require_signed_request_object&&!n.useJar)throw new a("jar_required","Server requires JAR (JWT Secured Authorization Request) but useJar option is not enabled");let i=e.authorization_endpoint,o=new URLSearchParams;o.set("client_id",this.clientId),o.set("response_type",n.responseType??"code"),o.set("redirect_uri",n.redirectUri),o.set("state",t.state),o.set("nonce",t.nonce),o.set("code_challenge",r.codeChallenge),o.set("code_challenge_method",r.codeChallengeMethod);let c=n.scope??"openid profile";if(o.set("scope",c),n.prompt&&o.set("prompt",n.prompt),n.loginHint&&o.set("login_hint",n.loginHint),n.acrValues&&o.set("acr_values",n.acrValues),n.extraParams){let p=new Set(["client_id","response_type","redirect_uri","state","nonce","code_challenge","code_challenge_method","scope"]);for(let[d,h]of Object.entries(n.extraParams))p.has(d.toLowerCase())||o.set(d,h);}let u={url:`${i}?${o.toString()}`};return n.exposeState&&(u.state=t.state,u.nonce=t.nonce),u}parseCallback(e){let t;e.includes("?")?t=(e.startsWith("http")?new URL(e):new URL(e,"https://dummy.local")).searchParams:t=new URLSearchParams(e);let r=t.get("error");if(r){let o=t.get("error_description")??"Authorization failed";throw new a("oauth_error",o,{details:{error:r,error_description:o,error_uri:t.get("error_uri")}})}let n=t.get("code"),i=t.get("state");if(!n)throw new a("missing_code","Authorization code not found in callback");if(!i)throw new a("missing_state","State parameter not found in callback");return {code:n,state:i}}async exchangeCode(e,t){let r=e.token_endpoint,n=new URLSearchParams({grant_type:"authorization_code",client_id:this.clientId,code:t.code,redirect_uri:t.redirectUri,code_verifier:t.codeVerifier}),i;try{i=await this.http.fetch(r,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n.toString()});}catch(d){throw new a("network_error","Token request failed",{cause:d instanceof Error?d:void 0})}if(!i.ok){let d=i.data;throw new a("token_error","Token exchange failed",{details:{status:i.status,error:d?.error,error_description:d?.error_description}})}let o=i.data;if(t.scope.split(" ").includes("openid")&&!o.id_token)throw new a("missing_id_token","ID token required when openid scope is requested but was not returned by the server");if(o.id_token){let d=G(o.id_token);if(d===void 0)throw new a("missing_nonce","ID token nonce claim is missing but was sent in authorization request");if(!v(d,t.nonce))throw new a("nonce_mismatch","ID token nonce does not match expected value")}let l=Math.floor(Date.now()/1e3),u=o.expires_in?l+o.expires_in:l+3600;return {accessToken:o.access_token,tokenType:o.token_type??"Bearer",expiresAt:u,refreshToken:o.refresh_token,idToken:o.id_token,scope:o.scope}}};var O=class{constructor(e,t,r){this.http=e;this.clientId=t;this.options=r;}async pushAuthorizationRequest(e,t){let r=e.pushed_authorization_request_endpoint;if(!r)throw new a("no_par_endpoint","PAR endpoint not available in discovery document");let n=new URLSearchParams;if(n.set("client_id",this.clientId),n.set("response_type",t.responseType??"code"),n.set("redirect_uri",t.redirectUri),n.set("state",t.state),n.set("nonce",t.nonce),n.set("code_challenge",t.codeChallenge),n.set("code_challenge_method",t.codeChallengeMethod),n.set("scope",t.scope??"openid profile"),t.prompt&&n.set("prompt",t.prompt),t.loginHint&&n.set("login_hint",t.loginHint),t.acrValues&&n.set("acr_values",t.acrValues),t.extraParams){let p=new Set(["client_id","response_type","redirect_uri","state","nonce","code_challenge","code_challenge_method","scope"]);for(let[d,h]of Object.entries(t.extraParams))p.has(d.toLowerCase())||n.set(d,h);}let i={"Content-Type":"application/x-www-form-urlencoded",...this.options?.headers},o;try{o=await this.http.fetch(r,{method:"POST",headers:i,body:n.toString()});}catch(p){throw new a("network_error","PAR request failed",{cause:p instanceof Error?p:void 0})}if(!o.ok){let p=o.data;throw new a("par_error","PAR request failed",{details:{status:o.status,error:p?.error,error_description:p?.error_description}})}let c=o.data;if(!c.request_uri)throw new a("par_error","PAR response missing request_uri");if(typeof c.expires_in!="number")throw new a("par_error","PAR response missing or invalid expires_in");let u=Math.floor(Date.now()/1e3)+c.expires_in;return {requestUri:c.request_uri,expiresAt:u}}buildAuthorizationUrlWithPar(e,t){let r=new URLSearchParams;return r.set("client_id",this.clientId),r.set("request_uri",t),`${e.authorization_endpoint}?${r.toString()}`}};var Te=5,M=class{constructor(e,t){this.http=e;this.clientId=t;}async startDeviceAuthorization(e,t){let r=e.device_authorization_endpoint;if(!r)throw new a("no_device_authorization_endpoint","Device authorization endpoint not available in discovery document");let n=new URLSearchParams({client_id:this.clientId});if(t?.scope&&n.set("scope",t.scope),t?.extraParams){let u=new Set(["client_id","scope"]);for(let[p,d]of Object.entries(t.extraParams))u.has(p.toLowerCase())||n.set(p,d);}let i;try{i=await this.http.fetch(r,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n.toString()});}catch(u){throw new a("network_error","Device authorization request failed",{cause:u instanceof Error?u:void 0})}if(!i.ok){let u=i.data;throw new a("device_authorization_error","Device authorization request failed",{details:{status:i.status,error:u?.error,error_description:u?.error_description}})}let o=i.data;if(!o.device_code||!o.user_code||!o.verification_uri)throw new a("device_authorization_error","Invalid device authorization response: missing required fields");let l=Math.floor(Date.now()/1e3)+o.expires_in;return {deviceCode:o.device_code,userCode:o.user_code,verificationUri:o.verification_uri,verificationUriComplete:o.verification_uri_complete,expiresAt:l,interval:o.interval??Te}}async pollOnce(e,t){let r=Math.floor(Date.now()/1e3);if(r>=t.expiresAt)return {status:"expired"};let n=e.token_endpoint,i=new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:t.deviceCode,client_id:this.clientId}),o;try{o=await this.http.fetch(n,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i.toString()});}catch(p){throw new a("network_error","Device flow token request failed",{cause:p instanceof Error?p:void 0})}if(!o.ok){let p=o.data,d=p?.error;switch(d){case "authorization_pending":return {status:"pending",retryAfter:t.interval};case "slow_down":return {status:"slow_down",retryAfter:t.interval+5};case "expired_token":return {status:"expired"};case "access_denied":return {status:"access_denied"};default:throw new a("device_authorization_error","Device flow token request failed",{details:{status:o.status,error:d,error_description:p?.error_description}})}}let c=o.data,l=c.expires_in?r+c.expires_in:r+3600;return {status:"completed",tokens:{accessToken:c.access_token,tokenType:c.token_type??"Bearer",expiresAt:l,refreshToken:c.refresh_token,idToken:c.id_token,scope:c.scope}}}async pollUntilComplete(e,t,r){let n=t.interval;for(;;){if(r?.signal?.aborted)throw new a("device_authorization_error","Device flow polling aborted");let i=await this.pollOnce(e,t);switch(i.status){case "completed":return i.tokens;case "pending":await this.sleep(i.retryAfter*1e3,r?.signal);continue;case "slow_down":n=i.retryAfter,t.interval=n,await this.sleep(n*1e3,r?.signal);continue;case "expired":throw new a("device_authorization_expired","Device authorization has expired. Please start a new authorization.");case "access_denied":throw new a("device_access_denied","User denied the device authorization request")}}}sleep(e,t){return new Promise((r,n)=>{let i=setTimeout(r,e);t&&t.addEventListener("abort",()=>{clearTimeout(i),n(new a("device_authorization_error","Device flow polling aborted"));},{once:true});})}};var L=class{constructor(e,t){this.keyPair=null;this.serverNonce=null;this.crypto=e,this.config=t??{};}async initialize(){if(!this.crypto.generateDPoPKeyPair)throw new a("dpop_key_generation_error","CryptoProvider does not support DPoP key generation");if(this.crypto.getDPoPKeyPair){let e=await this.crypto.getDPoPKeyPair();if(e){this.keyPair=e;return}}try{this.keyPair=await this.crypto.generateDPoPKeyPair(this.config.algorithm??"ES256");}catch(e){throw new a("dpop_key_generation_error","Failed to generate DPoP key pair",{cause:e instanceof Error?e:void 0})}}isInitialized(){return this.keyPair!==null}async generateProof(e,t,r){if(!this.keyPair)throw new a("dpop_proof_generation_error","DPoP manager not initialized. Call initialize() first.");let n=new URL(t),i=`${n.protocol}//${n.host}${n.pathname}`,o={typ:"dpop+jwt",alg:this.keyPair.algorithm,jwk:this.keyPair.publicKeyJwk},c=Math.floor(Date.now()/1e3),l={jti:this.generateJti(),htm:e.toUpperCase(),htu:i,iat:c};r?.accessTokenHash&&(l.ath=r.accessTokenHash),(r?.nonce??this.serverNonce)&&(l.nonce=r?.nonce??this.serverNonce??void 0);try{let u=F(JSON.stringify(o)),p=F(JSON.stringify(l)),d=`${u}.${p}`,h=await this.keyPair.sign(new TextEncoder().encode(d)),y=f(h);return `${d}.${y}`}catch(u){throw new a("dpop_proof_generation_error","Failed to generate DPoP proof",{cause:u instanceof Error?u:void 0})}}handleNonceResponse(e){this.serverNonce=e;}getServerNonce(){return this.serverNonce}clearServerNonce(){this.serverNonce=null;}getPublicKeyJwk(){return this.keyPair?.publicKeyJwk??null}getThumbprint(){return this.keyPair?.thumbprint??null}async calculateAccessTokenHash(e){let t=await this.crypto.sha256(e);return f(t)}async clear(){this.crypto.clearDPoPKeyPair&&await this.crypto.clearDPoPKeyPair(),this.keyPair=null,this.serverNonce=null;}generateJti(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).substring(2,15)}`}};var Y={access_token:"urn:ietf:params:oauth:token-type:access_token",refresh_token:"urn:ietf:params:oauth:token-type:refresh_token",id_token:"urn:ietf:params:oauth:token-type:id_token"};var _=class _{constructor(e){this.refreshPromise=null;this.discovery=null;this.expiringTimeout=null;this.isLeaderTab=true;this.currentOperationId=null;this.http=e.http,this.storage=e.storage,this.clientId=e.clientId,this.issuerHash=e.issuerHash,this.clientIdHash=e.clientIdHash,this.refreshSkewSeconds=e.refreshSkewSeconds??_.DEFAULT_REFRESH_SKEW_SECONDS,this.eventEmitter=e.eventEmitter,this.expiringThresholdMs=(e.expiringThresholdSeconds??_.DEFAULT_EXPIRING_THRESHOLD_SECONDS)*1e3,this.expiringJitterMs=e.expiringJitterMs??_.DEFAULT_EXPIRING_JITTER_MS;}setDiscovery(e){this.discovery=e;}get tokenKey(){return m.tokens(this.issuerHash,this.clientIdHash)}get idTokenKey(){return m.idToken(this.issuerHash,this.clientIdHash)}async getTokens(){let e=await this.storage.get(this.tokenKey);if(!e)return null;try{return JSON.parse(e)}catch{return await this.clearTokens(),null}}async saveTokens(e){await this.storage.set(this.tokenKey,JSON.stringify(e)),e.idToken&&await this.storage.set(this.idTokenKey,e.idToken),this.scheduleExpiringEvent(e.expiresAt);}scheduleExpiringEvent(e){if(this.expiringTimeout&&(clearTimeout(this.expiringTimeout),this.expiringTimeout=null),!this.isLeaderTab)return;let t=e*1e3,r=t-this.expiringThresholdMs,n=Math.random()*this.expiringJitterMs*2-this.expiringJitterMs,i=r-Date.now()+n;i>0&&(this.expiringTimeout=setTimeout(()=>{let o=Date.now(),c=Math.max(0,Math.floor((t-o)/1e3));this.eventEmitter?.emit("token:expiring",{expiresAt:e,expiresIn:c,timestamp:o,source:"core"});},i));}setLeaderTab(e){this.isLeaderTab=e,!e&&this.expiringTimeout&&(clearTimeout(this.expiringTimeout),this.expiringTimeout=null);}setOperationId(e){this.currentOperationId=e;}getOperationId(){return this.currentOperationId}async clearTokens(){await this.storage.remove(this.tokenKey),await this.storage.remove(this.idTokenKey);}async getAccessToken(){let e=await this.getTokens();if(!e)throw new a("no_tokens","No tokens available. Please authenticate first.");if(this.shouldRefresh(e)){if(!e.refreshToken)throw new a("token_expired","Access token expired and no refresh token available");return this.refreshWithLock(e.refreshToken)}return e.accessToken}async getIdToken(){return (await this.getTokens())?.idToken??null}shouldRefresh(e){let t=Math.floor(Date.now()/1e3);return e.expiresAt-this.refreshSkewSeconds<=t}async refreshWithLock(e,t="on_demand"){if(this.refreshPromise)return (await this.refreshPromise).accessToken;this.refreshPromise=this.doRefreshWithRetry(e,t);try{return (await this.refreshPromise).accessToken}finally{this.refreshPromise=null;}}async refresh(){let e=await this.getTokens();if(!e?.refreshToken)throw new a("no_tokens","No refresh token available");if(this.refreshPromise)return this.refreshPromise;this.refreshPromise=this.doRefreshWithRetry(e.refreshToken,"manual");try{return await this.refreshPromise}finally{this.refreshPromise=null;}}async doRefreshWithRetry(e,t="on_demand",r=0){let i=Date.now();r===0&&this.eventEmitter?.emit("token:refreshing",{reason:t,timestamp:i,source:"core",operationId:this.currentOperationId??void 0});try{return await this.doRefresh(e)}catch(o){let c=o instanceof a?o:new a("refresh_error","Token refresh failed",{cause:o instanceof Error?o:void 0}),l=r<1&&w(c);if(this.eventEmitter?.emit("token:refresh:failed",{error:c,willRetry:l,attempt:r,timestamp:Date.now(),source:"core",operationId:this.currentOperationId??void 0}),l)return this.doRefreshWithRetry(e,t,r+1);throw w(c)||this.eventEmitter?.emit("auth:required",{reason:"refresh_failed",timestamp:Date.now(),source:"core",operationId:this.currentOperationId??void 0}),o}}async doRefresh(e){if(!this.discovery)throw new a("no_discovery","Discovery document not set");let t=this.discovery.token_endpoint,r=new URLSearchParams({grant_type:"refresh_token",client_id:this.clientId,refresh_token:e}),n;try{n=await this.http.fetch(t,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:r.toString()});}catch(u){let p=new a("network_error","Token refresh request failed",{cause:u instanceof Error?u:void 0});throw this.eventEmitter?.emit("token:error",{error:p,context:"refresh",timestamp:Date.now(),source:"core"}),this.eventEmitter&&A(this.eventEmitter,p,{context:"refresh"}),p}if(!n.ok){let u=n.data,p=new a("refresh_error","Token refresh failed",{details:{status:n.status,error:u?.error,error_description:u?.error_description}});throw this.eventEmitter?.emit("token:error",{error:p,context:"refresh",timestamp:Date.now(),source:"core"}),this.eventEmitter&&A(this.eventEmitter,p,{context:"refresh"}),p}let i=n.data,o=Math.floor(Date.now()/1e3),c=i.expires_in?o+i.expires_in:o+3600,l={accessToken:i.access_token,tokenType:i.token_type??"Bearer",expiresAt:c,refreshToken:i.refresh_token??e,idToken:i.id_token,scope:i.scope};return await this.saveTokens(l),this.eventEmitter?.emit("token:refreshed",{hasAccessToken:!!l.accessToken,hasRefreshToken:!!l.refreshToken,hasIdToken:!!l.idToken,expiresAt:l.expiresAt,timestamp:Date.now(),source:"core",operationId:this.currentOperationId??void 0}),l}async isAuthenticated(){let e=await this.getTokens();if(!e)return false;let t=Math.floor(Date.now()/1e3);return e.expiresAt<=t?!!e.refreshToken:true}async exchangeToken(e){if(!this.discovery)throw new a("no_discovery","Discovery document not set");let t=this.discovery.token_endpoint,r=this.mapTokenTypeToUri(e.subjectTokenType??"access_token"),n=new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:token-exchange",client_id:this.clientId,subject_token:e.subjectToken,subject_token_type:r});e.audience&&n.set("audience",e.audience),e.scope&&n.set("scope",e.scope),e.requestedTokenType&&n.set("requested_token_type",this.mapTokenTypeToUri(e.requestedTokenType)),e.actorToken&&(n.set("actor_token",e.actorToken),e.actorTokenType&&n.set("actor_token_type",this.mapTokenTypeToUri(e.actorTokenType)));let i;try{i=await this.http.fetch(t,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n.toString()});}catch(d){let h=new a("network_error","Token exchange request failed",{cause:d instanceof Error?d:void 0});throw this.eventEmitter?.emit("token:error",{error:h,context:"exchange",timestamp:Date.now(),source:"core"}),this.eventEmitter&&A(this.eventEmitter,h,{context:"exchange"}),h}if(!i.ok){let d=i.data,h=new a("token_exchange_error","Token exchange failed",{details:{status:i.status,error:d?.error,error_description:d?.error_description}});throw this.eventEmitter?.emit("token:error",{error:h,context:"exchange",timestamp:Date.now(),source:"core"}),this.eventEmitter&&A(this.eventEmitter,h,{context:"exchange"}),h}let o=i.data,c=Math.floor(Date.now()/1e3),l=o.expires_in?c+o.expires_in:c+3600,u={accessToken:o.access_token,tokenType:o.token_type??"Bearer",expiresAt:l,refreshToken:o.refresh_token,idToken:o.id_token,scope:o.scope},p={tokens:u,issuedTokenType:o.issued_token_type};return this.eventEmitter?.emit("token:exchanged",{hasAccessToken:!!u.accessToken,hasRefreshToken:!!u.refreshToken,issuedTokenType:o.issued_token_type,timestamp:Date.now(),source:"core",operationId:this.currentOperationId??void 0}),p}mapTokenTypeToUri(e){return Y[e]}destroy(){this.expiringTimeout&&(clearTimeout(this.expiringTimeout),this.expiringTimeout=null);}};_.DEFAULT_REFRESH_SKEW_SECONDS=30,_.DEFAULT_EXPIRING_THRESHOLD_SECONDS=300,_.DEFAULT_EXPIRING_JITTER_MS=3e4;var H=_;var U=class{constructor(e){this.http=e.http,this.clientId=e.clientId;}async introspect(e,t){let r=e.introspection_endpoint;if(!r)throw new a("no_introspection_endpoint","Authorization server does not support token introspection");return this.introspectWithEndpoint(r,t)}async introspectWithEndpoint(e,t){let r=new URLSearchParams({client_id:this.clientId,token:t.token});t.tokenTypeHint&&r.set("token_type_hint",t.tokenTypeHint);let n;try{n=await this.http.fetch(e,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:r.toString()});}catch(i){throw new a("network_error","Token introspection request failed",{cause:i instanceof Error?i:void 0})}if(!n.ok){let i=n.data;throw new a("introspection_error","Token introspection failed",{details:{status:n.status,error:i?.error,error_description:i?.error_description}})}return n.data}async isActive(e,t){return (await this.introspect(e,{token:t})).active}};var k=class{constructor(e){this.http=e.http,this.clientId=e.clientId;}async revoke(e,t){let r=e.revocation_endpoint;if(!r)throw new a("no_revocation_endpoint","Authorization server does not support token revocation");let n=new URLSearchParams({client_id:this.clientId,token:t.token});t.tokenTypeHint&&n.set("token_type_hint",t.tokenTypeHint);let i;try{i=await this.http.fetch(r,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n.toString()});}catch(c){throw new a("network_error","Token revocation request failed",{cause:c instanceof Error?c:void 0})}if(i.ok)return;let o=i.data;throw new a("revocation_error","Token revocation failed",{details:{status:i.status,error:o?.error,error_description:o?.error_description}})}async revokeWithEndpoint(e,t){let r=new URLSearchParams({client_id:this.clientId,token:t.token});t.tokenTypeHint&&r.set("token_type_hint",t.tokenTypeHint);let n;try{n=await this.http.fetch(e,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:r.toString()});}catch(o){throw new a("network_error","Token revocation request failed",{cause:o instanceof Error?o:void 0})}if(n.ok)return;let i=n.data;throw new a("revocation_error","Token revocation failed",{details:{status:n.status,error:i?.error,error_description:i?.error_description}})}};var j=class{constructor(e){this.storage=e.storage,this.clientId=e.clientId,this.issuerHash=e.issuerHash,this.clientIdHash=e.clientIdHash,this.eventEmitter=e.eventEmitter,this.endpoints=e.endpoints,this.tokenRevoker=new k({http:e.http,clientId:e.clientId});}async logout(e,t){let r=await this.getStoredIdToken(),n=await this.getStoredTokens(),i;t?.revokeTokens&&e?.revocation_endpoint&&n&&(i=await this.revokeTokens(e,n)),await this.clearTokens(),this.eventEmitter?.emit("session:ended",{reason:"logout",timestamp:Date.now(),source:"core"});let o;if(this.endpoints?.endSession!==void 0?o=this.endpoints.endSession:e&&(o=e.end_session_endpoint),!o)return {localOnly:true,revocation:i};let c=t?.idTokenHint??r,l=new URLSearchParams({client_id:this.clientId});return c&&l.set("id_token_hint",c),t?.postLogoutRedirectUri&&l.set("post_logout_redirect_uri",t.postLogoutRedirectUri),t?.state&&l.set("state",t.state),{logoutUrl:`${o}?${l.toString()}`,localOnly:false,revocation:i}}async revokeTokens(e,t){let r={attempted:true};try{t.refreshToken&&(await this.tokenRevoker.revoke(e,{token:t.refreshToken,tokenTypeHint:"refresh_token"}),r.refreshTokenRevoked=!0),await this.tokenRevoker.revoke(e,{token:t.accessToken,tokenTypeHint:"access_token"}),r.accessTokenRevoked=!0;}catch(n){r.error=n instanceof Error?n:new Error(String(n));}return r}async clearTokens(){let e=m.tokens(this.issuerHash,this.clientIdHash),t=m.idToken(this.issuerHash,this.clientIdHash);await this.storage.remove(e),await this.storage.remove(t);}async getStoredIdToken(){let e=m.idToken(this.issuerHash,this.clientIdHash);return this.storage.get(e)}async getStoredTokens(){let e=m.tokens(this.issuerHash,this.clientIdHash),t=await this.storage.get(e);if(!t)return null;try{return JSON.parse(t)}catch{return null}}};var q=class{constructor(e){this.http=e.http;}async checkSession(e,t){let r=e.userinfo_endpoint;if(!r)return {valid:false,error:new a("no_userinfo_endpoint","UserInfo endpoint not available")};try{let n=await this.http.fetch(r,{method:"GET",headers:{Authorization:`Bearer ${t}`}});return n.ok?{valid:!0,user:n.data}:n.status===401?{valid:!1,error:new a("session_expired","Session has expired")}:{valid:!1,error:new a("session_check_failed","Session check failed",{details:{status:n.status}})}}catch(n){return {valid:false,error:new a("network_error","Failed to check session",{cause:n instanceof Error?n:void 0})}}}async getUserInfo(e,t){let r=e.userinfo_endpoint;if(!r)throw new a("no_userinfo_endpoint","UserInfo endpoint not available");let n;try{n=await this.http.fetch(r,{method:"GET",headers:{Authorization:`Bearer ${t}`}});}catch(i){throw new a("network_error","Failed to fetch user info",{cause:i instanceof Error?i:void 0})}if(!n.ok)throw new a("userinfo_error","Failed to get user info",{details:{status:n.status}});return n.data}};var z=class{constructor(e){this.discovery=null;this.tokenManager=e.tokenManager,this.tokenApiClient=e.tokenApiClient;}setDiscovery(e){this.discovery=e;}async isAuthenticated(){return this.tokenManager.isAuthenticated()}async checkSession(){if(!this.discovery)return {valid:false,error:new a("no_discovery","Discovery document not available")};try{let e=await this.tokenManager.getAccessToken();return this.tokenApiClient.checkSession(this.discovery,e)}catch(e){return e instanceof a?{valid:false,error:e}:{valid:false,error:new a("session_check_failed","Failed to check session",{cause:e instanceof Error?e:void 0})}}}async getUser(){if(!this.discovery)throw new a("no_discovery","Discovery document not available");let e=await this.tokenManager.getAccessToken();return this.tokenApiClient.getUserInfo(this.discovery,e)}};async function pe(s,e,t=16){let r=await s.sha256(e);return f(r).slice(0,t)}var K=class{constructor(e){this.dpopManager=null;this.initialized=false;this.config=$(e),this.normalizedIssuer=T(e.issuer),this.events=new b,this.discoveryClient=new x({http:this.config.http,cacheTtlMs:this.config.discoveryCacheTtlMs}),this.pkce=new P(this.config.crypto),this.authCodeFlow=new I(this.config.http,this.config.clientId),this.parClient=new O(this.config.http,this.config.clientId),this.deviceFlowClient=new M(this.config.http,this.config.clientId);}get eventEmitter(){return this.events}async initialize(){if(this.initialized)return;let e=this.config.hashOptions.hashLength;this.issuerHash=await pe(this.config.crypto,this.normalizedIssuer,e),this.clientIdHash=await pe(this.config.crypto,this.config.clientId,e),this.stateManager=new D(this.config.crypto,this.config.storage,this.issuerHash,this.clientIdHash),this.tokenManager=new H({http:this.config.http,storage:this.config.storage,clientId:this.config.clientId,issuerHash:this.issuerHash,clientIdHash:this.clientIdHash,refreshSkewSeconds:this.config.refreshSkewSeconds,eventEmitter:this.events}),this.logoutHandler=new j({storage:this.config.storage,http:this.config.http,clientId:this.config.clientId,issuerHash:this.issuerHash,clientIdHash:this.clientIdHash,eventEmitter:this.events,endpoints:this.config.endpoints}),this.tokenIntrospector=new U({http:this.config.http,clientId:this.config.clientId}),this.tokenRevoker=new k({http:this.config.http,clientId:this.config.clientId});let t=new q({http:this.config.http});this.sessionManager=new z({tokenManager:this.tokenManager,tokenApiClient:t}),await this.stateManager.cleanupExpiredStates(),this.initialized=true;}ensureInitialized(){if(!this.initialized)throw new a("not_initialized","Client not initialized. Use createAuthrimClient().")}async discover(){let e=await this.discoveryClient.discover(this.normalizedIssuer);return this.tokenManager.setDiscovery(e),this.sessionManager.setDiscovery(e),e}async buildAuthorizationUrl(e){this.ensureInitialized();let t=await this.discover(),r=await this.pkce.generatePKCE(),n=e.scope??"openid profile",i=await this.stateManager.generateAuthState({redirectUri:e.redirectUri,codeVerifier:r.codeVerifier,scope:n,ttlSeconds:this.config.stateTtlSeconds}),o=this.authCodeFlow.buildAuthorizationUrl(t,i,r,e);return this.events.emit("auth:redirecting",{url:o.url,timestamp:Date.now(),source:"core",operationId:i.operationId}),o}async handleCallback(e){this.ensureInitialized();let{code:t,state:r}=this.authCodeFlow.parseCallback(e),n=await this.stateManager.validateAndConsumeState(r),i=n.operationId;this.events.emit("auth:callback",{code:t,state:r,timestamp:Date.now(),source:"core",operationId:i}),this.events.emit("auth:callback:processing",{state:r,timestamp:Date.now(),source:"core",operationId:i});try{let o=await this.discover(),c=await this.authCodeFlow.exchangeCode(o,{code:t,state:r,redirectUri:n.redirectUri,codeVerifier:n.codeVerifier,nonce:n.nonce,scope:n.scope});return await this.tokenManager.saveTokens(c),this.events.emit("auth:callback:complete",{success:!0,timestamp:Date.now(),source:"core",operationId:i}),c}catch(o){throw this.events.emit("auth:callback:complete",{success:false,timestamp:Date.now(),source:"core",operationId:i}),o}}get par(){return {push:async e=>{this.ensureInitialized();let t=await this.discover(),r=await this.pkce.generatePKCE(),n=e.scope??"openid profile",i=await this.stateManager.generateAuthState({redirectUri:e.redirectUri,codeVerifier:r.codeVerifier,scope:n,ttlSeconds:this.config.stateTtlSeconds});return this.parClient.pushAuthorizationRequest(t,{redirectUri:e.redirectUri,scope:n,state:i.state,nonce:i.nonce,codeChallenge:r.codeChallenge,codeChallengeMethod:"S256",prompt:e.prompt,loginHint:e.loginHint,acrValues:e.acrValues,extraParams:e.extraParams})},buildAuthorizationUrl:async e=>{let t=await this.discover();return this.parClient.buildAuthorizationUrlWithPar(t,e)},isAvailable:async()=>!!(await this.discover()).pushed_authorization_request_endpoint,isRequired:async()=>(await this.discover()).require_pushed_authorization_requests===true}}get deviceFlow(){return {start:async e=>{this.ensureInitialized();let t=await this.discover();return this.deviceFlowClient.startDeviceAuthorization(t,e)},pollOnce:async e=>{let t=await this.discover();return this.deviceFlowClient.pollOnce(t,e)},pollUntilComplete:async(e,t)=>{let r=await this.discover(),n=await this.deviceFlowClient.pollUntilComplete(r,e,t);return await this.tokenManager.saveTokens(n),n},isAvailable:async()=>!!(await this.discover()).device_authorization_endpoint}}get dpop(){if(!this.config.crypto.generateDPoPKeyPair)return;this.dpopManager||(this.dpopManager=new L(this.config.crypto));let t=this.dpopManager;return {initialize:()=>t.initialize(),isInitialized:()=>t.isInitialized(),generateProof:(r,n,i)=>t.generateProof(r,n,i),handleNonceResponse:r=>t.handleNonceResponse(r),calculateAccessTokenHash:r=>t.calculateAccessTokenHash(r),getPublicKeyJwk:()=>t.getPublicKeyJwk(),getThumbprint:()=>t.getThumbprint(),clear:()=>t.clear(),isServerSupported:async()=>{let r=await this.discover();return Array.isArray(r.dpop_signing_alg_values_supported)&&r.dpop_signing_alg_values_supported.length>0}}}get token(){return this.ensureInitialized(),{getAccessToken:()=>this.tokenManager.getAccessToken(),getTokens:()=>this.tokenManager.getTokens(),getIdToken:()=>this.tokenManager.getIdToken(),isAuthenticated:()=>this.tokenManager.isAuthenticated(),exchange:async e=>(await this.discover(),this.tokenManager.exchangeToken(e)),introspect:async e=>{let t=await this.discover();return this.tokenIntrospector.introspect(t,e)},revoke:async e=>{let t=await this.discover();return this.tokenRevoker.revoke(t,e)}}}get session(){return this.ensureInitialized(),{isAuthenticated:()=>this.sessionManager.isAuthenticated(),check:()=>this.sessionManager.checkSession()}}async isAuthenticated(){return this.ensureInitialized(),this.tokenManager.isAuthenticated()}async getUser(){return this.ensureInitialized(),this.sessionManager.getUser()}async logout(e){this.ensureInitialized();let t=null;try{t=await this.discover();}catch{}return this.logoutHandler.logout(t,e)}on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}off(e,t){this.events.off(e,t);}};async function Ee(s){let e=new K(s);return await e.initialize(),e}var he=new Set(["login_required","interaction_required","consent_required","account_selection_required"]),X=class{constructor(e){this.clientId=e;}buildSilentAuthUrl(e,t,r,n){let i=e.authorization_endpoint,o=new URLSearchParams;o.set("client_id",this.clientId),o.set("response_type",n.responseType??"code"),o.set("redirect_uri",n.redirectUri),o.set("state",t.state),o.set("nonce",t.nonce),o.set("prompt","none"),o.set("code_challenge",r.codeChallenge),o.set("code_challenge_method",r.codeChallengeMethod);let c=n.scope??"openid";if(o.set("scope",c),n.loginHint&&o.set("login_hint",n.loginHint),n.idTokenHint&&o.set("id_token_hint",n.idTokenHint),n.extraParams){let p=new Set(["client_id","response_type","redirect_uri","state","nonce","code_challenge","code_challenge_method","scope","prompt"]);for(let[d,h]of Object.entries(n.extraParams))p.has(d.toLowerCase())||o.set(d,h);}let u={url:`${i}?${o.toString()}`};return n.exposeState&&(u.state=t.state,u.nonce=t.nonce),u}parseSilentAuthResponse(e){let t;e.includes("?")?t=(e.startsWith("http")?new URL(e):new URL(e,"https://dummy.local")).searchParams:t=new URLSearchParams(e);let r=t.get("error");if(r){let o=t.get("error_description"),c=this.mapSilentAuthError(r);return {success:false,error:new a(c,o??this.getDefaultErrorMessage(r),{details:{error:r,error_description:o,error_uri:t.get("error_uri")}})}}let n=t.get("code"),i=t.get("state");return n?i?{success:true,code:n,state:i}:{success:false,error:new a("missing_state","State parameter not found in silent auth response")}:{success:false,error:new a("missing_code","Authorization code not found in silent auth response")}}isInteractiveLoginRequired(e){return he.has(e.code)}mapSilentAuthError(e){return he.has(e)?e:"oauth_error"}getDefaultErrorMessage(e){switch(e){case "login_required":return "User must log in - no active session found";case "interaction_required":return "User interaction required";case "consent_required":return "User consent required";case "account_selection_required":return "User must select an account";default:return "Silent authentication failed"}}};async function Z(s,e,t){let r={},n={};switch(s.method){case "client_secret_basic":{let i=btoa(`${e}:${s.clientSecret}`);r.Authorization=`Basic ${i}`;break}case "client_secret_post":{n.client_id=e,n.client_secret=s.clientSecret;break}case "private_key_jwt":{let i=Math.floor(Date.now()/1e3),o={iss:e,sub:e,aud:t,jti:Re(),exp:i+300,iat:i},c;try{c=await s.signJwt(o);}catch(l){throw new a("invalid_client_authentication","Failed to sign client assertion JWT",{cause:l instanceof Error?l:void 0})}n.client_id=e,n.client_assertion_type="urn:ietf:params:oauth:client-assertion-type:jwt-bearer",n.client_assertion=c;break}case "none":{if(!("dangerouslyAllowInsecure"in s)||s.dangerouslyAllowInsecure!==true)throw new a("insecure_client_auth",'Client authentication method "none" requires dangerouslyAllowInsecure: true');n.client_id=e;break}default:{let i=s;throw new a("invalid_client_authentication",`Unknown client authentication method: ${i.method}`)}}return {headers:r,bodyParams:n}}function Re(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).substring(2,15)}`}var Q=class{constructor(e){this.http=e.http,this.clientId=e.clientId,this.credentials=e.credentials;}async getToken(e,t){let r=e.token_endpoint,{headers:n,bodyParams:i}=await Z(this.credentials,this.clientId,r),o=new URLSearchParams({grant_type:"client_credentials",...i});if(t?.scope&&o.set("scope",t.scope),t?.audience&&o.set("audience",t.audience),t?.extraParams){let y=new Set(["grant_type","client_id","client_secret","client_assertion","client_assertion_type","scope","audience"]);for(let[C,_e]of Object.entries(t.extraParams))y.has(C.toLowerCase())||o.set(C,_e);}let c={"Content-Type":"application/x-www-form-urlencoded",...n},l;try{l=await this.http.fetch(r,{method:"POST",headers:c,body:o.toString()});}catch(y){throw new a("network_error","Client credentials token request failed",{cause:y instanceof Error?y:void 0})}if(!l.ok){let y=l.data;throw new a("client_credentials_error","Client credentials token request failed",{details:{status:l.status,error:y?.error,error_description:y?.error_description}})}let u=l.data,p=Math.floor(Date.now()/1e3),d=u.expires_in?p+u.expires_in:p+3600;return {accessToken:u.access_token,tokenType:u.token_type??"Bearer",expiresAt:d,refreshToken:u.refresh_token,scope:u.scope}}};var ee=class{constructor(e){this.config=e;}async buildRequestObject(e){let t=Math.floor(Date.now()/1e3),r=this.config.lifetime??300,n={alg:this.config.algorithm??"RS256",typ:"oauth-authz-req+jwt"};this.config.keyId&&(n.kid=this.config.keyId);let i={iss:e.clientId,aud:e.issuer,response_type:e.responseType??"code",client_id:e.clientId,redirect_uri:e.redirectUri,scope:e.scope,state:e.state,nonce:e.nonce,code_challenge:e.codeChallenge,code_challenge_method:e.codeChallengeMethod,iat:t,exp:t+r,jti:this.generateJti()};if(e.prompt&&(i.prompt=e.prompt),e.loginHint&&(i.login_hint=e.loginHint),e.acrValues&&(i.acr_values=e.acrValues),e.extraClaims){let o=new Set(["iss","aud","response_type","client_id","redirect_uri","scope","state","nonce","code_challenge","code_challenge_method","iat","exp","jti","nbf"]);for(let[c,l]of Object.entries(e.extraClaims))o.has(c)||(i[c]=l);}try{return await this.config.signJwt(n,i)}catch(o){throw new a("jar_signing_error","Failed to sign JAR request object",{cause:o instanceof Error?o:void 0})}}generateJti(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).substring(2,15)}`}};function Ce(s){return s.require_signed_request_object===true}var te=class{constructor(e){this.config=e;}async validateResponse(e,t,r){let n=r.clockSkewSeconds??60,i;try{i=await this.config.verifyJwt(t,e.issuer);}catch(l){throw new a("jarm_signature_invalid","Failed to verify JARM response signature",{cause:l instanceof Error?l:void 0})}if(i.iss!==e.issuer)throw new a("jarm_validation_error","JARM response issuer does not match discovery issuer",{details:{expected:e.issuer,actual:i.iss}});if(!(Array.isArray(i.aud)?i.aud:[i.aud]).includes(r.clientId))throw new a("jarm_validation_error","JARM response audience does not match client_id",{details:{expected:r.clientId,actual:i.aud}});let c=Math.floor(Date.now()/1e3);if(i.exp&&i.exp+n<c)throw new a("jarm_validation_error","JARM response has expired");if(i.iat&&i.iat-n>c)throw new a("jarm_validation_error","JARM response iat is in the future");if(i.error)throw new a("oauth_error",i.error_description??i.error,{details:{error:i.error,error_description:i.error_description,error_uri:i.error_uri}});if(!i.state)throw new a("jarm_validation_error","JARM response is missing state claim");if(!v(i.state,r.expectedState))throw new a("jarm_validation_error","JARM response state does not match expected state");if(!i.code)throw new a("jarm_validation_error","JARM response is missing authorization code");return {code:i.code,state:i.state}}static extractResponseFromCallback(e){let t;return e.includes("?")?t=(e.startsWith("http")?new URL(e):new URL(e,"https://dummy.local")).searchParams:t=new URLSearchParams(e),t.get("response")}};var R=class R{constructor(e){this.tokenManager=null;this.checkInterval=null;this.abortController=null;this.isRunning=false;this.options={thresholdSeconds:e?.thresholdSeconds??R.DEFAULT_THRESHOLD_SECONDS,checkIntervalMs:e?.checkIntervalMs??R.DEFAULT_CHECK_INTERVAL_MS,eventEmitter:e?.eventEmitter};}start(e){this.isRunning||(this.tokenManager=e,this.abortController=new AbortController,this.isRunning=true,this.checkInterval=setInterval(()=>{this.checkAndRefresh().catch(()=>{});},this.options.checkIntervalMs),this.checkAndRefresh().catch(()=>{}));}stop(){this.isRunning&&(this.isRunning=false,this.checkInterval&&(clearInterval(this.checkInterval),this.checkInterval=null),this.abortController&&(this.abortController.abort(),this.abortController=null),this.tokenManager=null);}get running(){return this.isRunning}get signal(){return this.abortController?.signal??null}async checkAndRefresh(){if(!(!this.tokenManager||!this.isRunning))try{let e=await this.tokenManager.getTokens();if(!e)return;let t=Math.floor(Date.now()/1e3);e.expiresAt-t<=this.options.thresholdSeconds&&e.refreshToken&&await this.tokenManager.refresh();}catch{}}async forceCheck(){await this.checkAndRefresh();}};R.DEFAULT_THRESHOLD_SECONDS=60,R.DEFAULT_CHECK_INTERVAL_MS=3e4;var re=R;var ne=class{constructor(e){this.crypto=e.crypto;}async calculate(e){let t=e.salt;if(!t){let c=await this.crypto.randomBytes(16);t=f(c);}let r=e.clientId+" "+e.origin+" "+e.opBrowserState+t,n=await this.crypto.sha256(r),i=f(n);return {sessionState:i+"."+t,hash:i,salt:t}}async validate(e,t){let r=this.parse(e);if(!r)return false;let n=await this.calculate({...t,salt:r.salt});return v(n.sessionState,e)}parse(e){if(!e||typeof e!="string"||e.length>512)return null;let i=e.lastIndexOf(".");if(i===-1||i===0||i===e.length-1)return null;let o=e.substring(0,i),c=e.substring(i+1);if(!o||!c||o.length>256||c.length>128)return null;let l=/^[A-Za-z0-9_-]+$/;return !l.test(o)||!l.test(c)?null:{hash:o,salt:c}}};var ie=class{build(e,t){let r=new URL(e.logoutUri),n={};return e.includeIssuer&&t.iss&&(r.searchParams.set("iss",t.iss),n.iss=t.iss),e.includeSessionId&&t.sid&&(r.searchParams.set("sid",t.sid),n.sid=t.sid),{url:r.toString(),params:n}}parseParams(e){let t=typeof e=="string"?new URL(e):e,r={},n=t.searchParams.get("iss");n&&(r.iss=n);let i=t.searchParams.get("sid");return i&&(r.sid=i),r}validateRequest(e,t={}){let r;try{r=this.parseParams(e);}catch{return {valid:false,error:"Invalid URL format"}}return t.requireIss&&!r.iss?{valid:false,error:"Missing required iss parameter"}:t.requireSid&&!r.sid?{valid:false,error:"Missing required sid parameter"}:t.issuer&&r.iss&&!v(r.iss,t.issuer)?{valid:false,error:"Issuer validation failed"}:t.sessionId&&r.sid&&!v(r.sid,t.sessionId)?{valid:false,error:"Session ID validation failed"}:{valid:true,params:r}}};var xe=["accessToken","refreshToken","idToken","token","code","password","secret","credentials","authorization","bearer","codeVerifier","code_verifier","client_secret"],fe=["code","state","nonce","id_token","access_token","refresh_token","token"],B=class{constructor(e){this.entries=[];this.maxEvents=e?.maxEvents??100,this.redactLevel=e?.redactLevel??"default";}record(e,t,r){let n=r?.redact??this.redactLevel,i=this.redactData(t,n),o={type:e,timestamp:Date.now(),operationId:r?.operationId,data:i};for(this.entries.push(o);this.entries.length>this.maxEvents;)this.entries.shift();}getRecent(e){return e===void 0?[...this.entries]:this.entries.slice(-e)}getByOperationId(e){return this.entries.filter(t=>t.operationId===e)}getByType(e){return this.entries.filter(t=>t.type===e)}clear(){this.entries=[];}get length(){return this.entries.length}toJSON(){return JSON.stringify(this.entries,null,2)}setRedactLevel(e){this.redactLevel=e;}redactData(e,t){return t==="none"||e===void 0||e===null||typeof e!="object"?e:this.deepRedact(e,t)}deepRedact(e,t){let r={};for(let[n,i]of Object.entries(e)){let o=n.toLowerCase();if(this.isSensitiveKey(o)){let c=n.charAt(0).toUpperCase()+n.slice(1);r[`has${c}`]=i!=null,r[n]="[REDACTED]";continue}if(t==="aggressive"&&o==="url"&&typeof i=="string"){r[n]=this.redactUrl(i);continue}if(i!==null&&typeof i=="object"&&!Array.isArray(i)){r[n]=this.deepRedact(i,t);continue}if(Array.isArray(i)){r[n]=i.map(c=>c!==null&&typeof c=="object"?this.deepRedact(c,t):c);continue}r[n]=i;}return r}isSensitiveKey(e){return xe.some(t=>e===t.toLowerCase()||e.includes(t.toLowerCase()))}redactUrl(e){try{let t=new URL(e);for(let r of fe)t.searchParams.has(r)&&t.searchParams.set(r,"[REDACTED]");if(t.hash){let r=new URLSearchParams(t.hash.slice(1)),n=!1;for(let i of fe)r.has(i)&&(r.set(i,"[REDACTED]"),n=!0);n&&(t.hash="#"+r.toString());}return t.toString()}catch{return e.replace(/([?&])(code|token|state|nonce)=[^&]*/gi,"$1$2=[REDACTED]")}}};function oe(s){let e=s?.timestamps??false;return {log(t,r,n){let i=e?`[Authrim:${t.toUpperCase()} ${new Date().toISOString()}]`:`[Authrim:${t.toUpperCase()}]`,o=t==="debug"?"log":t,c=typeof console<"u"?console:null;c&&(n!==void 0?c[o]?.(i,r,n):c[o]?.(i,r));}}}var se={log(){}};function me(s){return s.enabled?s.logger?s.logger:oe({timestamps:s.logTimestamps}):se}var V=class{constructor(e,t){this.operationId=null;this.logger=e,this.verbose=t?.verbose??false;}setOperationId(e){this.operationId=e;}getOperationId(){return this.operationId}debug(e,t){this.verbose&&this.logger.log("debug",this.formatMessage(e),t);}info(e,t){this.logger.log("info",this.formatMessage(e),t);}warn(e,t){this.logger.log("warn",this.formatMessage(e),t);}error(e,t){this.logger.log("error",this.formatMessage(e),t);}formatMessage(e){return this.operationId?`[${this.operationId.slice(0,8)}] ${e}`:e}};async function be(s,e){let t=await e.sha256(s),r=t.slice(0,t.length/2);return f(r)}function Pe(s,e){return new Promise((t,r)=>{let n=new a("operation_cancelled","Operation was cancelled");if(e.aborted){r(n);return}let i=()=>{r(n);};e.addEventListener("abort",i,{once:true}),s.then(t).catch(r).finally(()=>{e.removeEventListener("abort",i);});})}function Se(s){let e=new AbortController;return {promise:s(e.signal),cancel:()=>e.abort(),signal:e.signal}}function ae(s){return s instanceof a&&s.code==="operation_cancelled"}async function De(s){try{let e=await Promise.race(s.map(t=>t.promise));return s.forEach(t=>t.cancel()),e}catch(e){throw s.forEach(t=>t.cancel()),e}}var Ie={maxRetries:3,baseDelayMs:1e3,maxDelayMs:3e4,jitter:true};function ye(s,e,t,r){let n=e*Math.pow(2,s),i=Math.min(n,t);if(r){let o=i*.5,c=Math.random()*o-o/2;return Math.max(0,Math.floor(i+c))}return i}function ge(s,e){return new Promise((t,r)=>{if(e?.aborted){r(new a("operation_cancelled","Sleep was cancelled"));return}let n=setTimeout(t,s);if(e){let i=()=>{clearTimeout(n),r(new a("operation_cancelled","Sleep was cancelled"));};e.addEventListener("abort",i,{once:true});}})}async function ve(s,e){let t={...Ie,...e},{maxRetries:r,baseDelayMs:n,maxDelayMs:i,jitter:o,signal:c,shouldRetry:l,onRetry:u}=t,p;for(let d=0;d<=r;d++)try{if(c?.aborted)throw new a("operation_cancelled","Operation was cancelled");return await s()}catch(h){if(p=h,ae(h))throw h;let y=l?l(h,d):h instanceof a&&w(h);if(d>=r||!y)throw h;let C=ye(d,n,i,o);u?.(h,d+1,C),await ge(C,c);}throw p}function Oe(s){return (e,t)=>ve(e,{...s,...t})}function Me(s){let e=s instanceof Headers?s.get("retry-after"):s["retry-after"]??s["Retry-After"];if(!e)return null;let t=parseInt(e,10);if(!isNaN(t))return t*1e3;let r=new Date(e);if(!isNaN(r.getTime())){let n=r.getTime()-Date.now();return Math.max(0,n)}return null}
|
|
2
|
-
export{I as AuthorizationCodeFlow,K as AuthrimClient,a as AuthrimError,re as AutoRefreshScheduler,Q as ClientCredentialsClient,L as DPoPManager,V as DebugContext,M as DeviceFlowClient,x as DiscoveryClient,b as EventEmitter,B as EventTimeline,ie as FrontChannelLogoutUrlBuilder,ee as JARBuilder,te as JARMValidator,j as LogoutHandler,O as PARClient,
|
|
1
|
+
function $(s){return {...s,scopes:s.scopes??["openid","profile"],flowEngine:s.flowEngine??false,discoveryCacheTtlMs:s.discoveryCacheTtlMs??3600*1e3,refreshSkewSeconds:s.refreshSkewSeconds??30,stateTtlSeconds:s.stateTtlSeconds??600,hashOptions:{hashLength:s.hashOptions?.hashLength??16}}}var a=class s extends Error{constructor(e,t,r){super(t),this.name="AuthrimError",this.code=e,this.details=r?.details,this.errorUri=r?.errorUri,this.cause=r?.cause;}static fromOAuthError(e){let r=["invalid_request","unauthorized_client","access_denied","unsupported_response_type","invalid_scope","server_error","temporarily_unavailable","invalid_grant","invalid_token"].includes(e.error)?e.error:"invalid_request";return new s(r,e.error_description??e.error,{errorUri:e.error_uri,details:{originalError:e.error}})}isRetryable(){return this.code==="network_error"||this.code==="timeout_error"}get meta(){return ce(this.code)}},ke={invalid_request:{transient:false,retryable:false,userAction:"contact_support",severity:"error"},unauthorized_client:{transient:false,retryable:false,userAction:"contact_support",severity:"fatal"},access_denied:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},unsupported_response_type:{transient:false,retryable:false,userAction:"contact_support",severity:"fatal"},invalid_scope:{transient:false,retryable:false,userAction:"contact_support",severity:"error"},server_error:{transient:true,retryable:true,retryAfterMs:5e3,maxRetries:3,userAction:"retry",severity:"error"},temporarily_unavailable:{transient:true,retryable:true,retryAfterMs:1e4,maxRetries:3,userAction:"retry",severity:"warning"},invalid_grant:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},invalid_token:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},invalid_state:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},expired_state:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},invalid_nonce:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},nonce_mismatch:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},missing_nonce:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},missing_id_token:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},session_expired:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},session_check_failed:{transient:true,retryable:true,retryAfterMs:3e3,maxRetries:2,userAction:"retry",severity:"warning"},network_error:{transient:true,retryable:true,retryAfterMs:2e3,maxRetries:3,userAction:"check_network",severity:"error"},timeout_error:{transient:true,retryable:true,retryAfterMs:3e3,maxRetries:3,userAction:"retry",severity:"warning"},discovery_error:{transient:true,retryable:true,retryAfterMs:5e3,maxRetries:2,userAction:"retry",severity:"error"},discovery_mismatch:{transient:false,retryable:false,userAction:"contact_support",severity:"fatal"},configuration_error:{transient:false,retryable:false,userAction:"contact_support",severity:"fatal"},storage_error:{transient:true,retryable:true,retryAfterMs:1e3,maxRetries:2,userAction:"retry",severity:"error"},flow_engine_error:{transient:false,retryable:false,userAction:"contact_support",severity:"error"},no_tokens:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},token_expired:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},token_error:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},refresh_error:{transient:false,retryable:false,retryAfterMs:0,maxRetries:0,userAction:"reauthenticate",severity:"error"},token_exchange_error:{transient:false,retryable:false,retryAfterMs:0,maxRetries:0,userAction:"reauthenticate",severity:"error"},oauth_error:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},missing_code:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},missing_state:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},not_initialized:{transient:false,retryable:false,userAction:"none",severity:"fatal"},no_discovery:{transient:true,retryable:true,retryAfterMs:3e3,maxRetries:2,userAction:"retry",severity:"error"},no_userinfo_endpoint:{transient:false,retryable:false,userAction:"none",severity:"warning"},userinfo_error:{transient:true,retryable:true,retryAfterMs:2e3,maxRetries:2,userAction:"retry",severity:"error"},introspection_error:{transient:true,retryable:true,retryAfterMs:2e3,maxRetries:2,userAction:"retry",severity:"error"},revocation_error:{transient:true,retryable:true,retryAfterMs:2e3,maxRetries:2,userAction:"retry",severity:"error"},no_introspection_endpoint:{transient:false,retryable:false,userAction:"none",severity:"warning"},no_revocation_endpoint:{transient:false,retryable:false,userAction:"none",severity:"warning"},login_required:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},interaction_required:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},consent_required:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},account_selection_required:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},dom_not_ready:{transient:true,retryable:true,retryAfterMs:100,maxRetries:3,userAction:"retry",severity:"error"},state_mismatch:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},popup_blocked:{transient:false,retryable:false,userAction:"none",severity:"warning"},popup_closed:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},invalid_response:{transient:false,retryable:false,userAction:"contact_support",severity:"error"},invalid_callback:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},passkey_not_found:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},passkey_verification_failed:{transient:false,retryable:true,retryAfterMs:1e3,maxRetries:3,userAction:"retry",severity:"error"},passkey_not_supported:{transient:false,retryable:false,userAction:"none",severity:"warning"},passkey_cancelled:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},passkey_invalid_credential:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},email_code_invalid:{transient:false,retryable:true,retryAfterMs:0,maxRetries:5,userAction:"retry",severity:"warning"},email_code_expired:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},email_code_too_many_attempts:{transient:false,retryable:false,retryAfterMs:3e5,userAction:"retry",severity:"error"},challenge_expired:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},challenge_invalid:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},auth_code_invalid:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},auth_code_expired:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},pkce_mismatch:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},origin_not_allowed:{transient:false,retryable:false,userAction:"contact_support",severity:"fatal"},mfa_required:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},email_verification_required:{transient:false,retryable:false,userAction:"none",severity:"warning"},consent_required_direct:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},rate_limited:{transient:true,retryable:true,retryAfterMs:6e4,maxRetries:3,userAction:"retry",severity:"warning"},event_handler_error:{transient:false,retryable:false,userAction:"none",severity:"warning"},par_required:{transient:false,retryable:false,userAction:"none",severity:"fatal"},no_par_endpoint:{transient:false,retryable:false,userAction:"contact_support",severity:"fatal"},par_error:{transient:true,retryable:true,retryAfterMs:2e3,maxRetries:2,userAction:"retry",severity:"error"},par_request_uri_expired:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},no_device_authorization_endpoint:{transient:false,retryable:false,userAction:"contact_support",severity:"fatal"},device_authorization_error:{transient:true,retryable:true,retryAfterMs:2e3,maxRetries:2,userAction:"retry",severity:"error"},device_authorization_pending:{transient:true,retryable:true,retryAfterMs:5e3,maxRetries:60,userAction:"none",severity:"warning"},device_slow_down:{transient:true,retryable:true,retryAfterMs:1e4,maxRetries:60,userAction:"none",severity:"warning"},device_authorization_expired:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},device_access_denied:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},client_credentials_error:{transient:true,retryable:true,retryAfterMs:2e3,maxRetries:2,userAction:"retry",severity:"error"},invalid_client_authentication:{transient:false,retryable:false,userAction:"contact_support",severity:"fatal"},insecure_client_auth:{transient:false,retryable:false,userAction:"none",severity:"fatal"},dpop_key_generation_error:{transient:true,retryable:true,retryAfterMs:1e3,maxRetries:2,userAction:"retry",severity:"error"},dpop_proof_generation_error:{transient:false,retryable:false,userAction:"none",severity:"error"},dpop_nonce_required:{transient:true,retryable:true,retryAfterMs:0,maxRetries:1,userAction:"none",severity:"warning"},jar_signing_error:{transient:false,retryable:false,userAction:"contact_support",severity:"error"},jar_required:{transient:false,retryable:false,userAction:"none",severity:"fatal"},jarm_validation_error:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},jarm_signature_invalid:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},operation_cancelled:{transient:false,retryable:true,retryAfterMs:0,maxRetries:1,userAction:"retry",severity:"warning"},invalid_return_to:{transient:false,retryable:false,userAction:"none",severity:"error"}};function ce(s){return ke[s]}function W(s){let e=s.meta;if(!e.retryable&&e.userAction==="contact_support")return {severity:"fatal",remediation:"contact_support"};if(e.severity==="fatal")return {severity:"fatal",remediation:we(e.userAction)};let t="none";return e.retryable?t="retry":e.userAction==="reauthenticate"?t="reauthenticate":s.code==="popup_blocked"?t="switch_flow":e.userAction==="contact_support"&&(t="contact_support"),{severity:"recoverable",remediation:t}}function we(s){switch(s){case "retry":case "check_network":return "retry";case "reauthenticate":return "reauthenticate";case "contact_support":return "contact_support";default:return "none"}}function w(s){let e=W(s);return e.severity==="recoverable"&&e.remediation==="retry"}function A(s,e,t){let{severity:r,remediation:n}=W(e),i=Date.now(),o=t.source??"core",c={error:e,severity:r,remediation:n,context:t.context,timestamp:i,source:o,operationId:t.operationId};s.emit("error",c),r==="recoverable"?s.emit("error:recoverable",{...c,severity:"recoverable"}):s.emit("error:fatal",{...c,severity:"fatal"});}function T(s){return s.replace(/\/+$/,"")}var N=class N{constructor(e){this.cache=new Map;this.http=e.http,this.cacheTtlMs=e.cacheTtlMs??N.DEFAULT_CACHE_TTL_MS;}async discover(e){let t=T(e),r=this.cache.get(t);if(r&&!this.isExpired(r))return r.doc;let n=`${t}/.well-known/openid-configuration`,i;try{let c=await this.http.fetch(n);if(!c.ok)throw new a("discovery_error",`Discovery request failed: ${c.status}`,{details:{status:c.status,statusText:c.statusText}});i=c.data;}catch(c){throw c instanceof a?c:new a("discovery_error","Failed to fetch discovery document",{cause:c instanceof Error?c:void 0,details:{url:n}})}let o=T(i.issuer);if(o!==t)throw new a("discovery_mismatch",`Issuer mismatch in discovery document: expected "${t}", got "${o}"`,{details:{expected:t,actual:o}});return this.cache.set(t,{doc:i,fetchedAt:Date.now()}),i}isExpired(e){return Date.now()-e.fetchedAt>this.cacheTtlMs}clearCache(){this.cache.clear();}clearIssuer(e){this.cache.delete(T(e));}};N.DEFAULT_CACHE_TTL_MS=3600*1e3;var x=N;var b=class{constructor(){this.listeners=new Map;}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>{this.off(e,t);}}once(e,t){let r=(n=>{this.off(e,r),t(n);});return this.on(e,r)}off(e,t){let r=this.listeners.get(e);r&&(r.delete(t),r.size===0&&this.listeners.delete(e));}emit(e,t){let r=this.listeners.get(e);if(r)for(let n of r)try{n(t);}catch(i){if(e!=="error"){let o=i instanceof a?i:new a("event_handler_error","Event handler threw an error",{cause:i instanceof Error?i:void 0});this.emit("error",{error:o,context:`Error in event handler for '${e}'`});}}}removeAllListeners(e){e?this.listeners.delete(e):this.listeners.clear();}listenerCount(e){return this.listeners.get(e)?.size??0}};var S=class{constructor(e){this.crypto=e;}async generatePKCE(){let e=await this.crypto.generateCodeVerifier(),t=await this.crypto.generateCodeChallenge(e);return {codeVerifier:e,codeChallenge:t,codeChallengeMethod:"S256"}}async generateCodeVerifier(){return this.crypto.generateCodeVerifier()}async generateCodeChallenge(e){return this.crypto.generateCodeChallenge(e)}};function f(s){let e="",t=s.length;for(let r=0;r<t;r+=3){let n=s[r],i=r+1<t?s[r+1]:0,o=r+2<t?s[r+2]:0,c=n<<16|i<<8|o;e+=E[c>>18&63],e+=E[c>>12&63],e+=r+1<t?E[c>>6&63]:"",e+=r+2<t?E[c&63]:"";}return e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function le(s){if(!/^[A-Za-z0-9_-]*$/.test(s))throw new Error("Invalid base64url string: contains invalid characters");let e=s.replace(/-/g,"+").replace(/_/g,"/");for(;e.length%4;)e+="=";let t=e.length,r=e.endsWith("==")?2:e.endsWith("=")?1:0,n=t*3/4-r,i=new Uint8Array(n),o=0;for(let c=0;c<t;c+=4){let l=P[e.charCodeAt(c)],u=P[e.charCodeAt(c+1)],p=P[e.charCodeAt(c+2)],d=P[e.charCodeAt(c+3)],h=l<<18|u<<12|p<<6|d;o<n&&(i[o++]=h>>16&255),o<n&&(i[o++]=h>>8&255),o<n&&(i[o++]=h&255);}return i}function F(s){let e=new TextEncoder;return f(e.encode(s))}function J(s){return new TextDecoder().decode(le(s))}var E="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",P=new Uint8Array(256);for(let s=0;s<E.length;s++)P[E.charCodeAt(s)]=s;var m={authState:(s,e,t)=>`authrim:${s}:${e}:auth:${t}`,tokens:(s,e)=>`authrim:${s}:${e}:tokens`,idToken:(s,e)=>`authrim:${s}:${e}:id_token`,authStatePrefix:(s,e)=>`authrim:${s}:${e}:auth:`},g=class g{constructor(e,t,r,n){this.crypto=e;this.storage=t;this.issuerHash=r;this.clientIdHash=n;this.cleanupInterval=null;}async generateAuthState(e){let t=e.ttlSeconds??g.DEFAULT_TTL_SECONDS,r;e.returnTo&&(r=this.validateReturnTo(e.returnTo,e.returnToOptions??{policy:"relative_only"}));let n=await this.crypto.randomBytes(g.ENTROPY_BYTES),i=await this.crypto.randomBytes(g.ENTROPY_BYTES),o=await this.crypto.randomBytes(g.OPERATION_ID_BYTES),c=f(n),l=f(i),u=f(o),p=Date.now(),d={state:c,nonce:l,codeVerifier:e.codeVerifier,redirectUri:e.redirectUri,scope:e.scope,createdAt:p,expiresAt:p+t*1e3,returnTo:r,operationId:u},h=m.authState(this.issuerHash,this.clientIdHash,c);return await this.storage.set(h,JSON.stringify(d)),d}validateReturnTo(e,t){switch(t.policy){case "relative_only":if(e.startsWith("/")&&!e.startsWith("//")&&!e.includes(":"))return e;throw new a("invalid_return_to","returnTo must be a relative path (e.g., /dashboard)");case "same_origin":try{let r=typeof globalThis<"u"?globalThis.window:void 0,n=t.currentOrigin??r?.location?.origin;if(!n)throw new a("invalid_return_to","currentOrigin is required for same_origin policy in non-browser environments");if(e.startsWith("/")&&!e.startsWith("//")||new URL(e).origin===n)return e}catch(r){if(r instanceof a)throw r}throw new a("invalid_return_to","returnTo must be same origin or a relative path");case "allowlist":if(!t.allowedOrigins||t.allowedOrigins.length===0)throw new a("invalid_return_to","allowedOrigins is required when using allowlist policy");if(e.startsWith("/")&&!e.startsWith("//"))return e;try{let r=new URL(e);if(t.allowedOrigins.includes(r.origin))return e}catch{}throw new a("invalid_return_to",`returnTo origin not in allowlist: ${t.allowedOrigins.join(", ")}`);default:throw new a("invalid_return_to",`Unknown returnTo policy: ${t.policy}`)}}async validateAndConsumeState(e){let t=m.authState(this.issuerHash,this.clientIdHash,e);try{let r=await this.storage.get(t);if(!r)throw new a("invalid_state","State not found or already used");let n;try{n=JSON.parse(r);}catch{throw new a("invalid_state","Malformed state data")}if(Date.now()>n.expiresAt)throw new a("expired_state","State has expired");return n}finally{await this.storage.remove(t);}}async cleanupExpiredStates(){if(!this.storage.getAll)return;let e=m.authStatePrefix(this.issuerHash,this.clientIdHash),t=await this.storage.getAll(),r=Date.now();for(let[n,i]of Object.entries(t))if(n.startsWith(e))try{let o=JSON.parse(i);r>o.expiresAt&&await this.storage.remove(n);}catch{await this.storage.remove(n);}}startAutoCleanup(e=g.DEFAULT_CLEANUP_INTERVAL_MS){this.stopAutoCleanup(),this.cleanupInterval=setInterval(()=>{this.cleanupExpiredStates().catch(()=>{});},e),this.cleanupExpiredStates().catch(()=>{});}stopAutoCleanup(){this.cleanupInterval&&(clearInterval(this.cleanupInterval),this.cleanupInterval=null);}async getStoredStateCount(){if(!this.storage.getAll)return -1;let e=m.authStatePrefix(this.issuerHash,this.clientIdHash),t=await this.storage.getAll(),r=0;for(let n of Object.keys(t))n.startsWith(e)&&r++;return r}};g.DEFAULT_TTL_SECONDS=600,g.ENTROPY_BYTES=32,g.OPERATION_ID_BYTES=16,g.DEFAULT_CLEANUP_INTERVAL_MS=3e5;var D=g;function ue(s){let e=s.split(".");if(e.length!==3)throw new Error("Invalid JWT format: expected 3 parts");let[t,r,n]=e;try{let i=JSON.parse(J(t)),o=JSON.parse(J(r));return {header:i,payload:o,signature:n}}catch{throw new Error("Invalid JWT format: failed to decode")}}function de(s){return ue(s).payload}function Ae(s,e=0){if(s.exp===void 0)return false;let t=Math.floor(Date.now()/1e3);return s.exp+e<t}function G(s){try{return de(s).nonce}catch{return}}function v(s,e){let t=new TextEncoder,r=t.encode(s),n=t.encode(e),i=r.length,o=n.length,c=Math.max(i,o),l=i^o;for(let u=0;u<c;u++){let p=u<i?r[u]:0,d=u<o?n[u]:0;l|=p^d;}return l===0}var I=class{constructor(e,t){this.http=e;this.clientId=t;}buildAuthorizationUrl(e,t,r,n){if(e.require_pushed_authorization_requests&&!n.usePar)throw new a("par_required","Server requires PAR (Pushed Authorization Request) but usePar option is not enabled");if(e.require_signed_request_object&&!n.useJar)throw new a("jar_required","Server requires JAR (JWT Secured Authorization Request) but useJar option is not enabled");let i=e.authorization_endpoint,o=new URLSearchParams;o.set("client_id",this.clientId),o.set("response_type",n.responseType??"code"),o.set("redirect_uri",n.redirectUri),o.set("state",t.state),o.set("nonce",t.nonce),o.set("code_challenge",r.codeChallenge),o.set("code_challenge_method",r.codeChallengeMethod);let c=n.scope??"openid profile";if(o.set("scope",c),n.prompt&&o.set("prompt",n.prompt),n.loginHint&&o.set("login_hint",n.loginHint),n.acrValues&&o.set("acr_values",n.acrValues),n.extraParams){let p=new Set(["client_id","response_type","redirect_uri","state","nonce","code_challenge","code_challenge_method","scope"]);for(let[d,h]of Object.entries(n.extraParams))p.has(d.toLowerCase())||o.set(d,h);}let u={url:`${i}?${o.toString()}`};return n.exposeState&&(u.state=t.state,u.nonce=t.nonce),u}parseCallback(e){let t;e.includes("?")?t=(e.startsWith("http")?new URL(e):new URL(e,"https://dummy.local")).searchParams:t=new URLSearchParams(e);let r=t.get("error");if(r){let o=t.get("error_description")??"Authorization failed";throw new a("oauth_error",o,{details:{error:r,error_description:o,error_uri:t.get("error_uri")}})}let n=t.get("code"),i=t.get("state");if(!n)throw new a("missing_code","Authorization code not found in callback");if(!i)throw new a("missing_state","State parameter not found in callback");return {code:n,state:i}}async exchangeCode(e,t){let r=e.token_endpoint,n=new URLSearchParams({grant_type:"authorization_code",client_id:this.clientId,code:t.code,redirect_uri:t.redirectUri,code_verifier:t.codeVerifier}),i;try{i=await this.http.fetch(r,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n.toString()});}catch(d){throw new a("network_error","Token request failed",{cause:d instanceof Error?d:void 0})}if(!i.ok){let d=i.data;throw new a("token_error","Token exchange failed",{details:{status:i.status,error:d?.error,error_description:d?.error_description}})}let o=i.data;if(t.scope.split(" ").includes("openid")&&!o.id_token)throw new a("missing_id_token","ID token required when openid scope is requested but was not returned by the server");if(o.id_token){let d=G(o.id_token);if(d===void 0)throw new a("missing_nonce","ID token nonce claim is missing but was sent in authorization request");if(!v(d,t.nonce))throw new a("nonce_mismatch","ID token nonce does not match expected value")}let l=Math.floor(Date.now()/1e3),u=o.expires_in?l+o.expires_in:l+3600;return {accessToken:o.access_token,tokenType:o.token_type??"Bearer",expiresAt:u,refreshToken:o.refresh_token,idToken:o.id_token,scope:o.scope}}};var O=class{constructor(e,t,r){this.http=e;this.clientId=t;this.options=r;}async pushAuthorizationRequest(e,t){let r=e.pushed_authorization_request_endpoint;if(!r)throw new a("no_par_endpoint","PAR endpoint not available in discovery document");let n=new URLSearchParams;if(n.set("client_id",this.clientId),n.set("response_type",t.responseType??"code"),n.set("redirect_uri",t.redirectUri),n.set("state",t.state),n.set("nonce",t.nonce),n.set("code_challenge",t.codeChallenge),n.set("code_challenge_method",t.codeChallengeMethod),n.set("scope",t.scope??"openid profile"),t.prompt&&n.set("prompt",t.prompt),t.loginHint&&n.set("login_hint",t.loginHint),t.acrValues&&n.set("acr_values",t.acrValues),t.extraParams){let p=new Set(["client_id","response_type","redirect_uri","state","nonce","code_challenge","code_challenge_method","scope"]);for(let[d,h]of Object.entries(t.extraParams))p.has(d.toLowerCase())||n.set(d,h);}let i={"Content-Type":"application/x-www-form-urlencoded",...this.options?.headers},o;try{o=await this.http.fetch(r,{method:"POST",headers:i,body:n.toString()});}catch(p){throw new a("network_error","PAR request failed",{cause:p instanceof Error?p:void 0})}if(!o.ok){let p=o.data;throw new a("par_error","PAR request failed",{details:{status:o.status,error:p?.error,error_description:p?.error_description}})}let c=o.data;if(!c.request_uri)throw new a("par_error","PAR response missing request_uri");if(typeof c.expires_in!="number")throw new a("par_error","PAR response missing or invalid expires_in");let u=Math.floor(Date.now()/1e3)+c.expires_in;return {requestUri:c.request_uri,expiresAt:u}}buildAuthorizationUrlWithPar(e,t){let r=new URLSearchParams;return r.set("client_id",this.clientId),r.set("request_uri",t),`${e.authorization_endpoint}?${r.toString()}`}};var Te=5,M=class{constructor(e,t){this.http=e;this.clientId=t;}async startDeviceAuthorization(e,t){let r=e.device_authorization_endpoint;if(!r)throw new a("no_device_authorization_endpoint","Device authorization endpoint not available in discovery document");let n=new URLSearchParams({client_id:this.clientId});if(t?.scope&&n.set("scope",t.scope),t?.extraParams){let u=new Set(["client_id","scope"]);for(let[p,d]of Object.entries(t.extraParams))u.has(p.toLowerCase())||n.set(p,d);}let i;try{i=await this.http.fetch(r,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n.toString()});}catch(u){throw new a("network_error","Device authorization request failed",{cause:u instanceof Error?u:void 0})}if(!i.ok){let u=i.data;throw new a("device_authorization_error","Device authorization request failed",{details:{status:i.status,error:u?.error,error_description:u?.error_description}})}let o=i.data;if(!o.device_code||!o.user_code||!o.verification_uri)throw new a("device_authorization_error","Invalid device authorization response: missing required fields");let l=Math.floor(Date.now()/1e3)+o.expires_in;return {deviceCode:o.device_code,userCode:o.user_code,verificationUri:o.verification_uri,verificationUriComplete:o.verification_uri_complete,expiresAt:l,interval:o.interval??Te}}async pollOnce(e,t){let r=Math.floor(Date.now()/1e3);if(r>=t.expiresAt)return {status:"expired"};let n=e.token_endpoint,i=new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:t.deviceCode,client_id:this.clientId}),o;try{o=await this.http.fetch(n,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i.toString()});}catch(p){throw new a("network_error","Device flow token request failed",{cause:p instanceof Error?p:void 0})}if(!o.ok){let p=o.data,d=p?.error;switch(d){case "authorization_pending":return {status:"pending",retryAfter:t.interval};case "slow_down":return {status:"slow_down",retryAfter:t.interval+5};case "expired_token":return {status:"expired"};case "access_denied":return {status:"access_denied"};default:throw new a("device_authorization_error","Device flow token request failed",{details:{status:o.status,error:d,error_description:p?.error_description}})}}let c=o.data,l=c.expires_in?r+c.expires_in:r+3600;return {status:"completed",tokens:{accessToken:c.access_token,tokenType:c.token_type??"Bearer",expiresAt:l,refreshToken:c.refresh_token,idToken:c.id_token,scope:c.scope}}}async pollUntilComplete(e,t,r){let n=t.interval;for(;;){if(r?.signal?.aborted)throw new a("device_authorization_error","Device flow polling aborted");let i=await this.pollOnce(e,t);switch(i.status){case "completed":return i.tokens;case "pending":await this.sleep(i.retryAfter*1e3,r?.signal);continue;case "slow_down":n=i.retryAfter,t.interval=n,await this.sleep(n*1e3,r?.signal);continue;case "expired":throw new a("device_authorization_expired","Device authorization has expired. Please start a new authorization.");case "access_denied":throw new a("device_access_denied","User denied the device authorization request")}}}sleep(e,t){return new Promise((r,n)=>{let i=setTimeout(r,e);t&&t.addEventListener("abort",()=>{clearTimeout(i),n(new a("device_authorization_error","Device flow polling aborted"));},{once:true});})}};var L=class{constructor(e,t){this.keyPair=null;this.serverNonce=null;this.crypto=e,this.config=t??{};}async initialize(){if(!this.crypto.generateDPoPKeyPair)throw new a("dpop_key_generation_error","CryptoProvider does not support DPoP key generation");if(this.crypto.getDPoPKeyPair){let e=await this.crypto.getDPoPKeyPair();if(e){this.keyPair=e;return}}try{this.keyPair=await this.crypto.generateDPoPKeyPair(this.config.algorithm??"ES256");}catch(e){throw new a("dpop_key_generation_error","Failed to generate DPoP key pair",{cause:e instanceof Error?e:void 0})}}isInitialized(){return this.keyPair!==null}async generateProof(e,t,r){if(!this.keyPair)throw new a("dpop_proof_generation_error","DPoP manager not initialized. Call initialize() first.");let n=new URL(t),i=`${n.protocol}//${n.host}${n.pathname}`,o={typ:"dpop+jwt",alg:this.keyPair.algorithm,jwk:this.keyPair.publicKeyJwk},c=Math.floor(Date.now()/1e3),l={jti:this.generateJti(),htm:e.toUpperCase(),htu:i,iat:c};r?.accessTokenHash&&(l.ath=r.accessTokenHash),(r?.nonce??this.serverNonce)&&(l.nonce=r?.nonce??this.serverNonce??void 0);try{let u=F(JSON.stringify(o)),p=F(JSON.stringify(l)),d=`${u}.${p}`,h=await this.keyPair.sign(new TextEncoder().encode(d)),y=f(h);return `${d}.${y}`}catch(u){throw new a("dpop_proof_generation_error","Failed to generate DPoP proof",{cause:u instanceof Error?u:void 0})}}handleNonceResponse(e){this.serverNonce=e;}getServerNonce(){return this.serverNonce}clearServerNonce(){this.serverNonce=null;}getPublicKeyJwk(){return this.keyPair?.publicKeyJwk??null}getThumbprint(){return this.keyPair?.thumbprint??null}async calculateAccessTokenHash(e){let t=await this.crypto.sha256(e);return f(t)}async clear(){this.crypto.clearDPoPKeyPair&&await this.crypto.clearDPoPKeyPair(),this.keyPair=null,this.serverNonce=null;}generateJti(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).substring(2,15)}`}};var Y={access_token:"urn:ietf:params:oauth:token-type:access_token",refresh_token:"urn:ietf:params:oauth:token-type:refresh_token",id_token:"urn:ietf:params:oauth:token-type:id_token"};var _=class _{constructor(e){this.refreshPromise=null;this.discovery=null;this.expiringTimeout=null;this.isLeaderTab=true;this.currentOperationId=null;this.http=e.http,this.storage=e.storage,this.clientId=e.clientId,this.issuerHash=e.issuerHash,this.clientIdHash=e.clientIdHash,this.refreshSkewSeconds=e.refreshSkewSeconds??_.DEFAULT_REFRESH_SKEW_SECONDS,this.eventEmitter=e.eventEmitter,this.expiringThresholdMs=(e.expiringThresholdSeconds??_.DEFAULT_EXPIRING_THRESHOLD_SECONDS)*1e3,this.expiringJitterMs=e.expiringJitterMs??_.DEFAULT_EXPIRING_JITTER_MS;}setDiscovery(e){this.discovery=e;}get tokenKey(){return m.tokens(this.issuerHash,this.clientIdHash)}get idTokenKey(){return m.idToken(this.issuerHash,this.clientIdHash)}async getTokens(){let e=await this.storage.get(this.tokenKey);if(!e)return null;try{return JSON.parse(e)}catch{return await this.clearTokens(),null}}async saveTokens(e){await this.storage.set(this.tokenKey,JSON.stringify(e)),e.idToken&&await this.storage.set(this.idTokenKey,e.idToken),this.scheduleExpiringEvent(e.expiresAt);}scheduleExpiringEvent(e){if(this.expiringTimeout&&(clearTimeout(this.expiringTimeout),this.expiringTimeout=null),!this.isLeaderTab)return;let t=e*1e3,r=t-this.expiringThresholdMs,n=Math.random()*this.expiringJitterMs*2-this.expiringJitterMs,i=r-Date.now()+n;i>0&&(this.expiringTimeout=setTimeout(()=>{let o=Date.now(),c=Math.max(0,Math.floor((t-o)/1e3));this.eventEmitter?.emit("token:expiring",{expiresAt:e,expiresIn:c,timestamp:o,source:"core"});},i));}setLeaderTab(e){this.isLeaderTab=e,!e&&this.expiringTimeout&&(clearTimeout(this.expiringTimeout),this.expiringTimeout=null);}setOperationId(e){this.currentOperationId=e;}getOperationId(){return this.currentOperationId}async clearTokens(){await this.storage.remove(this.tokenKey),await this.storage.remove(this.idTokenKey);}async getAccessToken(){let e=await this.getTokens();if(!e)throw new a("no_tokens","No tokens available. Please authenticate first.");if(this.shouldRefresh(e)){if(!e.refreshToken)throw new a("token_expired","Access token expired and no refresh token available");return this.refreshWithLock(e.refreshToken)}return e.accessToken}async getIdToken(){return (await this.getTokens())?.idToken??null}shouldRefresh(e){let t=Math.floor(Date.now()/1e3);return e.expiresAt-this.refreshSkewSeconds<=t}async refreshWithLock(e,t="on_demand"){if(this.refreshPromise)return (await this.refreshPromise).accessToken;this.refreshPromise=this.doRefreshWithRetry(e,t);try{return (await this.refreshPromise).accessToken}finally{this.refreshPromise=null;}}async refresh(){let e=await this.getTokens();if(!e?.refreshToken)throw new a("no_tokens","No refresh token available");if(this.refreshPromise)return this.refreshPromise;this.refreshPromise=this.doRefreshWithRetry(e.refreshToken,"manual");try{return await this.refreshPromise}finally{this.refreshPromise=null;}}async doRefreshWithRetry(e,t="on_demand",r=0){let i=Date.now();r===0&&this.eventEmitter?.emit("token:refreshing",{reason:t,timestamp:i,source:"core",operationId:this.currentOperationId??void 0});try{return await this.doRefresh(e)}catch(o){let c=o instanceof a?o:new a("refresh_error","Token refresh failed",{cause:o instanceof Error?o:void 0}),l=r<1&&w(c);if(this.eventEmitter?.emit("token:refresh:failed",{error:c,willRetry:l,attempt:r,timestamp:Date.now(),source:"core",operationId:this.currentOperationId??void 0}),l)return this.doRefreshWithRetry(e,t,r+1);throw w(c)||this.eventEmitter?.emit("auth:required",{reason:"refresh_failed",timestamp:Date.now(),source:"core",operationId:this.currentOperationId??void 0}),o}}async doRefresh(e){if(!this.discovery)throw new a("no_discovery","Discovery document not set");let t=this.discovery.token_endpoint,r=new URLSearchParams({grant_type:"refresh_token",client_id:this.clientId,refresh_token:e}),n;try{n=await this.http.fetch(t,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:r.toString()});}catch(u){let p=new a("network_error","Token refresh request failed",{cause:u instanceof Error?u:void 0});throw this.eventEmitter?.emit("token:error",{error:p,context:"refresh",timestamp:Date.now(),source:"core"}),this.eventEmitter&&A(this.eventEmitter,p,{context:"refresh"}),p}if(!n.ok){let u=n.data,p=new a("refresh_error","Token refresh failed",{details:{status:n.status,error:u?.error,error_description:u?.error_description}});throw this.eventEmitter?.emit("token:error",{error:p,context:"refresh",timestamp:Date.now(),source:"core"}),this.eventEmitter&&A(this.eventEmitter,p,{context:"refresh"}),p}let i=n.data,o=Math.floor(Date.now()/1e3),c=i.expires_in?o+i.expires_in:o+3600,l={accessToken:i.access_token,tokenType:i.token_type??"Bearer",expiresAt:c,refreshToken:i.refresh_token??e,idToken:i.id_token,scope:i.scope};return await this.saveTokens(l),this.eventEmitter?.emit("token:refreshed",{hasAccessToken:!!l.accessToken,hasRefreshToken:!!l.refreshToken,hasIdToken:!!l.idToken,expiresAt:l.expiresAt,timestamp:Date.now(),source:"core",operationId:this.currentOperationId??void 0}),l}async isAuthenticated(){let e=await this.getTokens();if(!e)return false;let t=Math.floor(Date.now()/1e3);return e.expiresAt<=t?!!e.refreshToken:true}async exchangeToken(e){if(!this.discovery)throw new a("no_discovery","Discovery document not set");let t=this.discovery.token_endpoint,r=this.mapTokenTypeToUri(e.subjectTokenType??"access_token"),n=new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:token-exchange",client_id:this.clientId,subject_token:e.subjectToken,subject_token_type:r});e.audience&&n.set("audience",e.audience),e.scope&&n.set("scope",e.scope),e.requestedTokenType&&n.set("requested_token_type",this.mapTokenTypeToUri(e.requestedTokenType)),e.actorToken&&(n.set("actor_token",e.actorToken),e.actorTokenType&&n.set("actor_token_type",this.mapTokenTypeToUri(e.actorTokenType)));let i;try{i=await this.http.fetch(t,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n.toString()});}catch(d){let h=new a("network_error","Token exchange request failed",{cause:d instanceof Error?d:void 0});throw this.eventEmitter?.emit("token:error",{error:h,context:"exchange",timestamp:Date.now(),source:"core"}),this.eventEmitter&&A(this.eventEmitter,h,{context:"exchange"}),h}if(!i.ok){let d=i.data,h=new a("token_exchange_error","Token exchange failed",{details:{status:i.status,error:d?.error,error_description:d?.error_description}});throw this.eventEmitter?.emit("token:error",{error:h,context:"exchange",timestamp:Date.now(),source:"core"}),this.eventEmitter&&A(this.eventEmitter,h,{context:"exchange"}),h}let o=i.data,c=Math.floor(Date.now()/1e3),l=o.expires_in?c+o.expires_in:c+3600,u={accessToken:o.access_token,tokenType:o.token_type??"Bearer",expiresAt:l,refreshToken:o.refresh_token,idToken:o.id_token,scope:o.scope},p={tokens:u,issuedTokenType:o.issued_token_type};return this.eventEmitter?.emit("token:exchanged",{hasAccessToken:!!u.accessToken,hasRefreshToken:!!u.refreshToken,issuedTokenType:o.issued_token_type,timestamp:Date.now(),source:"core",operationId:this.currentOperationId??void 0}),p}mapTokenTypeToUri(e){return Y[e]}destroy(){this.expiringTimeout&&(clearTimeout(this.expiringTimeout),this.expiringTimeout=null);}};_.DEFAULT_REFRESH_SKEW_SECONDS=30,_.DEFAULT_EXPIRING_THRESHOLD_SECONDS=300,_.DEFAULT_EXPIRING_JITTER_MS=3e4;var H=_;var U=class{constructor(e){this.http=e.http,this.clientId=e.clientId;}async introspect(e,t){let r=e.introspection_endpoint;if(!r)throw new a("no_introspection_endpoint","Authorization server does not support token introspection");return this.introspectWithEndpoint(r,t)}async introspectWithEndpoint(e,t){let r=new URLSearchParams({client_id:this.clientId,token:t.token});t.tokenTypeHint&&r.set("token_type_hint",t.tokenTypeHint);let n;try{n=await this.http.fetch(e,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:r.toString()});}catch(i){throw new a("network_error","Token introspection request failed",{cause:i instanceof Error?i:void 0})}if(!n.ok){let i=n.data;throw new a("introspection_error","Token introspection failed",{details:{status:n.status,error:i?.error,error_description:i?.error_description}})}return n.data}async isActive(e,t){return (await this.introspect(e,{token:t})).active}};var k=class{constructor(e){this.http=e.http,this.clientId=e.clientId;}async revoke(e,t){let r=e.revocation_endpoint;if(!r)throw new a("no_revocation_endpoint","Authorization server does not support token revocation");let n=new URLSearchParams({client_id:this.clientId,token:t.token});t.tokenTypeHint&&n.set("token_type_hint",t.tokenTypeHint);let i;try{i=await this.http.fetch(r,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n.toString()});}catch(c){throw new a("network_error","Token revocation request failed",{cause:c instanceof Error?c:void 0})}if(i.ok)return;let o=i.data;throw new a("revocation_error","Token revocation failed",{details:{status:i.status,error:o?.error,error_description:o?.error_description}})}async revokeWithEndpoint(e,t){let r=new URLSearchParams({client_id:this.clientId,token:t.token});t.tokenTypeHint&&r.set("token_type_hint",t.tokenTypeHint);let n;try{n=await this.http.fetch(e,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:r.toString()});}catch(o){throw new a("network_error","Token revocation request failed",{cause:o instanceof Error?o:void 0})}if(n.ok)return;let i=n.data;throw new a("revocation_error","Token revocation failed",{details:{status:n.status,error:i?.error,error_description:i?.error_description}})}};var j=class{constructor(e){this.storage=e.storage,this.clientId=e.clientId,this.issuerHash=e.issuerHash,this.clientIdHash=e.clientIdHash,this.eventEmitter=e.eventEmitter,this.endpoints=e.endpoints,this.tokenRevoker=new k({http:e.http,clientId:e.clientId});}async logout(e,t){let r=await this.getStoredIdToken(),n=await this.getStoredTokens(),i;t?.revokeTokens&&e?.revocation_endpoint&&n&&(i=await this.revokeTokens(e,n)),await this.clearTokens(),this.eventEmitter?.emit("session:ended",{reason:"logout",timestamp:Date.now(),source:"core"});let o;if(this.endpoints?.endSession!==void 0?o=this.endpoints.endSession:e&&(o=e.end_session_endpoint),!o)return {localOnly:true,revocation:i};let c=t?.idTokenHint??r,l=new URLSearchParams({client_id:this.clientId});return c&&l.set("id_token_hint",c),t?.postLogoutRedirectUri&&l.set("post_logout_redirect_uri",t.postLogoutRedirectUri),t?.state&&l.set("state",t.state),{logoutUrl:`${o}?${l.toString()}`,localOnly:false,revocation:i}}async revokeTokens(e,t){let r={attempted:true};try{t.refreshToken&&(await this.tokenRevoker.revoke(e,{token:t.refreshToken,tokenTypeHint:"refresh_token"}),r.refreshTokenRevoked=!0),await this.tokenRevoker.revoke(e,{token:t.accessToken,tokenTypeHint:"access_token"}),r.accessTokenRevoked=!0;}catch(n){r.error=n instanceof Error?n:new Error(String(n));}return r}async clearTokens(){let e=m.tokens(this.issuerHash,this.clientIdHash),t=m.idToken(this.issuerHash,this.clientIdHash);await this.storage.remove(e),await this.storage.remove(t);}async getStoredIdToken(){let e=m.idToken(this.issuerHash,this.clientIdHash);return this.storage.get(e)}async getStoredTokens(){let e=m.tokens(this.issuerHash,this.clientIdHash),t=await this.storage.get(e);if(!t)return null;try{return JSON.parse(t)}catch{return null}}};var q=class{constructor(e){this.http=e.http;}async checkSession(e,t){let r=e.userinfo_endpoint;if(!r)return {valid:false,error:new a("no_userinfo_endpoint","UserInfo endpoint not available")};try{let n=await this.http.fetch(r,{method:"GET",headers:{Authorization:`Bearer ${t}`}});return n.ok?{valid:!0,user:n.data}:n.status===401?{valid:!1,error:new a("session_expired","Session has expired")}:{valid:!1,error:new a("session_check_failed","Session check failed",{details:{status:n.status}})}}catch(n){return {valid:false,error:new a("network_error","Failed to check session",{cause:n instanceof Error?n:void 0})}}}async getUserInfo(e,t){let r=e.userinfo_endpoint;if(!r)throw new a("no_userinfo_endpoint","UserInfo endpoint not available");let n;try{n=await this.http.fetch(r,{method:"GET",headers:{Authorization:`Bearer ${t}`}});}catch(i){throw new a("network_error","Failed to fetch user info",{cause:i instanceof Error?i:void 0})}if(!n.ok)throw new a("userinfo_error","Failed to get user info",{details:{status:n.status}});return n.data}};var z=class{constructor(e){this.discovery=null;this.tokenManager=e.tokenManager,this.tokenApiClient=e.tokenApiClient;}setDiscovery(e){this.discovery=e;}async isAuthenticated(){return this.tokenManager.isAuthenticated()}async checkSession(){if(!this.discovery)return {valid:false,error:new a("no_discovery","Discovery document not available")};try{let e=await this.tokenManager.getAccessToken();return this.tokenApiClient.checkSession(this.discovery,e)}catch(e){return e instanceof a?{valid:false,error:e}:{valid:false,error:new a("session_check_failed","Failed to check session",{cause:e instanceof Error?e:void 0})}}}async getUser(){if(!this.discovery)throw new a("no_discovery","Discovery document not available");let e=await this.tokenManager.getAccessToken();return this.tokenApiClient.getUserInfo(this.discovery,e)}};async function pe(s,e,t=16){let r=await s.sha256(e);return f(r).slice(0,t)}var K=class{constructor(e){this.dpopManager=null;this.initialized=false;this.config=$(e),this.normalizedIssuer=T(e.issuer),this.events=new b,this.discoveryClient=new x({http:this.config.http,cacheTtlMs:this.config.discoveryCacheTtlMs}),this.pkce=new S(this.config.crypto),this.authCodeFlow=new I(this.config.http,this.config.clientId),this.parClient=new O(this.config.http,this.config.clientId),this.deviceFlowClient=new M(this.config.http,this.config.clientId);}get eventEmitter(){return this.events}async initialize(){if(this.initialized)return;let e=this.config.hashOptions.hashLength;this.issuerHash=await pe(this.config.crypto,this.normalizedIssuer,e),this.clientIdHash=await pe(this.config.crypto,this.config.clientId,e),this.stateManager=new D(this.config.crypto,this.config.storage,this.issuerHash,this.clientIdHash),this.tokenManager=new H({http:this.config.http,storage:this.config.storage,clientId:this.config.clientId,issuerHash:this.issuerHash,clientIdHash:this.clientIdHash,refreshSkewSeconds:this.config.refreshSkewSeconds,eventEmitter:this.events}),this.logoutHandler=new j({storage:this.config.storage,http:this.config.http,clientId:this.config.clientId,issuerHash:this.issuerHash,clientIdHash:this.clientIdHash,eventEmitter:this.events,endpoints:this.config.endpoints}),this.tokenIntrospector=new U({http:this.config.http,clientId:this.config.clientId}),this.tokenRevoker=new k({http:this.config.http,clientId:this.config.clientId});let t=new q({http:this.config.http});this.sessionManager=new z({tokenManager:this.tokenManager,tokenApiClient:t}),await this.stateManager.cleanupExpiredStates(),this.initialized=true;}ensureInitialized(){if(!this.initialized)throw new a("not_initialized","Client not initialized. Use createAuthrimClient().")}async discover(){let e=await this.discoveryClient.discover(this.normalizedIssuer);return this.tokenManager.setDiscovery(e),this.sessionManager.setDiscovery(e),e}async buildAuthorizationUrl(e){this.ensureInitialized();let t=await this.discover(),r=await this.pkce.generatePKCE(),n=e.scope??"openid profile",i=await this.stateManager.generateAuthState({redirectUri:e.redirectUri,codeVerifier:r.codeVerifier,scope:n,ttlSeconds:this.config.stateTtlSeconds}),o=this.authCodeFlow.buildAuthorizationUrl(t,i,r,e);return this.events.emit("auth:redirecting",{url:o.url,timestamp:Date.now(),source:"core",operationId:i.operationId}),o}async handleCallback(e){this.ensureInitialized();let{code:t,state:r}=this.authCodeFlow.parseCallback(e),n=await this.stateManager.validateAndConsumeState(r),i=n.operationId;this.events.emit("auth:callback",{code:t,state:r,timestamp:Date.now(),source:"core",operationId:i}),this.events.emit("auth:callback:processing",{state:r,timestamp:Date.now(),source:"core",operationId:i});try{let o=await this.discover(),c=await this.authCodeFlow.exchangeCode(o,{code:t,state:r,redirectUri:n.redirectUri,codeVerifier:n.codeVerifier,nonce:n.nonce,scope:n.scope});return await this.tokenManager.saveTokens(c),this.events.emit("auth:callback:complete",{success:!0,timestamp:Date.now(),source:"core",operationId:i}),c}catch(o){throw this.events.emit("auth:callback:complete",{success:false,timestamp:Date.now(),source:"core",operationId:i}),o}}get par(){return {push:async e=>{this.ensureInitialized();let t=await this.discover(),r=await this.pkce.generatePKCE(),n=e.scope??"openid profile",i=await this.stateManager.generateAuthState({redirectUri:e.redirectUri,codeVerifier:r.codeVerifier,scope:n,ttlSeconds:this.config.stateTtlSeconds});return this.parClient.pushAuthorizationRequest(t,{redirectUri:e.redirectUri,scope:n,state:i.state,nonce:i.nonce,codeChallenge:r.codeChallenge,codeChallengeMethod:"S256",prompt:e.prompt,loginHint:e.loginHint,acrValues:e.acrValues,extraParams:e.extraParams})},buildAuthorizationUrl:async e=>{let t=await this.discover();return this.parClient.buildAuthorizationUrlWithPar(t,e)},isAvailable:async()=>!!(await this.discover()).pushed_authorization_request_endpoint,isRequired:async()=>(await this.discover()).require_pushed_authorization_requests===true}}get deviceFlow(){return {start:async e=>{this.ensureInitialized();let t=await this.discover();return this.deviceFlowClient.startDeviceAuthorization(t,e)},pollOnce:async e=>{let t=await this.discover();return this.deviceFlowClient.pollOnce(t,e)},pollUntilComplete:async(e,t)=>{let r=await this.discover(),n=await this.deviceFlowClient.pollUntilComplete(r,e,t);return await this.tokenManager.saveTokens(n),n},isAvailable:async()=>!!(await this.discover()).device_authorization_endpoint}}get dpop(){if(!this.config.crypto.generateDPoPKeyPair)return;this.dpopManager||(this.dpopManager=new L(this.config.crypto));let t=this.dpopManager;return {initialize:()=>t.initialize(),isInitialized:()=>t.isInitialized(),generateProof:(r,n,i)=>t.generateProof(r,n,i),handleNonceResponse:r=>t.handleNonceResponse(r),calculateAccessTokenHash:r=>t.calculateAccessTokenHash(r),getPublicKeyJwk:()=>t.getPublicKeyJwk(),getThumbprint:()=>t.getThumbprint(),clear:()=>t.clear(),isServerSupported:async()=>{let r=await this.discover();return Array.isArray(r.dpop_signing_alg_values_supported)&&r.dpop_signing_alg_values_supported.length>0}}}get token(){return this.ensureInitialized(),{getAccessToken:()=>this.tokenManager.getAccessToken(),getTokens:()=>this.tokenManager.getTokens(),getIdToken:()=>this.tokenManager.getIdToken(),isAuthenticated:()=>this.tokenManager.isAuthenticated(),exchange:async e=>(await this.discover(),this.tokenManager.exchangeToken(e)),introspect:async e=>{let t=await this.discover();return this.tokenIntrospector.introspect(t,e)},revoke:async e=>{let t=await this.discover();return this.tokenRevoker.revoke(t,e)}}}get session(){return this.ensureInitialized(),{isAuthenticated:()=>this.sessionManager.isAuthenticated(),check:()=>this.sessionManager.checkSession()}}async isAuthenticated(){return this.ensureInitialized(),this.tokenManager.isAuthenticated()}async getUser(){return this.ensureInitialized(),this.sessionManager.getUser()}async logout(e){this.ensureInitialized();let t=null;try{t=await this.discover();}catch{}return this.logoutHandler.logout(t,e)}on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}off(e,t){this.events.off(e,t);}};async function Ee(s){let e=new K(s);return await e.initialize(),e}var he=new Set(["login_required","interaction_required","consent_required","account_selection_required"]),X=class{constructor(e){this.clientId=e;}buildSilentAuthUrl(e,t,r,n){let i=e.authorization_endpoint,o=new URLSearchParams;o.set("client_id",this.clientId),o.set("response_type",n.responseType??"code"),o.set("redirect_uri",n.redirectUri),o.set("state",t.state),o.set("nonce",t.nonce),o.set("prompt","none"),o.set("code_challenge",r.codeChallenge),o.set("code_challenge_method",r.codeChallengeMethod);let c=n.scope??"openid";if(o.set("scope",c),n.loginHint&&o.set("login_hint",n.loginHint),n.idTokenHint&&o.set("id_token_hint",n.idTokenHint),n.extraParams){let p=new Set(["client_id","response_type","redirect_uri","state","nonce","code_challenge","code_challenge_method","scope","prompt"]);for(let[d,h]of Object.entries(n.extraParams))p.has(d.toLowerCase())||o.set(d,h);}let u={url:`${i}?${o.toString()}`};return n.exposeState&&(u.state=t.state,u.nonce=t.nonce),u}parseSilentAuthResponse(e){let t;e.includes("?")?t=(e.startsWith("http")?new URL(e):new URL(e,"https://dummy.local")).searchParams:t=new URLSearchParams(e);let r=t.get("error");if(r){let o=t.get("error_description"),c=this.mapSilentAuthError(r);return {success:false,error:new a(c,o??this.getDefaultErrorMessage(r),{details:{error:r,error_description:o,error_uri:t.get("error_uri")}})}}let n=t.get("code"),i=t.get("state");return n?i?{success:true,code:n,state:i}:{success:false,error:new a("missing_state","State parameter not found in silent auth response")}:{success:false,error:new a("missing_code","Authorization code not found in silent auth response")}}isInteractiveLoginRequired(e){return he.has(e.code)}mapSilentAuthError(e){return he.has(e)?e:"oauth_error"}getDefaultErrorMessage(e){switch(e){case "login_required":return "User must log in - no active session found";case "interaction_required":return "User interaction required";case "consent_required":return "User consent required";case "account_selection_required":return "User must select an account";default:return "Silent authentication failed"}}};async function Z(s,e,t){let r={},n={};switch(s.method){case "client_secret_basic":{let i=btoa(`${e}:${s.clientSecret}`);r.Authorization=`Basic ${i}`;break}case "client_secret_post":{n.client_id=e,n.client_secret=s.clientSecret;break}case "private_key_jwt":{let i=Math.floor(Date.now()/1e3),o={iss:e,sub:e,aud:t,jti:Re(),exp:i+300,iat:i},c;try{c=await s.signJwt(o);}catch(l){throw new a("invalid_client_authentication","Failed to sign client assertion JWT",{cause:l instanceof Error?l:void 0})}n.client_id=e,n.client_assertion_type="urn:ietf:params:oauth:client-assertion-type:jwt-bearer",n.client_assertion=c;break}case "none":{if(!("dangerouslyAllowInsecure"in s)||s.dangerouslyAllowInsecure!==true)throw new a("insecure_client_auth",'Client authentication method "none" requires dangerouslyAllowInsecure: true');n.client_id=e;break}default:{let i=s;throw new a("invalid_client_authentication",`Unknown client authentication method: ${i.method}`)}}return {headers:r,bodyParams:n}}function Re(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).substring(2,15)}`}var Q=class{constructor(e){this.http=e.http,this.clientId=e.clientId,this.credentials=e.credentials;}async getToken(e,t){let r=e.token_endpoint,{headers:n,bodyParams:i}=await Z(this.credentials,this.clientId,r),o=new URLSearchParams({grant_type:"client_credentials",...i});if(t?.scope&&o.set("scope",t.scope),t?.audience&&o.set("audience",t.audience),t?.extraParams){let y=new Set(["grant_type","client_id","client_secret","client_assertion","client_assertion_type","scope","audience"]);for(let[C,_e]of Object.entries(t.extraParams))y.has(C.toLowerCase())||o.set(C,_e);}let c={"Content-Type":"application/x-www-form-urlencoded",...n},l;try{l=await this.http.fetch(r,{method:"POST",headers:c,body:o.toString()});}catch(y){throw new a("network_error","Client credentials token request failed",{cause:y instanceof Error?y:void 0})}if(!l.ok){let y=l.data;throw new a("client_credentials_error","Client credentials token request failed",{details:{status:l.status,error:y?.error,error_description:y?.error_description}})}let u=l.data,p=Math.floor(Date.now()/1e3),d=u.expires_in?p+u.expires_in:p+3600;return {accessToken:u.access_token,tokenType:u.token_type??"Bearer",expiresAt:d,refreshToken:u.refresh_token,scope:u.scope}}};var ee=class{constructor(e){this.config=e;}async buildRequestObject(e){let t=Math.floor(Date.now()/1e3),r=this.config.lifetime??300,n={alg:this.config.algorithm??"RS256",typ:"oauth-authz-req+jwt"};this.config.keyId&&(n.kid=this.config.keyId);let i={iss:e.clientId,aud:e.issuer,response_type:e.responseType??"code",client_id:e.clientId,redirect_uri:e.redirectUri,scope:e.scope,state:e.state,nonce:e.nonce,code_challenge:e.codeChallenge,code_challenge_method:e.codeChallengeMethod,iat:t,exp:t+r,jti:this.generateJti()};if(e.prompt&&(i.prompt=e.prompt),e.loginHint&&(i.login_hint=e.loginHint),e.acrValues&&(i.acr_values=e.acrValues),e.extraClaims){let o=new Set(["iss","aud","response_type","client_id","redirect_uri","scope","state","nonce","code_challenge","code_challenge_method","iat","exp","jti","nbf"]);for(let[c,l]of Object.entries(e.extraClaims))o.has(c)||(i[c]=l);}try{return await this.config.signJwt(n,i)}catch(o){throw new a("jar_signing_error","Failed to sign JAR request object",{cause:o instanceof Error?o:void 0})}}generateJti(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).substring(2,15)}`}};function Ce(s){return s.require_signed_request_object===true}var te=class{constructor(e){this.config=e;}async validateResponse(e,t,r){let n=r.clockSkewSeconds??60,i;try{i=await this.config.verifyJwt(t,e.issuer);}catch(l){throw new a("jarm_signature_invalid","Failed to verify JARM response signature",{cause:l instanceof Error?l:void 0})}if(i.iss!==e.issuer)throw new a("jarm_validation_error","JARM response issuer does not match discovery issuer",{details:{expected:e.issuer,actual:i.iss}});if(!(Array.isArray(i.aud)?i.aud:[i.aud]).includes(r.clientId))throw new a("jarm_validation_error","JARM response audience does not match client_id",{details:{expected:r.clientId,actual:i.aud}});let c=Math.floor(Date.now()/1e3);if(i.exp&&i.exp+n<c)throw new a("jarm_validation_error","JARM response has expired");if(i.iat&&i.iat-n>c)throw new a("jarm_validation_error","JARM response iat is in the future");if(i.error)throw new a("oauth_error",i.error_description??i.error,{details:{error:i.error,error_description:i.error_description,error_uri:i.error_uri}});if(!i.state)throw new a("jarm_validation_error","JARM response is missing state claim");if(!v(i.state,r.expectedState))throw new a("jarm_validation_error","JARM response state does not match expected state");if(!i.code)throw new a("jarm_validation_error","JARM response is missing authorization code");return {code:i.code,state:i.state}}static extractResponseFromCallback(e){let t;return e.includes("?")?t=(e.startsWith("http")?new URL(e):new URL(e,"https://dummy.local")).searchParams:t=new URLSearchParams(e),t.get("response")}};var R=class R{constructor(e){this.tokenManager=null;this.checkInterval=null;this.abortController=null;this.isRunning=false;this.options={thresholdSeconds:e?.thresholdSeconds??R.DEFAULT_THRESHOLD_SECONDS,checkIntervalMs:e?.checkIntervalMs??R.DEFAULT_CHECK_INTERVAL_MS,eventEmitter:e?.eventEmitter};}start(e){this.isRunning||(this.tokenManager=e,this.abortController=new AbortController,this.isRunning=true,this.checkInterval=setInterval(()=>{this.checkAndRefresh().catch(()=>{});},this.options.checkIntervalMs),this.checkAndRefresh().catch(()=>{}));}stop(){this.isRunning&&(this.isRunning=false,this.checkInterval&&(clearInterval(this.checkInterval),this.checkInterval=null),this.abortController&&(this.abortController.abort(),this.abortController=null),this.tokenManager=null);}get running(){return this.isRunning}get signal(){return this.abortController?.signal??null}async checkAndRefresh(){if(!(!this.tokenManager||!this.isRunning))try{let e=await this.tokenManager.getTokens();if(!e)return;let t=Math.floor(Date.now()/1e3);e.expiresAt-t<=this.options.thresholdSeconds&&e.refreshToken&&await this.tokenManager.refresh();}catch{}}async forceCheck(){await this.checkAndRefresh();}};R.DEFAULT_THRESHOLD_SECONDS=60,R.DEFAULT_CHECK_INTERVAL_MS=3e4;var re=R;var ne=class{constructor(e){this.crypto=e.crypto;}async calculate(e){let t=e.salt;if(!t){let c=await this.crypto.randomBytes(16);t=f(c);}let r=e.clientId+" "+e.origin+" "+e.opBrowserState+t,n=await this.crypto.sha256(r),i=f(n);return {sessionState:i+"."+t,hash:i,salt:t}}async validate(e,t){let r=this.parse(e);if(!r)return false;let n=await this.calculate({...t,salt:r.salt});return v(n.sessionState,e)}parse(e){if(!e||typeof e!="string"||e.length>512)return null;let i=e.lastIndexOf(".");if(i===-1||i===0||i===e.length-1)return null;let o=e.substring(0,i),c=e.substring(i+1);if(!o||!c||o.length>256||c.length>128)return null;let l=/^[A-Za-z0-9_-]+$/;return !l.test(o)||!l.test(c)?null:{hash:o,salt:c}}};var ie=class{build(e,t){let r=new URL(e.logoutUri),n={};return e.includeIssuer&&t.iss&&(r.searchParams.set("iss",t.iss),n.iss=t.iss),e.includeSessionId&&t.sid&&(r.searchParams.set("sid",t.sid),n.sid=t.sid),{url:r.toString(),params:n}}parseParams(e){let t=typeof e=="string"?new URL(e):e,r={},n=t.searchParams.get("iss");n&&(r.iss=n);let i=t.searchParams.get("sid");return i&&(r.sid=i),r}validateRequest(e,t={}){let r;try{r=this.parseParams(e);}catch{return {valid:false,error:"Invalid URL format"}}return t.requireIss&&!r.iss?{valid:false,error:"Missing required iss parameter"}:t.requireSid&&!r.sid?{valid:false,error:"Missing required sid parameter"}:t.issuer&&r.iss&&!v(r.iss,t.issuer)?{valid:false,error:"Issuer validation failed"}:t.sessionId&&r.sid&&!v(r.sid,t.sessionId)?{valid:false,error:"Session ID validation failed"}:{valid:true,params:r}}};var xe=["accessToken","refreshToken","idToken","token","code","password","secret","credentials","authorization","bearer","codeVerifier","code_verifier","client_secret"],fe=["code","state","nonce","id_token","access_token","refresh_token","token"],B=class{constructor(e){this.entries=[];this.maxEvents=e?.maxEvents??100,this.redactLevel=e?.redactLevel??"default";}record(e,t,r){let n=r?.redact??this.redactLevel,i=this.redactData(t,n),o={type:e,timestamp:Date.now(),operationId:r?.operationId,data:i};for(this.entries.push(o);this.entries.length>this.maxEvents;)this.entries.shift();}getRecent(e){return e===void 0?[...this.entries]:this.entries.slice(-e)}getByOperationId(e){return this.entries.filter(t=>t.operationId===e)}getByType(e){return this.entries.filter(t=>t.type===e)}clear(){this.entries=[];}get length(){return this.entries.length}toJSON(){return JSON.stringify(this.entries,null,2)}setRedactLevel(e){this.redactLevel=e;}redactData(e,t){return t==="none"||e===void 0||e===null||typeof e!="object"?e:this.deepRedact(e,t)}deepRedact(e,t){let r={};for(let[n,i]of Object.entries(e)){let o=n.toLowerCase();if(this.isSensitiveKey(o)){let c=n.charAt(0).toUpperCase()+n.slice(1);r[`has${c}`]=i!=null,r[n]="[REDACTED]";continue}if(t==="aggressive"&&o==="url"&&typeof i=="string"){r[n]=this.redactUrl(i);continue}if(i!==null&&typeof i=="object"&&!Array.isArray(i)){r[n]=this.deepRedact(i,t);continue}if(Array.isArray(i)){r[n]=i.map(c=>c!==null&&typeof c=="object"?this.deepRedact(c,t):c);continue}r[n]=i;}return r}isSensitiveKey(e){return xe.some(t=>e===t.toLowerCase()||e.includes(t.toLowerCase()))}redactUrl(e){try{let t=new URL(e);for(let r of fe)t.searchParams.has(r)&&t.searchParams.set(r,"[REDACTED]");if(t.hash){let r=new URLSearchParams(t.hash.slice(1)),n=!1;for(let i of fe)r.has(i)&&(r.set(i,"[REDACTED]"),n=!0);n&&(t.hash="#"+r.toString());}return t.toString()}catch{return e.replace(/([?&])(code|token|state|nonce)=[^&]*/gi,"$1$2=[REDACTED]")}}};function oe(s){let e=s?.timestamps??false;return {log(t,r,n){let i=e?`[Authrim:${t.toUpperCase()} ${new Date().toISOString()}]`:`[Authrim:${t.toUpperCase()}]`,o=t==="debug"?"log":t,c=typeof console<"u"?console:null;c&&(n!==void 0?c[o]?.(i,r,n):c[o]?.(i,r));}}}var se={log(){}};function me(s){return s.enabled?s.logger?s.logger:oe({timestamps:s.logTimestamps}):se}var V=class{constructor(e,t){this.operationId=null;this.logger=e,this.verbose=t?.verbose??false;}setOperationId(e){this.operationId=e;}getOperationId(){return this.operationId}debug(e,t){this.verbose&&this.logger.log("debug",this.formatMessage(e),t);}info(e,t){this.logger.log("info",this.formatMessage(e),t);}warn(e,t){this.logger.log("warn",this.formatMessage(e),t);}error(e,t){this.logger.log("error",this.formatMessage(e),t);}formatMessage(e){return this.operationId?`[${this.operationId.slice(0,8)}] ${e}`:e}};async function be(s,e){let t=await e.sha256(s),r=t.slice(0,t.length/2);return f(r)}function Se(s,e){return new Promise((t,r)=>{let n=new a("operation_cancelled","Operation was cancelled");if(e.aborted){r(n);return}let i=()=>{r(n);};e.addEventListener("abort",i,{once:true}),s.then(t).catch(r).finally(()=>{e.removeEventListener("abort",i);});})}function Pe(s){let e=new AbortController;return {promise:s(e.signal),cancel:()=>e.abort(),signal:e.signal}}function ae(s){return s instanceof a&&s.code==="operation_cancelled"}async function De(s){try{let e=await Promise.race(s.map(t=>t.promise));return s.forEach(t=>t.cancel()),e}catch(e){throw s.forEach(t=>t.cancel()),e}}var Ie={maxRetries:3,baseDelayMs:1e3,maxDelayMs:3e4,jitter:true};function ye(s,e,t,r){let n=e*Math.pow(2,s),i=Math.min(n,t);if(r){let o=i*.5,c=Math.random()*o-o/2;return Math.max(0,Math.floor(i+c))}return i}function ge(s,e){return new Promise((t,r)=>{if(e?.aborted){r(new a("operation_cancelled","Sleep was cancelled"));return}let n=setTimeout(t,s);if(e){let i=()=>{clearTimeout(n),r(new a("operation_cancelled","Sleep was cancelled"));};e.addEventListener("abort",i,{once:true});}})}async function ve(s,e){let t={...Ie,...e},{maxRetries:r,baseDelayMs:n,maxDelayMs:i,jitter:o,signal:c,shouldRetry:l,onRetry:u}=t,p;for(let d=0;d<=r;d++)try{if(c?.aborted)throw new a("operation_cancelled","Operation was cancelled");return await s()}catch(h){if(p=h,ae(h))throw h;let y=l?l(h,d):h instanceof a&&w(h);if(d>=r||!y)throw h;let C=ye(d,n,i,o);u?.(h,d+1,C),await ge(C,c);}throw p}function Oe(s){return (e,t)=>ve(e,{...s,...t})}function Me(s){let e=s instanceof Headers?s.get("retry-after"):s["retry-after"]??s["Retry-After"];if(!e)return null;let t=parseInt(e,10);if(!isNaN(t))return t*1e3;let r=new Date(e);if(!isNaN(r.getTime())){let n=r.getTime()-Date.now();return Math.max(0,n)}return null}
|
|
2
|
+
export{I as AuthorizationCodeFlow,K as AuthrimClient,a as AuthrimError,re as AutoRefreshScheduler,Q as ClientCredentialsClient,L as DPoPManager,V as DebugContext,M as DeviceFlowClient,x as DiscoveryClient,b as EventEmitter,B as EventTimeline,ie as FrontChannelLogoutUrlBuilder,ee as JARBuilder,te as JARMValidator,j as LogoutHandler,O as PARClient,S as PKCEHelper,m as STORAGE_KEYS,z as SessionManager,ne as SessionStateCalculator,X as SilentAuthHandler,D as StateManager,Y as TOKEN_TYPE_URIS,q as TokenApiClient,U as TokenIntrospector,H as TokenManager,k as TokenRevoker,le as base64urlDecode,f as base64urlEncode,J as base64urlToString,Z as buildClientAuthentication,ye as calculateBackoffDelay,be as calculateDsHash,W as classifyError,Ee as createAuthrimClient,Pe as createCancellableOperation,oe as createConsoleLogger,me as createDebugLogger,Oe as createRetryFunction,de as decodeIdToken,ue as decodeJwt,A as emitClassifiedError,ce as getErrorMeta,G as getIdTokenNonce,ae as isCancellationError,Ce as isJarRequired,Ae as isJwtExpired,w as isRetryableError,se as noopLogger,T as normalizeIssuer,Me as parseRetryAfterHeader,De as raceWithCancellation,$ as resolveConfig,ge as sleep,F as stringToBase64url,v as timingSafeEqual,Se as withAbortSignal,ve as withRetry};//# sourceMappingURL=index.js.map
|
|
3
3
|
//# sourceMappingURL=index.js.map
|