@authrim/core 0.1.12 → 0.1.13

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 CHANGED
@@ -1,3 +1,3 @@
1
- 'use strict';function W(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 le(this.code)}},Ae={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 le(s){return Ae[s]}function G(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:Te(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 Te(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=G(s);return e.severity==="recoverable"&&e.remediation==="retry"}function A(s,e,t){let{severity:r,remediation:n}=G(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 F=class F{constructor(e){this.cache=new Map;this.http=e.http,this.cacheTtlMs=e.cacheTtlMs??F.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));}};F.DEFAULT_CACHE_TTL_MS=3600*1e3;var C=F;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 g(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 de(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=D[e.charCodeAt(c)],d=D[e.charCodeAt(c+1)],u=D[e.charCodeAt(c+2)],p=D[e.charCodeAt(c+3)],h=l<<18|d<<12|u<<6|p;o<n&&(i[o++]=h>>16&255),o<n&&(i[o++]=h>>8&255),o<n&&(i[o++]=h&255);}return i}function J(s){let e=new TextEncoder;return g(e.encode(s))}function V(s){return new TextDecoder().decode(de(s))}var E="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",D=new Uint8Array(256);for(let s=0;s<E.length;s++)D[E.charCodeAt(s)]=s;var f={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:`},m=class m{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??m.DEFAULT_TTL_SECONDS,r;e.returnTo&&(r=this.validateReturnTo(e.returnTo,e.returnToOptions??{policy:"relative_only"}));let n=await this.crypto.randomBytes(m.ENTROPY_BYTES),i=await this.crypto.randomBytes(m.ENTROPY_BYTES),o=await this.crypto.randomBytes(m.OPERATION_ID_BYTES),c=g(n),l=g(i),d=g(o),u=Date.now(),p={state:c,nonce:l,codeVerifier:e.codeVerifier,redirectUri:e.redirectUri,scope:e.scope,createdAt:u,expiresAt:u+t*1e3,returnTo:r,operationId:d},h=f.authState(this.issuerHash,this.clientIdHash,c);return await this.storage.set(h,JSON.stringify(p)),p}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=f.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=f.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=m.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=f.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}};m.DEFAULT_TTL_SECONDS=600,m.ENTROPY_BYTES=32,m.OPERATION_ID_BYTES=16,m.DEFAULT_CLEANUP_INTERVAL_MS=3e5;var P=m;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(V(t)),o=JSON.parse(V(r));return {header:i,payload:o,signature:n}}catch{throw new Error("Invalid JWT format: failed to decode")}}function pe(s){return ue(s).payload}function Ee(s,e=0){if(s.exp===void 0)return false;let t=Math.floor(Date.now()/1e3);return s.exp+e<t}function Y(s){try{return pe(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 d=0;d<c;d++){let u=d<i?r[d]:0,p=d<o?n[d]:0;l|=u^p;}return l===0}var I=class{constructor(e,t){this.http=e;this.clientId=t;}setDiagnosticLogger(e){this.diagnosticLogger=e;}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 u=new Set(["client_id","response_type","redirect_uri","state","nonce","code_challenge","code_challenge_method","scope"]);for(let[p,h]of Object.entries(n.extraParams))u.has(p.toLowerCase())||o.set(p,h);}let d={url:`${i}?${o.toString()}`};return n.exposeState&&(d.state=t.state,d.nonce=t.nonce),d}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(p){throw new a("network_error","Token request failed",{cause:p instanceof Error?p:void 0})}if(!i.ok){let p=i.data;throw new a("token_error","Token exchange failed",{details:{status:i.status,error:p?.error,error_description:p?.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 p=Y(o.id_token);if(p===void 0)throw this.diagnosticLogger?.logTokenValidation({step:"nonce-check",tokenType:"id_token",result:"fail",expected:"nonce claim present",actual:"nonce claim missing",errorMessage:"ID token nonce claim is missing but was sent in authorization request"}),new a("missing_nonce","ID token nonce claim is missing but was sent in authorization request");if(!v(p,t.nonce))throw this.diagnosticLogger?.logTokenValidation({step:"nonce-check",tokenType:"id_token",result:"fail",errorMessage:"ID token nonce does not match expected value"}),new a("nonce_mismatch","ID token nonce does not match expected value");this.diagnosticLogger?.logTokenValidation({step:"nonce-check",tokenType:"id_token",result:"pass"});}let l=Math.floor(Date.now()/1e3),d=o.expires_in?l+o.expires_in:l+3600,u={accessToken:o.access_token,tokenType:o.token_type??"Bearer",expiresAt:d,refreshToken:o.refresh_token,idToken:o.id_token,scope:o.scope};return this.diagnosticLogger?.logAuthDecision({decision:"allow",reason:"Token exchange successful and ID token validation passed",flow:"authorization_code",context:{hasAccessToken:!!u.accessToken,hasRefreshToken:!!u.refreshToken,hasIdToken:!!u.idToken,scope:u.scope}}),u}};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 u=new Set(["client_id","response_type","redirect_uri","state","nonce","code_challenge","code_challenge_method","scope"]);for(let[p,h]of Object.entries(t.extraParams))u.has(p.toLowerCase())||n.set(p,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(u){throw new a("network_error","PAR request failed",{cause:u instanceof Error?u:void 0})}if(!o.ok){let u=o.data;throw new a("par_error","PAR request failed",{details:{status:o.status,error:u?.error,error_description:u?.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 d=Math.floor(Date.now()/1e3)+c.expires_in;return {requestUri:c.request_uri,expiresAt:d}}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 xe=5,L=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 d=new Set(["client_id","scope"]);for(let[u,p]of Object.entries(t.extraParams))d.has(u.toLowerCase())||n.set(u,p);}let 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","Device authorization request failed",{cause:d instanceof Error?d:void 0})}if(!i.ok){let d=i.data;throw new a("device_authorization_error","Device authorization request failed",{details:{status:i.status,error:d?.error,error_description:d?.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??xe}}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(u){throw new a("network_error","Device flow token request failed",{cause:u instanceof Error?u:void 0})}if(!o.ok){let u=o.data,p=u?.error;switch(p){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:p,error_description:u?.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 M=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 d=J(JSON.stringify(o)),u=J(JSON.stringify(l)),p=`${d}.${u}`,h=await this.keyPair.sign(new TextEncoder().encode(p)),y=g(h);return `${p}.${y}`}catch(d){throw new a("dpop_proof_generation_error","Failed to generate DPoP proof",{cause:d instanceof Error?d: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 g(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 X={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 f.tokens(this.issuerHash,this.clientIdHash)}get idTokenKey(){return f.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(d){let u=new a("network_error","Token refresh request failed",{cause:d instanceof Error?d:void 0});throw this.eventEmitter?.emit("token:error",{error:u,context:"refresh",timestamp:Date.now(),source:"core"}),this.eventEmitter&&A(this.eventEmitter,u,{context:"refresh"}),u}if(!n.ok){let d=n.data,u=new a("refresh_error","Token refresh failed",{details:{status:n.status,error:d?.error,error_description:d?.error_description}});throw this.eventEmitter?.emit("token:error",{error:u,context:"refresh",timestamp:Date.now(),source:"core"}),this.eventEmitter&&A(this.eventEmitter,u,{context:"refresh"}),u}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(p){let h=new a("network_error","Token exchange request failed",{cause:p instanceof Error?p: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 p=i.data,h=new a("token_exchange_error","Token exchange failed",{details:{status:i.status,error:p?.error,error_description:p?.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,d={accessToken:o.access_token,tokenType:o.token_type??"Bearer",expiresAt:l,refreshToken:o.refresh_token,idToken:o.id_token,scope:o.scope},u={tokens:d,issuedTokenType:o.issued_token_type};return this.eventEmitter?.emit("token:exchanged",{hasAccessToken:!!d.accessToken,hasRefreshToken:!!d.refreshToken,issuedTokenType:o.issued_token_type,timestamp:Date.now(),source:"core",operationId:this.currentOperationId??void 0}),u}mapTokenTypeToUri(e){return X[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=f.tokens(this.issuerHash,this.clientIdHash),t=f.idToken(this.issuerHash,this.clientIdHash);await this.storage.remove(e),await this.storage.remove(t);}async getStoredIdToken(){let e=f.idToken(this.issuerHash,this.clientIdHash);return this.storage.get(e)}async getStoredTokens(){let e=f.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 he(s,e,t=16){let r=await s.sha256(e);return g(r).slice(0,t)}var K=class{constructor(e){this.dpopManager=null;this.initialized=false;this.diagnosticLogger=null;this.config=W(e),this.normalizedIssuer=T(e.issuer),this.events=new b,this.discoveryClient=new C({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 L(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 he(this.config.crypto,this.normalizedIssuer,e),this.clientIdHash=await he(this.config.crypto,this.config.clientId,e),this.stateManager=new P(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 M(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)}setDiagnosticLogger(e){this.diagnosticLogger=e,this.authCodeFlow.setDiagnosticLogger(e);}getDiagnosticSessionId(){return this.diagnosticLogger?.getDiagnosticSessionId()??null}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 Re(s){let e=new K(s);return await e.initialize(),e}var ge=new Set(["login_required","interaction_required","consent_required","account_selection_required"]),Z=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 u=new Set(["client_id","response_type","redirect_uri","state","nonce","code_challenge","code_challenge_method","scope","prompt"]);for(let[p,h]of Object.entries(n.extraParams))u.has(p.toLowerCase())||o.set(p,h);}let d={url:`${i}?${o.toString()}`};return n.exposeState&&(d.state=t.state,d.nonce=t.nonce),d}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 ge.has(e.code)}mapSilentAuthError(e){return ge.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 Q(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:Ce(),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 Ce(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).substring(2,15)}`}var ee=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 Q(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[R,we]of Object.entries(t.extraParams))y.has(R.toLowerCase())||o.set(R,we);}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 d=l.data,u=Math.floor(Date.now()/1e3),p=d.expires_in?u+d.expires_in:u+3600;return {accessToken:d.access_token,tokenType:d.token_type??"Bearer",expiresAt:p,refreshToken:d.refresh_token,scope:d.scope}}};var te=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 be(s){return s.require_signed_request_object===true}var re=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 x=class x{constructor(e){this.tokenManager=null;this.checkInterval=null;this.abortController=null;this.isRunning=false;this.options={thresholdSeconds:e?.thresholdSeconds??x.DEFAULT_THRESHOLD_SECONDS,checkIntervalMs:e?.checkIntervalMs??x.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();}};x.DEFAULT_THRESHOLD_SECONDS=60,x.DEFAULT_CHECK_INTERVAL_MS=3e4;var ne=x;var ie=class{constructor(e){this.crypto=e.crypto;}async calculate(e){let t=e.salt;if(!t){let c=await this.crypto.randomBytes(16);t=g(c);}let r=e.clientId+" "+e.origin+" "+e.opBrowserState+t,n=await this.crypto.sha256(r),i=g(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 oe=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 Se=["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 Se.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 se(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 ae={log(){}};function ye(s){return s.enabled?s.logger?s.logger:se({timestamps:s.logTimestamps}):ae}var $=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}};var N=class{constructor(e){this.logs=[];this.diagnosticSessionId=this.generateSessionId(),this.enabled=e.enabled,this.debugLogger=e.debugLogger,this.collectLogs=e.collectLogs??false,this.maxLogs=e.maxLogs??1e3;}getDiagnosticSessionId(){return this.diagnosticSessionId}isEnabled(){return this.enabled}logTokenValidation(e){if(!this.enabled)return;let t={id:this.generateEntryId(),diagnosticSessionId:this.diagnosticSessionId,category:"token-validation",level:e.result==="fail"?"error":"debug",timestamp:Date.now(),step:e.step,tokenType:e.tokenType,result:e.result,expected:e.expected,actual:e.actual,errorMessage:e.errorMessage,details:e.details};this.writeLog(t);}logAuthDecision(e){if(!this.enabled)return;let t={id:this.generateEntryId(),diagnosticSessionId:this.diagnosticSessionId,category:"auth-decision",level:e.decision==="deny"?"warn":"info",timestamp:Date.now(),decision:e.decision,reason:e.reason,flow:e.flow,context:e.context};this.writeLog(t);}getLogs(){return [...this.logs]}exportLogs(){return JSON.stringify(this.logs,null,2)}clearLogs(){this.logs=[];}writeLog(e){this.debugLogger&&this.debugLogger.log(e.level,`[DIAGNOSTIC] ${e.category}`,e),this.collectLogs&&(this.logs.push(e),this.logs.length>this.maxLogs&&this.logs.shift());}generateSessionId(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return (e==="x"?t:t&3|8).toString(16)})}generateEntryId(){return `${Date.now()}-${Math.random().toString(36).substring(2,9)}`}};function me(s){return s.enabled?new N(s):null}async function De(s,e){let t=await e.sha256(s),r=t.slice(0,t.length/2);return g(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 Ie(s){let e=new AbortController;return {promise:s(e.signal),cancel:()=>e.abort(),signal:e.signal}}function ce(s){return s instanceof a&&s.code==="operation_cancelled"}async function Oe(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 Le={maxRetries:3,baseDelayMs:1e3,maxDelayMs:3e4,jitter:true};function ve(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 _e(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 ke(s,e){let t={...Le,...e},{maxRetries:r,baseDelayMs:n,maxDelayMs:i,jitter:o,signal:c,shouldRetry:l,onRetry:d}=t,u;for(let p=0;p<=r;p++)try{if(c?.aborted)throw new a("operation_cancelled","Operation was cancelled");return await s()}catch(h){if(u=h,ce(h))throw h;let y=l?l(h,p):h instanceof a&&w(h);if(p>=r||!y)throw h;let R=ve(p,n,i,o);d?.(h,p+1,R),await _e(R,c);}throw u}function Me(s){return (e,t)=>ke(e,{...s,...t})}function He(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=ne;exports.ClientCredentialsClient=ee;exports.DPoPManager=M;exports.DebugContext=$;exports.DeviceFlowClient=L;exports.DiagnosticLogger=N;exports.DiscoveryClient=C;exports.EventEmitter=b;exports.EventTimeline=B;exports.FrontChannelLogoutUrlBuilder=oe;exports.JARBuilder=te;exports.JARMValidator=re;exports.LogoutHandler=j;exports.PARClient=O;exports.PKCEHelper=S;exports.STORAGE_KEYS=f;exports.SessionManager=z;exports.SessionStateCalculator=ie;exports.SilentAuthHandler=Z;exports.StateManager=P;exports.TOKEN_TYPE_URIS=X;exports.TokenApiClient=q;exports.TokenIntrospector=U;exports.TokenManager=H;exports.TokenRevoker=k;exports.base64urlDecode=de;exports.base64urlEncode=g;exports.base64urlToString=V;exports.buildClientAuthentication=Q;exports.calculateBackoffDelay=ve;exports.calculateDsHash=De;exports.classifyError=G;exports.createAuthrimClient=Re;exports.createCancellableOperation=Ie;exports.createConsoleLogger=se;exports.createDebugLogger=ye;exports.createDiagnosticLogger=me;exports.createRetryFunction=Me;exports.decodeIdToken=pe;exports.decodeJwt=ue;exports.emitClassifiedError=A;exports.getErrorMeta=le;exports.getIdTokenNonce=Y;exports.isCancellationError=ce;exports.isJarRequired=be;exports.isJwtExpired=Ee;exports.isRetryableError=w;exports.noopLogger=ae;exports.normalizeIssuer=T;exports.parseRetryAfterHeader=He;exports.raceWithCancellation=Oe;exports.resolveConfig=W;exports.sleep=_e;exports.stringToBase64url=J;exports.timingSafeEqual=v;exports.withAbortSignal=Pe;exports.withRetry=ke;//# sourceMappingURL=index.cjs.map
1
+ 'use strict';function W(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 le(this.code)}},Te={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 le(s){return Te[s]}function G(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:Ae(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 Ae(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=G(s);return e.severity==="recoverable"&&e.remediation==="retry"}function T(s,e,t){let{severity:r,remediation:n}=G(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 A(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=A(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=A(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(A(e));}};N.DEFAULT_CACHE_TTL_MS=3600*1e3;var b=N;var C=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 g(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 de(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=D[e.charCodeAt(c)],d=D[e.charCodeAt(c+1)],u=D[e.charCodeAt(c+2)],p=D[e.charCodeAt(c+3)],h=l<<18|d<<12|u<<6|p;o<n&&(i[o++]=h>>16&255),o<n&&(i[o++]=h>>8&255),o<n&&(i[o++]=h&255);}return i}function J(s){let e=new TextEncoder;return g(e.encode(s))}function B(s){return new TextDecoder().decode(de(s))}var E="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",D=new Uint8Array(256);for(let s=0;s<E.length;s++)D[E.charCodeAt(s)]=s;var f={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:`},y=class y{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??y.DEFAULT_TTL_SECONDS,r;e.returnTo&&(r=this.validateReturnTo(e.returnTo,e.returnToOptions??{policy:"relative_only"}));let n=await this.crypto.randomBytes(y.ENTROPY_BYTES),i=await this.crypto.randomBytes(y.ENTROPY_BYTES),o=await this.crypto.randomBytes(y.OPERATION_ID_BYTES),c=g(n),l=g(i),d=g(o),u=Date.now(),p={state:c,nonce:l,codeVerifier:e.codeVerifier,redirectUri:e.redirectUri,scope:e.scope,createdAt:u,expiresAt:u+t*1e3,returnTo:r,operationId:d},h=f.authState(this.issuerHash,this.clientIdHash,c);return await this.storage.set(h,JSON.stringify(p)),p}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=f.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=f.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=y.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=f.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}};y.DEFAULT_TTL_SECONDS=600,y.ENTROPY_BYTES=32,y.OPERATION_ID_BYTES=16,y.DEFAULT_CLEANUP_INTERVAL_MS=3e5;var P=y;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(B(t)),o=JSON.parse(B(r));return {header:i,payload:o,signature:n}}catch{throw new Error("Invalid JWT format: failed to decode")}}function pe(s){return ue(s).payload}function Ee(s,e=0){if(s.exp===void 0)return false;let t=Math.floor(Date.now()/1e3);return s.exp+e<t}function Y(s){try{return pe(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 d=0;d<c;d++){let u=d<i?r[d]:0,p=d<o?n[d]:0;l|=u^p;}return l===0}var I=class{constructor(e,t){this.http=e;this.clientId=t;}setDiagnosticLogger(e){this.diagnosticLogger=e;}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 u=new Set(["client_id","response_type","redirect_uri","state","nonce","code_challenge","code_challenge_method","scope"]);for(let[p,h]of Object.entries(n.extraParams))u.has(p.toLowerCase())||o.set(p,h);}let d={url:`${i}?${o.toString()}`};return n.exposeState&&(d.state=t.state,d.nonce=t.nonce),d}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(p){throw new a("network_error","Token request failed",{cause:p instanceof Error?p:void 0})}if(!i.ok){let p=i.data;throw new a("token_error","Token exchange failed",{details:{status:i.status,error:p?.error,error_description:p?.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 p=Y(o.id_token);if(p===void 0)throw this.diagnosticLogger?.logTokenValidation({step:"nonce-check",tokenType:"id_token",result:"fail",expected:"nonce claim present",actual:"nonce claim missing",errorMessage:"ID token nonce claim is missing but was sent in authorization request"}),new a("missing_nonce","ID token nonce claim is missing but was sent in authorization request");if(!v(p,t.nonce))throw this.diagnosticLogger?.logTokenValidation({step:"nonce-check",tokenType:"id_token",result:"fail",errorMessage:"ID token nonce does not match expected value"}),new a("nonce_mismatch","ID token nonce does not match expected value");this.diagnosticLogger?.logTokenValidation({step:"nonce-check",tokenType:"id_token",result:"pass"});}let l=Math.floor(Date.now()/1e3),d=o.expires_in?l+o.expires_in:l+3600,u={accessToken:o.access_token,tokenType:o.token_type??"Bearer",expiresAt:d,refreshToken:o.refresh_token,idToken:o.id_token,scope:o.scope};return this.diagnosticLogger?.logAuthDecision({decision:"allow",reason:"Token exchange successful and ID token validation passed",flow:"authorization_code",context:{hasAccessToken:!!u.accessToken,hasRefreshToken:!!u.refreshToken,hasIdToken:!!u.idToken,scope:u.scope}}),u}};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 u=new Set(["client_id","response_type","redirect_uri","state","nonce","code_challenge","code_challenge_method","scope"]);for(let[p,h]of Object.entries(t.extraParams))u.has(p.toLowerCase())||n.set(p,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(u){throw new a("network_error","PAR request failed",{cause:u instanceof Error?u:void 0})}if(!o.ok){let u=o.data;throw new a("par_error","PAR request failed",{details:{status:o.status,error:u?.error,error_description:u?.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 d=Math.floor(Date.now()/1e3)+c.expires_in;return {requestUri:c.request_uri,expiresAt:d}}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 xe=5,L=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 d=new Set(["client_id","scope"]);for(let[u,p]of Object.entries(t.extraParams))d.has(u.toLowerCase())||n.set(u,p);}let 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","Device authorization request failed",{cause:d instanceof Error?d:void 0})}if(!i.ok){let d=i.data;throw new a("device_authorization_error","Device authorization request failed",{details:{status:i.status,error:d?.error,error_description:d?.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??xe}}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(u){throw new a("network_error","Device flow token request failed",{cause:u instanceof Error?u:void 0})}if(!o.ok){let u=o.data,p=u?.error;switch(p){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:p,error_description:u?.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 M=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 d=J(JSON.stringify(o)),u=J(JSON.stringify(l)),p=`${d}.${u}`,h=await this.keyPair.sign(new TextEncoder().encode(p)),m=g(h);return `${p}.${m}`}catch(d){throw new a("dpop_proof_generation_error","Failed to generate DPoP proof",{cause:d instanceof Error?d: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 g(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 X={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 f.tokens(this.issuerHash,this.clientIdHash)}get idTokenKey(){return f.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(d){let u=new a("network_error","Token refresh request failed",{cause:d instanceof Error?d:void 0});throw this.eventEmitter?.emit("token:error",{error:u,context:"refresh",timestamp:Date.now(),source:"core"}),this.eventEmitter&&T(this.eventEmitter,u,{context:"refresh"}),u}if(!n.ok){let d=n.data,u=new a("refresh_error","Token refresh failed",{details:{status:n.status,error:d?.error,error_description:d?.error_description}});throw this.eventEmitter?.emit("token:error",{error:u,context:"refresh",timestamp:Date.now(),source:"core"}),this.eventEmitter&&T(this.eventEmitter,u,{context:"refresh"}),u}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(p){let h=new a("network_error","Token exchange request failed",{cause:p instanceof Error?p:void 0});throw this.eventEmitter?.emit("token:error",{error:h,context:"exchange",timestamp:Date.now(),source:"core"}),this.eventEmitter&&T(this.eventEmitter,h,{context:"exchange"}),h}if(!i.ok){let p=i.data,h=new a("token_exchange_error","Token exchange failed",{details:{status:i.status,error:p?.error,error_description:p?.error_description}});throw this.eventEmitter?.emit("token:error",{error:h,context:"exchange",timestamp:Date.now(),source:"core"}),this.eventEmitter&&T(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,d={accessToken:o.access_token,tokenType:o.token_type??"Bearer",expiresAt:l,refreshToken:o.refresh_token,idToken:o.id_token,scope:o.scope},u={tokens:d,issuedTokenType:o.issued_token_type};return this.eventEmitter?.emit("token:exchanged",{hasAccessToken:!!d.accessToken,hasRefreshToken:!!d.refreshToken,issuedTokenType:o.issued_token_type,timestamp:Date.now(),source:"core",operationId:this.currentOperationId??void 0}),u}mapTokenTypeToUri(e){return X[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 U=_;var H=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=f.tokens(this.issuerHash,this.clientIdHash),t=f.idToken(this.issuerHash,this.clientIdHash);await this.storage.remove(e),await this.storage.remove(t);}async getStoredIdToken(){let e=f.idToken(this.issuerHash,this.clientIdHash);return this.storage.get(e)}async getStoredTokens(){let e=f.tokens(this.issuerHash,this.clientIdHash),t=await this.storage.get(e);if(!t)return null;try{return JSON.parse(t)}catch{return null}}};var z=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 q=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 he(s,e,t=16){let r=await s.sha256(e);return g(r).slice(0,t)}var V=class{constructor(e){this.dpopManager=null;this.initialized=false;this.diagnosticLogger=null;this.config=W(e),this.normalizedIssuer=A(e.issuer),this.events=new C,this.discoveryClient=new b({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 L(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 he(this.config.crypto,this.normalizedIssuer,e),this.clientIdHash=await he(this.config.crypto,this.config.clientId,e),this.stateManager=new P(this.config.crypto,this.config.storage,this.issuerHash,this.clientIdHash),this.tokenManager=new U({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 H({http:this.config.http,clientId:this.config.clientId}),this.tokenRevoker=new k({http:this.config.http,clientId:this.config.clientId});let t=new z({http:this.config.http});this.sessionManager=new q({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 M(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)}setDiagnosticLogger(e){this.diagnosticLogger=e,this.authCodeFlow.setDiagnosticLogger(e);}getDiagnosticSessionId(){return this.diagnosticLogger?.getDiagnosticSessionId()??null}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 Re(s){let e=new V(s);return await e.initialize(),e}var ge=new Set(["login_required","interaction_required","consent_required","account_selection_required"]),Z=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 u=new Set(["client_id","response_type","redirect_uri","state","nonce","code_challenge","code_challenge_method","scope","prompt"]);for(let[p,h]of Object.entries(n.extraParams))u.has(p.toLowerCase())||o.set(p,h);}let d={url:`${i}?${o.toString()}`};return n.exposeState&&(d.state=t.state,d.nonce=t.nonce),d}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 ge.has(e.code)}mapSilentAuthError(e){return ge.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 Q(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:be(),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 be(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).substring(2,15)}`}var ee=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 Q(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 m=new Set(["grant_type","client_id","client_secret","client_assertion","client_assertion_type","scope","audience"]);for(let[R,we]of Object.entries(t.extraParams))m.has(R.toLowerCase())||o.set(R,we);}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(m){throw new a("network_error","Client credentials token request failed",{cause:m instanceof Error?m:void 0})}if(!l.ok){let m=l.data;throw new a("client_credentials_error","Client credentials token request failed",{details:{status:l.status,error:m?.error,error_description:m?.error_description}})}let d=l.data,u=Math.floor(Date.now()/1e3),p=d.expires_in?u+d.expires_in:u+3600;return {accessToken:d.access_token,tokenType:d.token_type??"Bearer",expiresAt:p,refreshToken:d.refresh_token,scope:d.scope}}};var te=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 re=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 x=class x{constructor(e){this.tokenManager=null;this.checkInterval=null;this.abortController=null;this.isRunning=false;this.options={thresholdSeconds:e?.thresholdSeconds??x.DEFAULT_THRESHOLD_SECONDS,checkIntervalMs:e?.checkIntervalMs??x.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();}};x.DEFAULT_THRESHOLD_SECONDS=60,x.DEFAULT_CHECK_INTERVAL_MS=3e4;var ne=x;var ie=class{constructor(e){this.crypto=e.crypto;}async calculate(e){let t=e.salt;if(!t){let c=await this.crypto.randomBytes(16);t=g(c);}let r=e.clientId+" "+e.origin+" "+e.opBrowserState+t,n=await this.crypto.sha256(r),i=g(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 oe=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 Se=["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"],K=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 Se.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 se(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 ae={log(){}};function me(s){return s.enabled?s.logger?s.logger:se({timestamps:s.logTimestamps}):ae}var $=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}};var F=class{constructor(e){this.logs=[];this.sendBuffer=[];this.isFlushing=false;this.diagnosticSessionId=this.generateSessionId(),this.enabled=e.enabled,this.debugLogger=e.debugLogger,this.collectLogs=e.collectLogs??false,this.maxLogs=e.maxLogs??1e3,this.sendToServer=e.sendToServer??false,this.serverUrl=e.serverUrl,this.clientId=e.clientId,this.clientSecret=e.clientSecret,this.batchSize=e.batchSize??50,this.flushIntervalMs=e.flushIntervalMs??5e3,this.sendToServer&&(!this.serverUrl||!this.clientId)&&(this.debugLogger&&this.debugLogger.log("warn","[DIAGNOSTIC] sendToServer is enabled but serverUrl or clientId is missing. Server sending disabled."),this.sendToServer=false);}getDiagnosticSessionId(){return this.diagnosticSessionId}isEnabled(){return this.enabled}logTokenValidation(e){if(!this.enabled)return;let t={id:this.generateEntryId(),diagnosticSessionId:this.diagnosticSessionId,category:"token-validation",level:e.result==="fail"?"error":"debug",timestamp:Date.now(),step:e.step,tokenType:e.tokenType,result:e.result,expected:e.expected,actual:e.actual,errorMessage:e.errorMessage,details:e.details};this.writeLog(t);}logAuthDecision(e){if(!this.enabled)return;let t={id:this.generateEntryId(),diagnosticSessionId:this.diagnosticSessionId,category:"auth-decision",level:e.decision==="deny"?"warn":"info",timestamp:Date.now(),decision:e.decision,reason:e.reason,flow:e.flow,context:e.context};this.writeLog(t);}getLogs(){return [...this.logs]}exportLogs(){return JSON.stringify(this.logs,null,2)}clearLogs(){this.logs=[];}getBufferedLogsCount(){return this.sendBuffer.length}writeLog(e){this.debugLogger&&this.debugLogger.log(e.level,`[DIAGNOSTIC] ${e.category}`,e),this.collectLogs&&(this.logs.push(e),this.logs.length>this.maxLogs&&this.logs.shift()),this.sendToServer&&this.bufferLog(e);}bufferLog(e){this.sendBuffer.push(e),this.sendBuffer.length>=this.batchSize?this.flush():this.scheduleFlush();}scheduleFlush(){this.flushTimer&&clearTimeout(this.flushTimer),this.flushTimer=setTimeout(()=>{this.flush();},this.flushIntervalMs);}async flush(){if(this.isFlushing||this.sendBuffer.length===0)return;this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=void 0),this.isFlushing=true;let e=[...this.sendBuffer];this.sendBuffer=[];try{let t=await fetch(`${this.serverUrl}/api/v1/diagnostic-logs/ingest`,{method:"POST",headers:{"Content-Type":"application/json","X-Diagnostic-Session-Id":this.diagnosticSessionId},body:JSON.stringify({logs:e,client_id:this.clientId,client_secret:this.clientSecret})});t.ok?this.debugLogger&&this.debugLogger.log("debug",`[DIAGNOSTIC] Sent ${e.length} logs to server`):this.handleSendFailure(e,`HTTP ${t.status}: ${t.statusText}`);}catch(t){this.handleSendFailure(e,t instanceof Error?t.message:String(t));}finally{this.isFlushing=false;}}handleSendFailure(e,t){if(this.debugLogger&&this.debugLogger.log("warn",`[DIAGNOSTIC] Failed to send logs to server: ${t}`),this.collectLogs)for(let r of e)this.logs.some(n=>n.id===r.id)||(this.logs.push(r),this.logs.length>this.maxLogs&&this.logs.shift());}generateSessionId(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return (e==="x"?t:t&3|8).toString(16)})}generateEntryId(){return `${Date.now()}-${Math.random().toString(36).substring(2,9)}`}};function ye(s){return s.enabled?new F(s):null}async function De(s,e){let t=await e.sha256(s),r=t.slice(0,t.length/2);return g(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 Ie(s){let e=new AbortController;return {promise:s(e.signal),cancel:()=>e.abort(),signal:e.signal}}function ce(s){return s instanceof a&&s.code==="operation_cancelled"}async function Oe(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 Le={maxRetries:3,baseDelayMs:1e3,maxDelayMs:3e4,jitter:true};function ve(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 _e(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 ke(s,e){let t={...Le,...e},{maxRetries:r,baseDelayMs:n,maxDelayMs:i,jitter:o,signal:c,shouldRetry:l,onRetry:d}=t,u;for(let p=0;p<=r;p++)try{if(c?.aborted)throw new a("operation_cancelled","Operation was cancelled");return await s()}catch(h){if(u=h,ce(h))throw h;let m=l?l(h,p):h instanceof a&&w(h);if(p>=r||!m)throw h;let R=ve(p,n,i,o);d?.(h,p+1,R),await _e(R,c);}throw u}function Me(s){return (e,t)=>ke(e,{...s,...t})}function Ue(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=V;exports.AuthrimError=a;exports.AutoRefreshScheduler=ne;exports.ClientCredentialsClient=ee;exports.DPoPManager=M;exports.DebugContext=$;exports.DeviceFlowClient=L;exports.DiagnosticLogger=F;exports.DiscoveryClient=b;exports.EventEmitter=C;exports.EventTimeline=K;exports.FrontChannelLogoutUrlBuilder=oe;exports.JARBuilder=te;exports.JARMValidator=re;exports.LogoutHandler=j;exports.PARClient=O;exports.PKCEHelper=S;exports.STORAGE_KEYS=f;exports.SessionManager=q;exports.SessionStateCalculator=ie;exports.SilentAuthHandler=Z;exports.StateManager=P;exports.TOKEN_TYPE_URIS=X;exports.TokenApiClient=z;exports.TokenIntrospector=H;exports.TokenManager=U;exports.TokenRevoker=k;exports.base64urlDecode=de;exports.base64urlEncode=g;exports.base64urlToString=B;exports.buildClientAuthentication=Q;exports.calculateBackoffDelay=ve;exports.calculateDsHash=De;exports.classifyError=G;exports.createAuthrimClient=Re;exports.createCancellableOperation=Ie;exports.createConsoleLogger=se;exports.createDebugLogger=me;exports.createDiagnosticLogger=ye;exports.createRetryFunction=Me;exports.decodeIdToken=pe;exports.decodeJwt=ue;exports.emitClassifiedError=T;exports.getErrorMeta=le;exports.getIdTokenNonce=Y;exports.isCancellationError=ce;exports.isJarRequired=Ce;exports.isJwtExpired=Ee;exports.isRetryableError=w;exports.noopLogger=ae;exports.normalizeIssuer=A;exports.parseRetryAfterHeader=Ue;exports.raceWithCancellation=Oe;exports.resolveConfig=W;exports.sleep=_e;exports.stringToBase64url=J;exports.timingSafeEqual=v;exports.withAbortSignal=Pe;exports.withRetry=ke;//# sourceMappingURL=index.cjs.map
3
3
  //# sourceMappingURL=index.cjs.map