ark-oauth-client-js 2.2.0 → 2.3.0

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.
@@ -1,4 +1,4 @@
1
- /*! ark-oauth-client-js 2.2.0 | MIT | https://github.com/ir-dev/ark-oauth-oidc */
1
+ /*! ark-oauth-client-js 2.3.0 | MIT | https://github.com/ir-dev/ark-oauth-oidc */
2
2
  var ArkOAuth = (() => {
3
3
  var __defProp = Object.defineProperty;
4
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
@@ -65,7 +65,7 @@ var ArkOAuth = (() => {
65
65
  });
66
66
 
67
67
  // src/version.js
68
- var VERSION = "2.2.0";
68
+ var VERSION = "2.3.0";
69
69
 
70
70
  // src/errors.js
71
71
  var ArkError = class extends Error {
@@ -1,3 +1,3 @@
1
- /*! ark-oauth-client-js 2.2.0 | MIT | https://github.com/ir-dev/ark-oauth-oidc */
2
- var ArkOAuth=(()=>{var de=Object.defineProperty;var mt=Object.getOwnPropertyDescriptor;var gt=Object.getOwnPropertyNames;var wt=Object.prototype.hasOwnProperty;var kt=(n,e)=>{for(var t in e)de(n,t,{get:e[t],enumerable:!0})},yt=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of gt(e))!wt.call(n,s)&&s!==t&&de(n,s,{get:()=>e[s],enumerable:!(r=mt(e,s))||r.enumerable});return n};var bt=n=>yt(de({},"__esModule",{value:!0}),n);var zt={};kt(zt,{ACCOUNT_SWITCH_DEFAULTS:()=>X,ArkAccessDeniedReasons:()=>Q,ArkBrowserClient:()=>V,ArkCallbackError:()=>T,ArkChallengeProperties:()=>fe,ArkConfigError:()=>f,ArkError:()=>y,ArkLoginRequiredError:()=>x,ArkNetworkError:()=>$,ArkOAuthError:()=>w,ArkPopupError:()=>E,ArkTokenError:()=>p,DEFAULT_POST_LOGOUT_PATH:()=>F,DEFAULT_REDIRECT_PATH:()=>ee,DEFAULT_SCOPES:()=>pe,INITIAL_SNAPSHOT:()=>K,JwksCache:()=>H,MemoryStorage:()=>j,MetadataResolver:()=>D,SUPPORTED_ALGORITHMS:()=>be,TokenSet:()=>I,VERSION:()=>Y,base64UrlDecode:()=>B,base64UrlEncode:()=>U,codeChallengeFor:()=>ve,createArkClient:()=>et,createCodeVerifier:()=>xe,createNonce:()=>oe,createPkcePair:()=>ae,createState:()=>W,decodeJwt:()=>J,discoveryUrls:()=>we,localOrDefault:()=>R,normalizeAccountSwitch:()=>Z,normalizeConfig:()=>te,randomToken:()=>q,renderAccessDenied:()=>tt,validateClaims:()=>Ae,validateTokenHashes:()=>Te,verifyJwt:()=>ie,verifySignature:()=>_e});var Y="2.2.0";var y=class extends Error{constructor(e,t){super(e,t),this.name=new.target.name}},f=class extends y{},w=class n extends y{constructor(e,t,{status:r=0,endpoint:s=null,errorUri:i=null,body:o=null}={}){super(t?`${e}: ${t}`:e),this.error=e,this.errorDescription=t??null,this.errorUri=i,this.status=r,this.endpoint=s,this.body=o}static fromResponse(e,t,r){return t&&typeof t=="object"&&typeof t.error=="string"?new n(t.error,t.error_description,{status:e,endpoint:r,errorUri:t.error_uri??null,body:t}):new n("server_error",`the endpoint returned HTTP ${e}.`,{status:e,endpoint:r,body:t})}},p=class extends y{constructor(e,{claim:t=null}={}){super(e),this.claim=t}},T=class extends y{},$=class extends y{},x=class extends y{constructor(e="no user is signed in, or the session has ended. Call signinRedirect() to sign in."){super(e),this.error="login_required"}},E=class extends y{constructor(e,t){super(t),this.reason=e}};var Q=Object.freeze({NO_APP_ACCESS:"no_app_access",FORBIDDEN:"forbidden"}),X=Object.freeze({requireArkClaims:!1,requiredClaims:Object.freeze([]),accessDeniedPath:null,prompt:"login",endProviderSessionOnSwitch:!1,appDisplayName:null,showSignedInAccount:!0,allowFullSignOut:!0,homePath:"/",supportUrl:null,supportEmail:null});function R(n,e="/"){let t=typeof e=="string"&&e.trim()?e:e===null?null:"/";if(typeof n!="string"||!n.trim())return t;let r=n.trim();return!r.startsWith("/")||r.startsWith("//")||r.startsWith("/\\")||/[\u0000-\u001f\u007f]/.test(r)?t:r}function Z(n={}){let e={...X};for(let[t,r]of Object.entries(n??{}))Object.prototype.hasOwnProperty.call(X,t)&&r!==void 0&&(e[t]=r);for(let t of["accessDeniedPath","homePath"])if(e[t]!==null&&R(e[t],null)!==e[t])throw new f(`ark_oauth_client: accountSwitch.${t} must be a local path starting with '/', but is '${e[t]}'.`);if(e.supportUrl&&!/^https?:\/\//i.test(e.supportUrl))throw new f(`ark_oauth_client: accountSwitch.supportUrl must be an http(s) URL, but is '${e.supportUrl}'.`);return e.requiredClaims=Object.freeze([...e.requiredClaims??[]].map(String)),Object.freeze(e)}var fe=Object.freeze({switchUser(n=null,e=null,t="login"){return{returnTo:n||"/",prompt:t||"login",...e?{loginHint:e}:{}}},selectAccount(n=null){return fe.switchUser(n,null,"select_account")}});async function Pe(n,e,{claims:t={},arkClaims:r=[],tokens:s=null}={}){let i=n.requiredClaims.map(a=>a.toLowerCase()),o=!n.requireArkClaims||(i.length?r.some(a=>i.includes(String(a).toLowerCase())):r.length>0);return typeof e!="function"?o:!!await e({claims:{...t},arkClaims:[...r],allowedByConfiguration:o,tokens:s})}function Ue(n,e,t,r){let s=(...i)=>{for(let o of i)if(e?.[o])return String(e[o]);return null};return{reason:n,subject:s("sub"),email:s("email","preferred_username"),name:s("name"),arkClaims:[...t??[]],returnTo:r??null}}var pe=Object.freeze(["openid","profile","email","offline_access"]),ee="/signin-oidc",F="/signout-callback-oidc";function Me(n){return["localhost","127.0.0.1","[::1]","::1"].includes(n.hostname)}function me(n,e){let t;try{t=new URL(n)}catch{throw new f(`ark_oauth_client: '${e}' must be an absolute URL, but is '${n}'.`)}if(t.protocol!=="https:"&&t.protocol!=="http:")throw new f(`ark_oauth_client: '${e}' must be an http or https URL, but is '${n}'.`);return t}function Ie(n,e){if(n==null||n==="")return null;let t=String(n);if(t.startsWith("/")&&!t.startsWith("//")){if(t.includes("#"))throw new f(`ark_oauth_client: '${e}' must not contain a fragment: ${t}`);return t}let r=me(t,e);if(r.hash)throw new f(`ark_oauth_client: '${e}' must not contain a fragment: ${t}`);if(r.protocol!=="https:"&&!Me(r))throw new f(`ark_oauth_client: '${e}' is ${t}. The server accepts http only for loopback addresses (RFC 8252 \xA77.3).`);return t}function St(n){return Object.freeze([...n??[]].map(e=>{if(e==="*")throw new f("ark_oauth_client: 'apiOrigins' cannot be '*'. List the exact origins the access token may be sent to.");return me(String(e),"apiOrigins").origin}))}function te(n={}){let{authority:e,authServerUrl:t,tenantId:r,clientId:s,clientSecret:i,privateKeyJwt:o,tokenEndpointAuthMethod:a,usePar:h,redirectUri:d=ee,postLogoutRedirectUri:u=F,scopes:c,responseMode:l="query",prompt:k=null,acrValues:g=null,extraAuthorizationParams:_=null,storage:S="session",automaticRefresh:b=!0,refreshBeforeSeconds:m=60,apiOrigins:C=[],syncTabs:G=!0,accountSwitch:ue,onEvaluateAccess:rt=null,onRedirectCallback:nt=null,navigate:st=null,redirect:it=null,popup:ot={},transactionTtlSeconds:at=600,clockToleranceSeconds:ct=60,requireHttps:Ee=!0,requireTokenHashes:ht=!0,idTokenSigningAlgorithms:Re=null,timeoutMs:lt=1e4,metadataTtlMs:ut=5*6e4,jwksTtlMs:dt=5*6e4,jwksMinRefreshIntervalMs:ft=1e4,fetch:pt=void 0}=n,P=String(e??"").trim();if(!P&&t&&r&&(P=`${String(t).replace(/\/+$/,"")}/${r}`),!P)throw new f("ark_oauth_client: set 'authority' to the issuer URL of your Ark tenant, {BaseUrl}/{TenantId}, e.g. https://idp.example.com/my_idp. (Or set authServerUrl + tenantId and they are joined for you.)");P=P.replace(/\/+$/,"");let Oe=me(P,"authority");if(Ee&&Oe.protocol!=="https:"&&!Me(Oe))throw new f(`ark_oauth_client: 'authority' is ${P}, which is plain http. Tokens would cross the network in the clear. Use https, or set requireHttps:false, only ever for local development.`);if(!s||typeof s!="string")throw new f("ark_oauth_client: 'clientId' is required: the client id registered with the tenant.");if(i||o||a&&a!=="none")throw new f("ark_oauth_client: a browser app cannot keep a client secret or a private key: anything in the bundle is readable by every visitor. Register this app as a public client (token endpoint auth method 'none'; PKCE protects the code), or keep the confidential client on a server with ark-oauth-client-node (Node), ark-oauth-client (Python) or Ark.oAuth.Client (.NET).");if(h)throw new f("ark_oauth_client: 'usePar' is not available in a browser app: /oauth2/par needs client authentication and serves no CORS. Leave PAR to a server-side client.");if(!["query","fragment"].includes(l))throw new f(`ark_oauth_client: 'responseMode' is '${l}'. A browser app reads the response from its own URL, so use 'query' or 'fragment'`+(l==="form_post"?"; form_post POSTs to a server, which a single-page app does not have.":"."));if(!Number.isFinite(m)||m<0)throw new f(`ark_oauth_client: 'refreshBeforeSeconds' must be a number of seconds, not '${m}'.`);return Object.freeze({authority:P,clientId:s,redirectUri:Ie(d,"redirectUri")??ee,postLogoutRedirectUri:Ie(u,"postLogoutRedirectUri"),scopes:Object.freeze(c?.length?[...c]:[...pe]),responseMode:l,prompt:k,acrValues:g,extraAuthorizationParams:_?Object.freeze({..._}):null,storage:S,automaticRefresh:!!b,refreshBeforeSeconds:m,apiOrigins:St(C),syncTabs:!!G,accountSwitch:Z(ue),onEvaluateAccess:rt,onRedirectCallback:nt,navigate:st,redirect:it,popup:Object.freeze({width:520,height:680,timeoutMs:5*6e4,...ot}),transactionTtlSeconds:at,clockToleranceSeconds:ct,requireHttps:Ee,requireTokenHashes:ht,idTokenSigningAlgorithms:Re?Object.freeze([...Re]):null,timeoutMs:lt,metadataTtlMs:ut,jwksTtlMs:dt,jwksMinRefreshIntervalMs:ft,fetch:pt})}var Le=1e4;function ze(n,e){let t;if(typeof AbortSignal.timeout=="function")t=AbortSignal.timeout(e);else{let i=new AbortController;setTimeout(()=>i.abort(new DOMException("The operation timed out.","TimeoutError")),e),t=i.signal}if(!n)return t;if(typeof AbortSignal.any=="function")return AbortSignal.any([n,t]);let r=new AbortController,s=i=>()=>r.abort(i.reason);return n.aborted&&r.abort(n.reason),n.addEventListener("abort",s(n),{once:!0}),t.addEventListener("abort",s(t),{once:!0}),r.signal}async function _t(n){let e=await n.text();if(!e)return null;let t=n.headers.get("content-type")??"",r=e.trimStart();if(t.includes("json")||r.startsWith("{")||r.startsWith("["))try{return JSON.parse(e)}catch{return e}return e}function At(){try{return globalThis.location?.origin??null}catch{return null}}function De(n,e,t,r){if(t?.name==="TimeoutError"||t?.cause?.name==="TimeoutError")return`${n} ${e} timed out after ${r}ms.`;if(t?.name==="AbortError")return`${n} ${e} was aborted.`;let i=At();return`${n} ${e} failed: ${t?.message??t}. In a browser this is most often CORS: the provider must list this app's origin${i&&i!=="null"?` (${i})`:""} in ark_oauth_server:Oidc:CorsOrigins (the Protocol step of the setup wizard). Otherwise the provider is unreachable from here: wrong host or port, offline, or stopped.`}async function qe(n,e={}){let{method:t="GET",form:r,headers:s={},cache:i,timeoutMs:o=Le,signal:a,fetch:h=globalThis.fetch}=e;if(typeof h!="function")throw new $("no fetch implementation is available; pass `fetch` in the client options.");let d={method:t,headers:{Accept:"application/json",...s},signal:ze(a,o),cache:i??"no-store",credentials:"omit",redirect:t==="GET"?"follow":"manual"};if(r){let l=new URLSearchParams;for(let[k,g]of Object.entries(r))g==null||g===""||l.set(k,String(g));d.body=l,d.headers["Content-Type"]="application/x-www-form-urlencoded"}let u;try{u=await h(n,d)}catch(l){throw new $(De(t,n,l,o),{cause:l})}if(u.type==="opaqueredirect"||u.status>=300&&u.status<400)throw new w("server_error",`${t} ${n} answered with a redirect, which is not followed for a token request.`,{status:u.status,endpoint:n});let c=await _t(u);if(!u.ok)throw w.fromResponse(u.status,c,n);return{status:u.status,body:c,headers:u.headers}}async function L(n,e){let{body:t}=await qe(n,{...e,method:"GET"});if(!t||typeof t!="object")throw new w("server_error",`${n} did not return a JSON object.`,{endpoint:n,body:t});return t}async function ge(n,e,t){let{body:r,status:s}=await qe(n,{...t,method:"POST",form:e});if(r===null)return{};if(typeof r!="object")throw new w("server_error",`${n} returned HTTP ${s} with a non-JSON body.`,{endpoint:n,status:s,body:r});return r}async function He(n,e,{timeoutMs:t=Le,fetch:r=globalThis.fetch}={}){let s=new URLSearchParams;for(let[i,o]of Object.entries(e))o!=null&&o!==""&&s.set(i,String(o));try{await r(n,{method:"POST",mode:"no-cors",credentials:"omit",cache:"no-store",keepalive:!0,body:s,signal:ze(void 0,t)})}catch(i){throw new $(De("POST",n,i,t),{cause:i})}}var Tt=5*6e4;function we(n){let e=n.replace(/\/+$/,""),t=new URL(e),r=t.pathname.replace(/\/+$/,"");return[`${e}/.well-known/openid-configuration`,`${t.origin}/.well-known/oauth-authorization-server${r}`]}var D=class{#e;#r;#p;#o=null;constructor(e,{ttlMs:t=Tt,...r}={}){this.#e=e.replace(/\/+$/,""),this.#r=t,this.#p=r}get(e=!1){let t=this.#o;if(t&&!e&&(t.pending||Date.now()-t.fetchedAt<=this.#r))return t.promise;let r={fetchedAt:Date.now(),pending:!0};return r.promise=this.#n(e).then(s=>(r.pending=!1,s),s=>{throw this.#o===r&&(this.#o=null),s}),this.#o=r,r.promise}clear(){this.#o=null}async#n(e){let[t,r]=we(this.#e),s={...this.#p,cache:e?"no-cache":"default"},i;try{i=await L(t,s)}catch(o){if(o instanceof w&&o.status===404)i=await L(r,s);else throw o}if(!i.issuer)throw new w("server_error",`${t} returned a document with no 'issuer'.`,{endpoint:t});if(i.issuer.replace(/\/+$/,"")!==this.#e)throw new f(`the provider at ${t} identifies itself as '${i.issuer}', but this client is configured for '${this.#e}'. Set 'authority' to exactly the issuer value: for Ark that is {BaseUrl}/{TenantId}.`);return Object.freeze(i)}};function je(){let n=globalThis.crypto;if(!n?.getRandomValues)throw new f("ark_oauth_client: this environment has no Web Crypto API (globalThis.crypto).");return n}function re(){let n=je().subtle;if(!n)throw new f("ark_oauth_client: crypto.subtle is unavailable because this page is not a secure context. Serve the app over https, or over http only on localhost / 127.0.0.1 during development.");return n}var ke=new TextEncoder,xt=new TextDecoder;function Ne(n){return n instanceof Uint8Array?n:n instanceof ArrayBuffer?new Uint8Array(n):ArrayBuffer.isView(n)?new Uint8Array(n.buffer,n.byteOffset,n.byteLength):ke.encode(String(n))}function U(n){let e=Ne(n),t="";for(let r=0;r<e.length;r+=32768)t+=String.fromCharCode.apply(null,e.subarray(r,r+32768));return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function B(n){let e=String(n).replace(/-/g,"+").replace(/_/g,"/"),t=e+"=".repeat((4-e.length%4)%4),r;try{r=atob(t)}catch(i){throw new p("a token segment is not valid base64url.",{cause:i})}let s=new Uint8Array(r.length);for(let i=0;i<r.length;i++)s[i]=r.charCodeAt(i);return s}function ye(n){return xt.decode(B(n))}function q(n=32){let e=new Uint8Array(n);return je().getRandomValues(e),U(e)}async function Fe(n,e="SHA-256"){return new Uint8Array(await re().digest(e,Ne(n)))}function ne(n){return Fe(n,"SHA-256")}async function Be(n,e="SHA-256"){let t=await Fe(n,e);return U(t.subarray(0,t.length/2))}function Je(n,e){if(typeof n!="string"||typeof e!="string")return!1;let t=ke.encode(n),r=ke.encode(e),s=t.length^r.length;for(let i=0;i<Math.max(t.length,r.length);i++)s|=(t[i]??0)^(r[i]??0);return s===0}var se={RS256:{kty:"RSA",hash:"SHA-256",importParams:{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},verifyParams:{name:"RSASSA-PKCS1-v1_5"}},RS384:{kty:"RSA",hash:"SHA-384",importParams:{name:"RSASSA-PKCS1-v1_5",hash:"SHA-384"},verifyParams:{name:"RSASSA-PKCS1-v1_5"}},RS512:{kty:"RSA",hash:"SHA-512",importParams:{name:"RSASSA-PKCS1-v1_5",hash:"SHA-512"},verifyParams:{name:"RSASSA-PKCS1-v1_5"}},PS256:{kty:"RSA",hash:"SHA-256",importParams:{name:"RSA-PSS",hash:"SHA-256"},verifyParams:{name:"RSA-PSS",saltLength:32}},PS384:{kty:"RSA",hash:"SHA-384",importParams:{name:"RSA-PSS",hash:"SHA-384"},verifyParams:{name:"RSA-PSS",saltLength:48}},PS512:{kty:"RSA",hash:"SHA-512",importParams:{name:"RSA-PSS",hash:"SHA-512"},verifyParams:{name:"RSA-PSS",saltLength:64}},ES256:{kty:"EC",hash:"SHA-256",crv:"P-256",importParams:{name:"ECDSA",namedCurve:"P-256"},verifyParams:{name:"ECDSA",hash:"SHA-256"}},ES384:{kty:"EC",hash:"SHA-384",crv:"P-384",importParams:{name:"ECDSA",namedCurve:"P-384"},verifyParams:{name:"ECDSA",hash:"SHA-384"}},ES512:{kty:"EC",hash:"SHA-512",crv:"P-521",importParams:{name:"ECDSA",namedCurve:"P-521"},verifyParams:{name:"ECDSA",hash:"SHA-512"}}},be=Object.freeze(Object.keys(se));function vt(n){return se[n]?.hash??"SHA-256"}var We=n=>n!==null&&typeof n=="object"&&!Array.isArray(n);function J(n){if(typeof n!="string")throw new p("the token is not a string.");let e=n.split(".");if(e.length!==3)throw new p(`the token is not a compact JWS: expected 3 segments, found ${e.length}.`);let t,r;try{t=JSON.parse(ye(e[0])),r=JSON.parse(ye(e[1]))}catch(s){throw new p("the token header or payload is not valid JSON.",{cause:s})}if(!We(t)||!We(r))throw new p("the token header and payload must both be JSON objects.");return{header:t,payload:r,signature:B(e[2]),signingInput:`${e[0]}.${e[1]}`}}async function Se(n,e){let t=se[e];if(!t)throw new p(`unsupported signing algorithm '${e}'.`);let r=t.kty==="RSA"?{kty:"RSA",n:n.n,e:n.e}:{kty:"EC",crv:n.crv,x:n.x,y:n.y};try{return await re().importKey("jwk",{...r,ext:!0},t.importParams,!1,["verify"])}catch(s){throw new p(`the published key for kid '${n.kid}' could not be imported: ${s?.message??s}`,{cause:s})}}async function _e(n,e,{algorithms:t,key:r}={}){let s=n.header.alg;if(!s||s==="none")throw new p(`the token declares alg '${s??"missing"}'; unsigned tokens are never accepted.`);let i=t??be;if(!i.includes(s))throw new p(`the token is signed with ${s}, which this client does not accept (allowed: ${i.join(", ")}).`);let o=se[s];if(!o)throw new p(`unsupported signing algorithm '${s}'.`);if(e.kty!==o.kty)throw new p(`the signing key is a ${e.kty} key but the token declares ${s}.`);if(e.alg&&e.alg!==s)throw new p(`the key published for kid '${e.kid}' is registered for ${e.alg}, not ${s}.`);if(e.use&&e.use!=="sig")throw new p(`the key published for kid '${e.kid}' is for '${e.use}', not signing.`);if(o.crv&&e.crv!==o.crv)throw new p(`the key for kid '${e.kid}' is on ${e.crv}, but ${s} needs ${o.crv}.`);let a=r??await Se(e,s);if(!await re().verify(o.verifyParams,a,n.signature,new TextEncoder().encode(n.signingInput)))throw new p("the token signature does not verify against the published key.");return!0}function Ae(n,e={}){let{issuer:t,audience:r,subject:s,nonce:i,maxAgeSeconds:o,clockToleranceSeconds:a=60,requireExp:h=!0,requireIat:d=!1,now:u=Math.floor(Date.now()/1e3)}=e,c=(l,k)=>{throw new p(l,{claim:k})};if(t&&(n.iss||c("the token has no `iss` claim.","iss"),n.iss!==t&&c(`the token was issued by '${n.iss}', not by '${t}'.`,"iss")),r){let l=Array.isArray(n.aud)?n.aud:n.aud?[n.aud]:[];l.length===0&&c("the token has no `aud` claim.","aud"),l.includes(r)||c(`the token is addressed to ${l.map(k=>`'${k}'`).join(", ")}, not to '${r}'.`,"aud"),l.length>1&&n.azp&&n.azp!==r&&c(`the token names '${n.azp}' as its authorized party, not '${r}'.`,"azp")}s&&n.sub!==s&&c(`the token belongs to subject '${n.sub}', not '${s}'.`,"sub"),n.exp===void 0?h&&c("the token has no `exp` claim.","exp"):(typeof n.exp!="number"||u>=n.exp+a)&&c(`the token expired at ${new Date((Number(n.exp)||0)*1e3).toISOString()}.`,"exp");for(let l of["nbf","iat"])n[l]!==void 0&&(typeof n[l]!="number"||!Number.isFinite(n[l]))&&c(`the token's \`${l}\` is not a NumericDate.`,l);return n.nbf!==void 0&&u+a<n.nbf&&c(`the token is not valid before ${new Date(n.nbf*1e3).toISOString()}.`,"nbf"),n.iat===void 0?d&&c("the token has no `iat` claim.","iat"):u+a<n.iat&&c(`the token was issued in the future, at ${new Date(n.iat*1e3).toISOString()}.`,"iat"),i!=null&&(n.nonce||c("the ID token has no `nonce`, so it cannot be tied to this sign-in.","nonce"),n.nonce!==i&&c("the ID token `nonce` does not match the one sent with the authorization request.","nonce")),o!=null&&(typeof n.auth_time!="number"&&c("`max_age` was requested but the ID token carries no `auth_time`.","auth_time"),u-n.auth_time>o+a&&c(`the user authenticated ${u-n.auth_time}s ago, beyond the requested max_age of ${o}s.`,"auth_time")),n}async function Te(n,{alg:e="RS256",accessToken:t,code:r,require:s=!0}={}){let i=vt(e);for(let[o,a]of[["at_hash",t],["c_hash",r]]){if(!a)continue;let h=n[o];if(!h){if(s)throw new p(`the ID token has no \`${o}\`, so the ${o==="at_hash"?"access token":"authorization code"} it arrived with cannot be tied to it.`,{claim:o});continue}if(h!==await Be(a,i))throw new p(`the ID token \`${o}\` does not cover the value it arrived with; it may have been substituted.`,{claim:o})}return n}async function ie(n,e,t={}){let r=J(n),{jwk:s,key:i}=await e.getSigningKey(r.header.kid,r.header.alg);return await _e(r,s,{algorithms:t.algorithms,key:i}),Ae(r.payload,t),(t.accessToken||t.code)&&await Te(r.payload,{alg:r.header.alg,accessToken:t.accessToken,code:t.code,require:t.requireTokenHashes!==!1}),r.payload}var $t={RS:"RSA",PS:"RSA",ES:"EC"},Ct=64,H=class{#e;#r;#p;#o;#n=null;#y=0;#b=0;#S=null;#c=new Set;#d=new Map;constructor(e,{ttlMs:t=5*6e4,minRefreshIntervalMs:r=1e4,...s}={}){this.#e=e,this.#r=t,this.#p=r,this.#o=s}get uri(){return this.#e}async keys({force:e=!1}={}){let t=Date.now()-this.#y>this.#r;return this.#n&&!e&&!t?this.#n:this.#_(e)}async getSigningKey(e,t){let r=this.#s(await this.keys(),e,t);if(r.length===0){let a=e??"\0none";!this.#c.has(a)&&Date.now()-this.#b>=this.#p&&(r=this.#s(await this.keys({force:!0}),e,t)),r.length===0&&(this.#c.size>=Ct&&this.#c.clear(),this.#c.add(a))}if(r.length===0)throw new p(e?`no key with kid '${e}' is published at ${this.#e}; the token may have been signed by a different provider.`:`the token carries no 'kid' and ${this.#e} publishes more than one key, so the signing key is ambiguous.`);let s=r[0],i=`${s.kid??""}|${t}|${s.n??s.x??""}`,o=this.#d.get(i);return o||(o=await Se(s,t),this.#d.set(i,o)),{jwk:s,key:o}}clear(){this.#n=null,this.#y=0,this.#b=0,this.#c.clear(),this.#d.clear()}#s(e,t,r){let s=$t[String(r??"").slice(0,2)],i=e.filter(o=>(!o.use||o.use==="sig")&&(!s||o.kty===s)&&(!o.alg||!r||o.alg===r));return t?i.filter(o=>o.kid===t):i.length===1?i:[]}async#_(e){return e&&(this.#b=Date.now()),this.#S??=(async()=>{try{let t=await L(this.#e,{...this.#o,cache:e?"no-cache":"default"}),r=Array.isArray(t.keys)?t.keys:[];if(r.length===0)throw new p(`${this.#e} published no keys.`);return this.#n=r,this.#y=Date.now(),this.#c.clear(),r}finally{this.#S=null}})(),this.#S}};var I=class n{constructor(e={},{issuedAt:t=Math.floor(Date.now()/1e3),claims:r=null}={}){this.accessToken=e.access_token??null,this.tokenType=e.token_type??"Bearer",this.refreshToken=e.refresh_token??null,this.idToken=e.id_token??null,this.scope=e.scope??null,this.issuedAt=t,this.expiresAt=typeof e.expires_in=="number"?t+e.expires_in:e.expires_at??null,this.claims=r}expiresIn(e=Math.floor(Date.now()/1e3)){return this.expiresAt===null?null:this.expiresAt-e}expired(e=0,t=Math.floor(Date.now()/1e3)){return this.expiresAt===null?!1:t>=this.expiresAt-e}scopes(){return this.scope?this.scope.split(" ").filter(Boolean):[]}hasScope(...e){let t=new Set(this.scopes());return e.flat().every(r=>t.has(r))}arkClaims(){let e=this.accessTokenClaims()?.ark_claims;return Array.isArray(e)?e.map(String):typeof e=="string"?[e]:[]}accessTokenClaims(){if(!this.accessToken)return null;try{return J(this.accessToken).payload}catch{return null}}get subject(){return this.claims?.sub??this.accessTokenClaims()?.sub??null}authorizationHeader(){return`${this.tokenType} ${this.accessToken}`}toJSON(){return{access_token:this.accessToken,token_type:this.tokenType,refresh_token:this.refreshToken,id_token:this.idToken,scope:this.scope,expires_at:this.expiresAt,issued_at:this.issuedAt,claims:this.claims}}static fromJSON(e){return e?e instanceof n?e:new n(e,{issuedAt:e.issued_at??Math.floor(Date.now()/1e3),claims:e.claims??null}):null}};function xe(){return q(32)}async function ve(n){return U(await ne(n))}function W(){return q(24)}function oe(){return q(24)}async function ae(){let n=xe();return{codeVerifier:n,codeChallenge:await ve(n),codeChallengeMethod:"S256"}}var K=Object.freeze({status:"loading",isLoading:!0,isAuthenticated:!1,user:null,arkClaims:Object.freeze([]),scopes:Object.freeze([]),expiresAt:null,error:null,denial:null}),ce=class{#e=K;#r=new Set;get(){return this.#e}set(e){let t={...this.#e,...e};if(t.isLoading=t.status==="loading",t.isAuthenticated=t.status==="authenticated",Object.keys(t).every(r=>Object.is(t[r],this.#e[r])))return this.#e;this.#e=Object.freeze(t);for(let r of[...this.#r])try{r(this.#e)}catch(s){queueMicrotask(()=>{throw s})}return this.#e}subscribe(e){return this.#r.add(e),()=>this.#r.delete(e)}};var j=class{#e=new Map;getItem(e){return this.#e.has(e)?this.#e.get(e):null}setItem(e,t){this.#e.set(e,String(t))}removeItem(e){this.#e.delete(e)}key(e){return[...this.#e.keys()][e]??null}get length(){return this.#e.size}clear(){this.#e.clear()}};function Et(n){return n&&typeof n.getItem=="function"&&typeof n.setItem=="function"&&typeof n.removeItem=="function"}function Rt(n){try{let e="__ark_probe__";return n.setItem(e,"1"),n.removeItem(e),n}catch{return null}}function he(n,e){if(Et(n))return{storage:n,kind:"custom"};if(n==="memory"||!e)return{storage:new j,kind:"memory"};if(n==="session"||n==="local"){let t=null;try{t=n==="session"?e.sessionStorage:e.localStorage}catch{t=null}let r=t?Rt(t):null;return r?{storage:r,kind:n}:{storage:new j,kind:"memory"}}throw new f(`ark_oauth_client: 'storage' must be 'session', 'local', 'memory' or a Storage-like object, not '${n}'.`)}function O(n,e){try{let t=n.getItem(e);return t?JSON.parse(t):null}catch{return null}}function N(n,e,t){try{return n.setItem(e,JSON.stringify(t)),!0}catch{return!1}}function z(n,e){try{n.removeItem(e)}catch{}}function Ke(n,e){let t=[];try{let r=n.length??0;for(let s=0;s<r;s++){let i=n.key(s);i&&i.startsWith(e)&&t.push(i)}}catch{}return t}async function Ve(n,e,t){let r=t?.navigator?.locks??globalThis.navigator?.locks;return r&&typeof r.request=="function"?r.request(n,{mode:"exclusive"},()=>e()):e()}var Ge="ark-oidc:callback";function $e(n,e){return`ark-oidc:${n}|${e}:popup`}function Ye(n,{width:e=520,height:t=680}={}){let r=n.screenX??n.screenLeft??0,s=n.screenY??n.screenTop??0,i=n.outerWidth??e,o=n.outerHeight??t,a=Math.max(0,Math.round(r+(i-e)/2)),h=Math.max(0,Math.round(s+(o-t)/2)),d=`popup=yes,width=${e},height=${t},left=${a},top=${h},resizable=yes,scrollbars=yes`,u=null;try{u=n.open("","ark-oidc-popup",d)}catch{u=null}if(!u)throw new E("blocked","the browser blocked the sign-in popup. Call signinPopup() directly from a click handler, before any await, or use signinRedirect().");return u}function Xe(n,e,{state:t,channelName:r,timeoutMs:s}){let i;return{promise:new Promise((a,h)=>{let d=!1,u=null,c=null,l=null,k=null,g=()=>{d=!0,n.removeEventListener("message",S),u&&(u.onmessage=null,u.close()),clearInterval(c),clearTimeout(l),clearTimeout(k)},_=m=>{d||!m||m.type!==Ge||m.state!==t||typeof m.url!="string"||(g(),a(m.url))},S=m=>{m.origin===n.location.origin&&_(m.data)};n.addEventListener("message",S);let b=n.BroadcastChannel??globalThis.BroadcastChannel;typeof b=="function"&&(u=new b(r),u.onmessage=m=>_(m.data)),c=setInterval(()=>{let m=!1;try{m=e.closed}catch{m=!1}m&&!d&&!l&&(l=setTimeout(()=>{d||(g(),h(new E("closed","the sign-in popup was closed before the sign-in finished.")))},400))},250),k=setTimeout(()=>{if(!d){g();try{e.close()}catch{}h(new E("timeout",`the sign-in popup did not finish within ${Math.round(s/1e3)}s.`))}},s),i=m=>{d||(g(),h(m))}}),cancel:a=>i(a??new E("closed","the sign-in popup was cancelled."))}}function Qe(n,e,t,r){let s=!1,i={type:Ge,url:e,state:t};try{let a=n.opener;a&&a!==n&&(a.postMessage(i,n.location.origin),s=!0)}catch{}let o=n.BroadcastChannel??globalThis.BroadcastChannel;if(typeof o=="function")try{let a=new o(r);a.postMessage(i),a.close(),s=s||!!n.opener||n.name==="ark-oidc-popup"}catch{}return s}var le=["code","state","iss","error","error_description","error_uri","session_state"],Ot=300,Pt=15e3,Ut=50,It=2147483647,Ze=["signedIn","signedOut","tokensRefreshed","refreshFailed","sessionExpired","accessDenied","error"],M=()=>Math.floor(Date.now()/1e3),Mt=0;function Ce(n){return n&&typeof n.unref=="function"&&n.unref(),n}var V=class{#e;#r;#p;#o=null;#n=new ce;#y=new Map(Ze.map(e=>[e,new Set]));#b=`ark-${++Mt}-${Math.random().toString(36).slice(2,8)}`;#S=!1;#c=null;#d="memory";#s=null;#_=null;#i;#t=null;#$={claims:null,arkClaims:Object.freeze([]),scopes:Object.freeze([])};#m=null;#C=null;#O=null;#f=null;#k=null;#P=[];#T=!1;constructor(e={}){this.#e=te(e),this.#r=e.window!==void 0?e.window:typeof window<"u"?window:null,this.#i=`ark.oidc:${this.#e.clientId}@${this.#e.authority}:`,this.#p=new D(this.#e.authority,{ttlMs:this.#e.metadataTtlMs,timeoutMs:this.#e.timeoutMs,fetch:this.#e.fetch}),this.subscribe=this.subscribe.bind(this),this.getSnapshot=this.getSnapshot.bind(this),this.getServerSnapshot=this.getServerSnapshot.bind(this),this.fetch=this.fetch.bind(this),this.getAccessToken=this.getAccessToken.bind(this)}get config(){return this.#e}get authority(){return this.#e.authority}get clientId(){return this.#e.clientId}get isBrowser(){return!!this.#r}getSnapshot(){return this.#n.get()}getServerSnapshot(){return K}subscribe(e){return this.#n.subscribe(e)}get state(){return{subscribe:e=>(e(this.#n.get()),this.#n.subscribe(e))}}getUser(){return this.#n.get().user}on(e,t){let r=this.#y.get(e);if(!r)throw new f(`ark_oauth_client: unknown event '${e}'. Known events: ${Ze.join(", ")}.`);return r.add(t),()=>r.delete(t)}hasArkClaims(...e){let t=this.#n.get().arkClaims;return e.flat().every(r=>t.includes(r))}hasAnyArkClaim(...e){let t=this.#n.get().arkClaims;return e.flat().some(r=>t.includes(r))}hasScopes(...e){let t=this.#n.get().scopes;return e.flat().every(r=>t.includes(r))}init(e={}){return this.#r?(this.#C??=this.#Q(e),this.#C):Promise.resolve(this.#n.get())}async#Q({handleCallback:e=!0,onRedirectCallback:t}={}){this.#h(),this.#he(),this.#ce();let r=this.#r.location.href,s=(i,o)=>{let a=t??this.#e.onRedirectCallback;if(!a)return this.#Y(i);try{Promise.resolve(a(i,o)).catch(h=>this.#a("error",h))}catch(h){this.#a("error",h)}};try{let i=e?this.#H(r):null;if(i==="signin"){let o;try{o=await this.handleRedirectCallback(r)}catch(a){return this.#I(),await this.#M(),this.#W(a)}return o.relayed?this.#n.get():(s(o.returnTo,o),this.#n.get())}if(i==="signout"){let o=this.#ae(r);return o?.then==="signin"?(await this.signinRedirect({prompt:o.prompt??this.#e.accountSwitch.prompt,returnTo:o.returnTo,loginHint:o.loginHint}),this.#n.get()):(this.#l({error:null}),s(o?.returnTo??R(this.#e.accountSwitch.homePath),{signedOut:!0}),this.#n.get())}this.#I(),await this.#M(),this.#l(),this.#A()}catch(i){return this.#W(i)}return this.#n.get()}async createAuthorizationUrl(e={}){let t=this.#w(),r=this.#e,s=await this.metadata();if(s.require_pushed_authorization_requests===!0)throw new f("the tenant requires pushed authorization requests, which a browser app cannot make (/oauth2/par needs client authentication and serves no CORS). Turn RequirePushedAuthorizationRequests off for this tenant, or the client's require_par flag, or sign in through a server-side client.");if(!s.authorization_endpoint)throw new w("server_error","the provider's metadata has no 'authorization_endpoint'.",{endpoint:r.authority});let i=this.#v(e.redirectUri??r.redirectUri),o=e.scopes?.length?[...e.scopes]:[...r.scopes],{codeVerifier:a,codeChallenge:h,codeChallengeMethod:d}=await ae(),u=W(),c=o.includes("openid")?oe():null,l=e.prompt??r.prompt,k=e.acrValues??r.acrValues,g=e.responseMode??r.responseMode,_={...r.extraAuthorizationParams,...e.extra,response_type:"code",client_id:r.clientId,redirect_uri:i,scope:o.join(" "),state:u,code_challenge:h,code_challenge_method:d,response_mode:g,...c?{nonce:c}:{},...l?{prompt:l}:{},...e.loginHint?{login_hint:e.loginHint}:{},...e.maxAge!==void 0&&e.maxAge!==null?{max_age:String(e.maxAge)}:{},...k?{acr_values:k}:{}},S=new URLSearchParams(Object.entries(_).filter(([,C])=>C!=null&&C!=="")),b=`${t.location.pathname}${t.location.search}${t.location.hash}`,m=R(e.returnTo??(this.#H(t.location.href)?"/":b),"/");return{url:`${s.authorization_endpoint}${s.authorization_endpoint.includes("?")?"&":"?"}${S}`,transaction:{state:u,nonce:c,codeVerifier:a,redirectUri:i,responseMode:g,scope:o.join(" "),maxAge:e.maxAge??null,returnTo:m,createdAt:M()}}}async signinRedirect(e={}){this.#h();let{url:t,transaction:r}=await this.createAuthorizationUrl(e);this.#ie(r),await this.#G(t)}async signinPopup(e={}){let t=this.#w(),r=e.popupWindow??Ye(t,this.#e.popup),s=null;try{this.#h();let{url:i,transaction:o}=await this.createAuthorizationUrl(e);s=Xe(t,r,{state:o.state,channelName:$e(this.#e.authority,this.#e.clientId),timeoutMs:this.#e.popup.timeoutMs}),r.location.href=i;let a=await s.promise,h=this.#R(new URL(a),o.responseMode);if(h.error)throw this.#V(h);return await this.#N(h,o)}catch(i){throw s?.cancel(i),this.#l({error:i instanceof y?i:new y(String(i?.message??i))}),this.#a("error",i),i}finally{try{r.closed||r.close()}catch{}}}isSigninCallback(e){return this.#H(String(e??this.#w().location.href))==="signin"}async handleRedirectCallback(e){let t=this.#w();this.#h();let r=String(e??t.location.href),s=new URL(r,t.location.href),i=this.#R(s),o=i.state?this.#oe(i.state):null;if(!o&&i.state&&Qe(t,r,i.state,$e(this.#e.authority,this.#e.clientId)))return setTimeout(()=>{try{t.close()}catch{}},50),{relayed:!0,returnTo:null,user:null,denied:!1};if(this.#K(s),i.error)throw this.#V(i);if(!i.state)throw new T("the authorization response carried no `state`.");if(!o)throw new T("the authorization response does not belong to a sign-in started in this tab (unknown or expired `state`). Start the sign-in again. If this keeps happening, check that the redirect URI is served by this same origin, and that storage is not being cleared between the two pages.");if(!Je(String(i.state),String(o.state)))throw new T("the authorization response `state` does not match the request. Treat this as a CSRF attempt.");return this.#N(i,o)}async#N(e,t){let r=await this.metadata();if(e.iss||r.authorization_response_iss_parameter_supported){if(!e.iss)throw new T("the provider advertises `iss` in authorization responses but this one has none.");if(e.iss!==r.issuer)throw new T(`the authorization response came from '${e.iss}', not from '${r.issuer}'.`)}if(!e.code)throw new T("the authorization response carried no `code`.");let s=await this.#te({code:e.code,codeVerifier:t.codeVerifier,redirectUri:t.redirectUri,nonce:t.nonce??null,maxAge:t.maxAge??null}),i=R(t.returnTo,"/"),o=s.arkClaims();if(!await Pe(this.#e.accountSwitch,this.#e.onEvaluateAccess,{claims:s.claims??{},arkClaims:o,tokens:s})){let h=Ue(Q.NO_APP_ACCESS,s.claims,o,i);return this.#x({...h,idTokenHint:s.idToken,createdAt:M()}),this.#g(null),s.refreshToken&&this.#E(s.refreshToken),this.#l({error:null}),this.#a("accessDenied",this.#n.get().denial),{returnTo:this.#e.accountSwitch.accessDeniedPath??i,user:s.claims,denied:!0}}return this.#x(null),this.#g(s),this.#l({error:null}),this.#A(),this.#a("signedIn",{user:s.claims,returnTo:i}),this.#j("signed-in"),{returnTo:i,user:s.claims,denied:!1}}async getAccessToken({forceRefresh:e=!1}={}){if(!this.#r||(this.#h(),this.#C?await this.#C:this.#I(),!this.#t))return null;if(e||this.#t.expired(this.#D(this.#t))){if(!this.#t.refreshToken)return this.#t.expired(0)?(this.#u("expired",{broadcast:!1}),this.#a("sessionExpired",{reason:"expired"}),null):this.#t.accessToken;try{await this.refresh()}catch(t){if(!this.#t)return null;if(this.#t.expired(0))throw t}}return this.#t?.accessToken??null}refresh(){return this.#O??=this.#Z().finally(()=>{this.#O=null}),this.#O}async#Z(){if(this.#h(),!this.#t?.refreshToken)throw new x("there is no refresh token to renew the session with.");return Ve(`${this.#i}refresh`,async()=>{if(this.#T)throw new y("the client was destroyed.");let e=this.#t;if(!e?.refreshToken)throw new x;if(this.#d!=="memory"){let r=this.#U();if(!r)throw this.#u("signout",{broadcast:!1}),new x;if(r.refreshToken!==e.refreshToken){if(!r.expired(this.#D(r)))return this.#g(r,{persist:!1}),this.#l({error:null}),this.#A(),r;e=r}}if(await this.#re(e.refreshToken))throw this.#u("expired",{broadcast:!1}),this.#a("sessionExpired",{reason:"refresh_token_spent"}),new x("this tab's refresh token was already redeemed by a copy of it (a duplicated tab). Sign in again.");let t;try{let r=await this.metadata(),s=await this.#F(r.token_endpoint,{grant_type:"refresh_token",refresh_token:e.refreshToken});s.refresh_token&&s.refresh_token!==e.refreshToken&&(await this.#ne(e.refreshToken),e=I.fromJSON({...e.toJSON(),refresh_token:s.refresh_token}),this.#g(e)),t=await this.#B(s,{nonce:null,subject:e.claims?.sub??null,previous:e})}catch(r){throw this.#ee(r),r}return this.#g(t),this.#T||(this.#l({error:null}),this.#A(),this.#a("tokensRefreshed",{expiresAt:t.expiresAt}),this.#j("tokens")),t},this.#r)}#ee(e){if(e instanceof p||e instanceof w&&["invalid_grant","invalid_client","unauthorized_client"].includes(e.error)){let r=e instanceof p?this.#t?.refreshToken:null;this.#u("expired",{broadcast:this.#L()}),r&&this.#E(r),this.#a("sessionExpired",{reason:"refresh_refused",error:e});return}this.#a("refreshFailed",{error:e}),this.#e.automaticRefresh&&this.#t&&!this.#T&&(clearTimeout(this.#f),this.#f=Ce(setTimeout(()=>this.refresh().catch(()=>{}),Pt)))}isApiUrl(e){let t=this.#r,r;try{r=new URL(String(e),t?.location?.href)}catch{return!1}let s=t?.location?.origin;return r.origin===s||this.#e.apiOrigins.includes(r.origin)}async fetch(e,t={}){let r=this.#w(),s=typeof e=="string"||e instanceof URL?String(e):e?.url;if(!this.isApiUrl(s)){let u=(()=>{try{return new URL(s,r.location.href).origin}catch{return s}})();throw new f(`ark_oauth_client: refusing to send the access token to ${u}. Add that origin to 'apiOrigins' if it is your API, or call it with plain fetch().`)}let i=this.#e.fetch??globalThis.fetch,o=u=>{let c=new Headers(t.headers??(typeof Request<"u"&&e instanceof Request?e.headers:void 0));return c.set("Authorization",`Bearer ${u}`),i(e,{...t,headers:c})},a=await this.getAccessToken();if(!a)throw new x;let h=await o(a),d=!(typeof Request<"u"&&e instanceof Request)&&!(t.body&&typeof t.body.getReader=="function");if(h.status===401&&d&&this.#t?.refreshToken){let u=h.headers.get("WWW-Authenticate")??"";if(!u||/invalid_token/i.test(u)){let c=await this.getAccessToken({forceRefresh:!0}).catch(()=>null);c&&(h=await o(c))}}return h}async userInfo(){let e=await this.getAccessToken();if(!e)throw new x;let t=await this.metadata();return L(t.userinfo_endpoint,{headers:{Authorization:`Bearer ${e}`},timeoutMs:this.#e.timeoutMs,fetch:this.#e.fetch})}async signoutRedirect({returnTo:e,postLogoutRedirectUri:t,revoke:r=!0,...s}={}){this.#w(),this.#h();let i=this.#t?.idToken??this.#m?.idTokenHint??null,o=this.#t?.refreshToken??null,a=null;try{a=await this.metadata()}catch{a=null}this.#u("signout",{broadcast:!0}),r&&o&&a?.revocation_endpoint&&await this.#E(o,a);let h=R(e??this.#e.accountSwitch.homePath,"/");if(!a?.end_session_endpoint){this.#Y(h);return}let d=new URLSearchParams({client_id:this.#e.clientId});i&&d.set("id_token_hint",i);let u=t??this.#e.postLogoutRedirectUri;if(u){let l=W();d.set("post_logout_redirect_uri",this.#v(u)),d.set("state",l),N(this.#s,`${this.#i}logout:${l}`,{returnTo:h,then:s.then??null,prompt:s.prompt??null,loginHint:s.loginHint??null,createdAt:M()})}let c=a.end_session_endpoint;await this.#G(`${c}${c.includes("?")?"&":"?"}${d}`)}async signoutLocal({revoke:e=!0}={}){this.#h();let t=this.#t?.refreshToken??null;this.#u("signout",{broadcast:!0}),e&&t&&await this.#E(t)}async switchUser({returnTo:e,loginHint:t}={}){let r=this.#e.accountSwitch,s=R(e??this.#m?.returnTo??null,r.homePath);if(r.endProviderSessionOnSwitch){await this.signoutRedirect({returnTo:s,then:"signin",prompt:r.prompt,loginHint:t});return}await this.signoutLocal(),await this.signinRedirect({prompt:r.prompt||"login",returnTo:s,loginHint:t})}clearDenial(){this.#h(),this.#x(null),this.#l()}metadata({force:e=!1}={}){return this.#p.get(e)}async jwks(){let{jwks_uri:e}=await this.metadata();if(!e)throw new w("server_error","the provider's metadata has no 'jwks_uri'.",{endpoint:this.#e.authority});return(!this.#o||this.#o.uri!==e)&&(this.#o=new H(e,{ttlMs:this.#e.jwksTtlMs,minRefreshIntervalMs:this.#e.jwksMinRefreshIntervalMs,timeoutMs:this.#e.timeoutMs,fetch:this.#e.fetch})),this.#o}async verifyIdToken(e,{nonce:t=null,accessToken:r=null,code:s=null,maxAge:i=null,subject:o=null}={}){let a=await this.metadata();return ie(e,await this.jwks(),{issuer:a.issuer,audience:this.#e.clientId,subject:o??void 0,nonce:t,accessToken:r,code:s,maxAgeSeconds:i,requireTokenHashes:this.#e.requireTokenHashes,requireIat:!0,clockToleranceSeconds:this.#e.clockToleranceSeconds,algorithms:this.#e.idTokenSigningAlgorithms??a.id_token_signing_alg_values_supported??void 0})}async checkSetup(){let e=this.#r,t=this.#e,r=t.authority.lastIndexOf("/"),s=t.authority.slice(r+1),i={authority:t.authority,clientId:t.clientId,tenantId:s,origin:e?.location?.origin??null,secureContext:!!(e?.isSecureContext??globalThis.isSecureContext),webCrypto:!!globalThis.crypto?.subtle,storage:(this.#h(),this.#d),scopes:[...t.scopes],responseMode:t.responseMode,redirectUri:e?this.#v(t.redirectUri):t.redirectUri,postLogoutRedirectUri:t.postLogoutRedirectUri&&e?this.#v(t.postLogoutRedirectUri):t.postLogoutRedirectUri,adminConsoleUrl:`${t.authority}/admin`,integrationPageUrl:`${t.authority}/oauth2/integrate/${encodeURIComponent(t.clientId)}`,discoveryUrl:`${t.authority}/.well-known/openid-configuration`,discoveryOk:!1,jwksOk:!1,tokenEndpointCorsOk:null,provider:null,signingKeys:[],problems:[]};(!i.secureContext||!i.webCrypto)&&i.problems.push("This page is not a secure context, so crypto.subtle is unavailable. Serve it over https, or over http on localhost only.");let o;try{o=await this.metadata({force:!0}),i.discoveryOk=!0}catch(c){return i.problems.push(`The provider's discovery document could not be read: ${c.message}`),i}i.provider={issuer:o.issuer,authorizationEndpoint:o.authorization_endpoint,tokenEndpoint:o.token_endpoint,userInfoEndpoint:o.userinfo_endpoint,jwksUri:o.jwks_uri,endSessionEndpoint:o.end_session_endpoint??null,revocationEndpoint:o.revocation_endpoint??null,scopesSupported:o.scopes_supported??[],grantTypesSupported:o.grant_types_supported??[],responseModesSupported:o.response_modes_supported??[],codeChallengeMethodsSupported:o.code_challenge_methods_supported??[],tokenEndpointAuthMethodsSupported:o.token_endpoint_auth_methods_supported??[],requirePushedAuthorizationRequests:o.require_pushed_authorization_requests===!0};try{let c=await(await this.jwks()).keys({force:!0});i.jwksOk=!0,i.signingKeys=c.map(l=>({kid:l.kid??null,kty:l.kty,alg:l.alg??null,use:l.use??null}))}catch(c){i.problems.push(`The provider's signing keys could not be read: ${c.message}`)}try{await ge(o.token_endpoint,{grant_type:"refresh_token",refresh_token:"ark-setup-probe",client_id:t.clientId},{timeoutMs:t.timeoutMs,fetch:t.fetch}),i.tokenEndpointCorsOk=!0}catch(c){i.tokenEndpointCorsOk=!(c instanceof $),i.tokenEndpointCorsOk?c instanceof w&&["invalid_client","unauthorized_client"].includes(c.error)&&i.problems.push(`The token endpoint refused client '${t.clientId}' (${c.error}${c.errorDescription?`: ${c.errorDescription}`:""}). Check the client id, that the client is active, and that it is registered as a public client ('none') for authorization_code and refresh_token.`):i.problems.push(`The token endpoint is not reachable from this page: ${c.message}`)}let a=new Set(o.scopes_supported??[]),h=a.size?t.scopes.filter(c=>!a.has(c)):[];h.length&&i.problems.push(`The tenant does not publish the scope(s) ${h.join(", ")}. A scope the client is not registered for is rejected outright, not dropped.`),(o.code_challenge_methods_supported??[]).includes("S256")||i.problems.push("The tenant does not advertise the S256 PKCE method, which this client always sends.");let d=o.token_endpoint_auth_methods_supported??[];d.length&&!d.includes("none")&&i.problems.push("The tenant does not list the 'none' token endpoint auth method, which a browser (public) client needs.");let u=o.response_modes_supported??[];return u.length&&!u.includes(t.responseMode)&&i.problems.push(`The tenant does not support response_mode '${t.responseMode}' (it lists ${u.join(", ")}).`),t.scopes.includes("offline_access")&&!(o.grant_types_supported??["refresh_token"]).includes("refresh_token")&&i.problems.push("offline_access is requested but the tenant does not serve the refresh_token grant."),t.scopes.includes("offline_access")||i.problems.push("offline_access is not requested, so there is no refresh token: the session ends when the access token expires."),o.require_pushed_authorization_requests===!0&&i.problems.push("The tenant requires pushed authorization requests, which a browser app cannot make."),o.end_session_endpoint||i.problems.push("The provider has no end_session_endpoint, so sign-out can only end the local session."),i}destroy(){this.#T=!0,clearTimeout(this.#f),this.#f=null;for(let e of this.#P.splice(0))e();this.#k&&(this.#k.onmessage=null,this.#k.close(),this.#k=null)}async#te({code:e,codeVerifier:t,redirectUri:r,nonce:s,maxAge:i}){let o=await this.metadata(),a=await this.#F(o.token_endpoint,{grant_type:"authorization_code",code:e,redirect_uri:r,code_verifier:t});return this.#B(a,{nonce:s,code:e,maxAge:i})}#F(e,t){if(!e)throw new w("server_error","the provider's metadata has no 'token_endpoint'.",{endpoint:this.#e.authority});return ge(e,{...t,client_id:this.#e.clientId},{timeoutMs:this.#e.timeoutMs,fetch:this.#e.fetch})}async#B(e,{nonce:t,code:r=null,maxAge:s=null,subject:i=null,previous:o=null}){if(!e.access_token)throw new p("the token response contains no access_token.");let a=null;if(e.id_token)a=await this.verifyIdToken(e.id_token,{nonce:t,accessToken:e.access_token,code:r,maxAge:s,subject:i});else if(t!==null&&String(e.scope??"").split(" ").includes("openid"))throw new p("the token response contains no id_token, although the openid scope was granted.");let h={...e};return o&&(h.refresh_token??=o.refreshToken,h.id_token??=o.idToken),new I(h,{claims:a??o?.claims??null})}#g(e,{persist:t=!0}={}){this.#t=e,this.#$=e?{claims:e.claims?Object.freeze({...e.claims}):null,arkClaims:Object.freeze(e.arkClaims()),scopes:Object.freeze(e.scopes())}:{claims:null,arkClaims:Object.freeze([]),scopes:Object.freeze([])},t&&(e?N(this.#c,`${this.#i}tokens`,e.toJSON()):z(this.#c,`${this.#i}tokens`))}#U(){let e=O(this.#c,`${this.#i}tokens`);return e?.access_token?I.fromJSON(e):null}#I(){if(!this.#t){let e=this.#U();e&&this.#g(e,{persist:!1})}if(!this.#m){let e=O(this.#s,`${this.#i}denied`);e&&M()-(e.createdAt??0)<=Ot?this.#m=e:e&&z(this.#s,`${this.#i}denied`)}}async#M(){if(!(!this.#t||!this.#t.expired(this.#D(this.#t)))){if(!this.#t.refreshToken){this.#t.expired(0)&&this.#u("expired",{broadcast:!1});return}try{await this.refresh()}catch{}}}#u(e,{broadcast:t}){let r=!!(this.#t||this.#m);clearTimeout(this.#f),this.#f=null,this.#g(null),this.#x(null),this.#l(),r&&this.#a("signedOut",{reason:e}),t&&this.#j("signed-out")}async#E(e,t=null){try{let r=t??await this.metadata();if(!r.revocation_endpoint)return;await He(r.revocation_endpoint,{token:e,token_type_hint:"refresh_token",client_id:this.#e.clientId},{timeoutMs:Math.min(this.#e.timeoutMs,5e3),fetch:this.#e.fetch})}catch{}}#A(){clearTimeout(this.#f),this.#f=null;let e=this.#t;if(this.#T||!e||e.expiresAt===null||!this.#r)return;let t=!!(this.#e.automaticRefresh&&e.refreshToken);if(!t&&e.refreshToken)return;let r=t?e.expiresAt-this.#z(e):e.expiresAt,s=Math.min(It,Math.max(0,(r-M())*1e3));this.#f=Ce(setTimeout(()=>{t?this.refresh().catch(()=>{}):this.#t===e&&(this.#u("expired",{broadcast:!1}),this.#a("sessionExpired",{reason:"expired"}))},s))}#L(){return this.#d==="local"||this.#d==="custom"}#z(e,t=this.#e.refreshBeforeSeconds){if(!e||e.expiresAt===null)return t;let r=e.expiresAt-e.issuedAt;return r>0?Math.min(t,r/2):t}#D(e){return this.#z(e,Math.min(30,this.#e.refreshBeforeSeconds))}async#J(e){return U(await ne(`${this.#e.clientId}|${e}`)).slice(0,24)}async#re(e){let t=await this.#J(e);return(O(this.#_,`${this.#i}spent`)??[]).some(r=>r?.h===t)}async#ne(e){let t=await this.#J(e),r=(O(this.#_,`${this.#i}spent`)??[]).filter(s=>s&&s.h!==t);r.push({h:t,at:M()}),N(this.#_,`${this.#i}spent`,r.slice(-Ut))}#h(){if(this.#S)return;this.#S=!0;let{storage:e,kind:t}=he(this.#e.storage,this.#r);this.#c=e,this.#d=t,this.#s=t==="session"?e:he("session",this.#r).storage,this.#_=t==="local"?e:he("local",this.#r).storage}#l(e={}){let t=this.#t,r=this.#m;this.#n.set({status:t?"authenticated":r?"denied":"unauthenticated",user:this.#$.claims,arkClaims:this.#$.arkClaims,scopes:this.#$.scopes,expiresAt:t?.expiresAt??null,denial:r?this.#se(r):null,...e})}#se(e){if(this.#q?.source===e)return this.#q.value;let{idTokenHint:t,createdAt:r,...s}=e,i=Object.freeze({...s,arkClaims:Object.freeze([...s.arkClaims??[]])});return this.#q={source:e,value:i},i}#q=null;#x(e){this.#m=e,e?N(this.#s,`${this.#i}denied`,e):z(this.#s,`${this.#i}denied`)}#W(e){let t=e instanceof y?e:new y(String(e?.message??e),{cause:e});return this.#l({error:t}),this.#A(),this.#a("error",t),this.#n.get()}#ie(e){N(this.#s,`${this.#i}tx:${e.state}`,e)}#oe(e){let t=`${this.#i}tx:${e}`,r=O(this.#s,t);return z(this.#s,t),!r||M()-(r.createdAt??0)>this.#e.transactionTtlSeconds?null:r}#ae(e){let t=this.#R(new URL(e)).state;if(!t)return null;let r=`${this.#i}logout:${t}`,s=O(this.#s,r);return z(this.#s,r),this.#K(new URL(e)),s}#ce(){let e=this.#e.transactionTtlSeconds;for(let t of Ke(this.#s,this.#i)){if(!t.includes(":tx:")&&!t.includes(":logout:"))continue;let r=O(this.#s,t);(!r||M()-(r.createdAt??0)>e)&&z(this.#s,t)}}#w(){if(!this.#r)throw new f("ark_oauth_client: this needs a browser window. On the server (SSR), create the client but call its methods from the browser only, e.g. in an effect.");return this.#r}#v(e){return!e||/^https?:\/\//i.test(e)?e:new URL(e,this.#w().location.origin).toString()}#R(e,t=this.#e.responseMode){let r=e.searchParams,s=new URLSearchParams(e.hash.startsWith("#")?e.hash.slice(1):e.hash),i=t==="fragment"?[s,r]:[r,s],o=i.find(h=>h.has("state")||h.has("code")||h.has("error"))??i[0],a={};for(let h of le){let d=o.get(h);d!==null&&(a[h]=d)}return a}#H(e){if(!this.#r)return null;let t;try{t=new URL(e,this.#r.location.href)}catch{return null}let r=i=>{if(!i)return!1;let o=new URL(this.#v(i));return o.origin===t.origin&&o.pathname===t.pathname},s=this.#R(t);return r(this.#e.redirectUri)&&(s.code||s.error)?"signin":r(this.#e.postLogoutRedirectUri??F)&&s.state&&(this.#h(),O(this.#s,`${this.#i}logout:${s.state}`))?"signout":null}#K(e){let t=this.#r;if(!t?.history?.replaceState)return;let r=new URL(e.toString());for(let i of le)r.searchParams.delete(i);if(r.hash){let i=new URLSearchParams(r.hash.slice(1));if(le.some(o=>i.has(o))){for(let a of le)i.delete(a);let o=i.toString();r.hash=o?`#${o}`:""}}let s=`${r.pathname}${r.search}${r.hash}`;try{t.history.replaceState(t.history.state,"",s)}catch{}}#V(e){return new w(e.error,e.error_description,{endpoint:`${this.#e.authority}/oauth2/authorize`,errorUri:e.error_uri??null,body:e})}async#G(e){if(this.#e.redirect)return this.#e.redirect(e);this.#w().location.assign(e)}#Y(e){if(this.#e.navigate)return this.#e.navigate(e);let t=this.#r;if(t)try{t.history.replaceState(null,"",e);let r=t.PopStateEvent??globalThis.PopStateEvent;typeof r=="function"&&t.dispatchEvent(new r("popstate",{state:null}))}catch{t.location.replace(e)}}#a(e,t){for(let r of[...this.#y.get(e)??[]])try{r(t)}catch(s){queueMicrotask(()=>{throw s})}}#j(e){try{this.#k?.postMessage({type:e,from:this.#b})}catch{}}#he(){let e=this.#r;if(!e||this.#P.length)return;if(this.#e.syncTabs){let r=e.BroadcastChannel??globalThis.BroadcastChannel;typeof r=="function"&&(this.#k=Ce(new r(`ark-oidc:${this.#e.authority}|${this.#e.clientId}`)),this.#k.onmessage=s=>this.#le(s.data))}let t=e.document;if(t?.addEventListener){let r=()=>{t.visibilityState!=="visible"||!this.#t||(this.#L()&&this.#X(),this.#t?.expired(this.#z(this.#t))&&this.#M())};t.addEventListener("visibilitychange",r),this.#P.push(()=>t.removeEventListener("visibilitychange",r))}}#le(e){if(!(!e||e.from===this.#b)){if(e.type==="signed-out"){(this.#t||this.#m)&&this.#u("signout",{broadcast:!1});return}(e.type==="tokens"||e.type==="signed-in")&&this.#L()&&this.#X()}}#X(){let e=this.#U();if(!e){this.#t&&this.#u("signout",{broadcast:!1});return}e.accessToken!==this.#t?.accessToken&&(this.#g(e,{persist:!1}),this.#x(null),this.#l({error:null}),this.#A())}};function et(n){return new V(n)}var Lt={light:{bg:"#f7f7f8",surface:"#ffffff",border:"#e2e2e6",fg:"#17171a",muted:"#6a6a73",accent:"#4f46e5",accentFg:"#ffffff"},dark:{bg:"#111114",surface:"#1a1a1f",border:"#313139",fg:"#ececf1",muted:"#9a9aa5",accent:"#8b85ff",accentFg:"#16161c"}};function A(n,e,t,r){let s=n.createElement(e);return t&&(s.className=t),r!==void 0&&(s.textContent=r),s}function v(n,e){for(let[t,r]of Object.entries(e))n.style.setProperty(t,r)}function tt(n,e,t={}){let r=n.ownerDocument??globalThis.document,s=e.config.accountSwitch,i=e.getSnapshot().denial,o=(t.appName??s.appDisplayName??"").trim()||e.clientId||"this application",a=s.showSignedInAccount?i?.email??i?.name??i?.subject??null:null,h=!!r.defaultView?.matchMedia?.("(prefers-color-scheme: dark)").matches,d=Lt[h?"dark":"light"],u=!t.unstyled,c=A(r,"main","ark-denied");c.setAttribute("role","alert");let l=A(r,"div","ark-denied__card");c.append(l),l.append(A(r,"h1","ark-denied__title",`You do not have access to ${o}`));let k=A(r,"p","ark-denied__lede");a?k.append("You are signed in as ",A(r,"strong",null,a),`, and that account does not have access to ${o}.`):k.textContent=`The account you are signed in with does not have access to ${o}.`,l.append(k),l.append(A(r,"p","ark-denied__hint",`If somebody else was using this browser, their sign-in is still active and it is the one being offered to ${o}. Choose \u201CSign in as a different user\u201D to enter your own credentials.`));let g=A(r,"div","ark-denied__actions"),_=A(r,"button","ark-denied__switch","Sign in as a different user");_.type="button",_.addEventListener("click",()=>e.switchUser({returnTo:i?.returnTo??void 0})),g.append(_);let S=null;s.allowFullSignOut&&(S=A(r,"button","ark-denied__signout","Sign out completely"),S.type="button",S.addEventListener("click",()=>e.signoutRedirect({returnTo:s.homePath})),g.append(S)),l.append(g);let b=null;if(s.supportUrl||s.supportEmail){b=A(r,"p","ark-denied__foot",`Need access to ${o}? `);let C=A(r,"a",null,s.supportUrl?"Request it here":s.supportEmail);C.href=s.supportUrl?s.supportUrl:`mailto:${s.supportEmail}`,b.append(C),l.append(b)}let m=A(r,"p","ark-denied__version",`ark-oauth-client-js ${Y}`);if(l.append(m),u){v(c,{"min-height":"100vh",display:"flex","align-items":"center","justify-content":"center",padding:"24px","box-sizing":"border-box",background:d.bg,color:d.fg,font:'15px/1.55 ui-sans-serif, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif'}),v(l,{width:"100%","max-width":"480px",background:d.surface,border:`1px solid ${d.border}`,"border-radius":"12px",padding:"28px","box-sizing":"border-box"});for(let ue of l.querySelectorAll("p"))v(ue,{margin:"0 0 14px",color:d.muted});v(k,{color:d.fg}),v(l.querySelector("h1"),{margin:"0 0 10px","font-size":"19px","font-weight":"640"}),v(g,{display:"flex","flex-direction":"column",gap:"10px","margin-top":"20px"});let G={width:"100%",padding:"11px 14px","border-radius":"8px",font:"inherit","font-weight":"560",cursor:"pointer"};v(_,{...G,border:`1px solid ${d.accent}`,background:d.accent,color:d.accentFg}),S&&v(S,{...G,border:`1px solid ${d.border}`,background:"transparent",color:d.fg}),b&&(v(b,{"margin-top":"18px","padding-top":"14px","border-top":`1px solid ${d.border}`,"font-size":"13px"}),v(b.querySelector("a"),{color:d.accent})),v(m,{margin:"18px 0 0","padding-top":"14px","border-top":b?"0":`1px solid ${d.border}`,"font-size":"12px","text-align":"center"})}return n.replaceChildren(c),()=>c.remove()}return bt(zt);})();
1
+ /*! ark-oauth-client-js 2.3.0 | MIT | https://github.com/ir-dev/ark-oauth-oidc */
2
+ var ArkOAuth=(()=>{var de=Object.defineProperty;var mt=Object.getOwnPropertyDescriptor;var gt=Object.getOwnPropertyNames;var wt=Object.prototype.hasOwnProperty;var kt=(n,e)=>{for(var t in e)de(n,t,{get:e[t],enumerable:!0})},yt=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of gt(e))!wt.call(n,s)&&s!==t&&de(n,s,{get:()=>e[s],enumerable:!(r=mt(e,s))||r.enumerable});return n};var bt=n=>yt(de({},"__esModule",{value:!0}),n);var zt={};kt(zt,{ACCOUNT_SWITCH_DEFAULTS:()=>X,ArkAccessDeniedReasons:()=>Q,ArkBrowserClient:()=>V,ArkCallbackError:()=>T,ArkChallengeProperties:()=>fe,ArkConfigError:()=>f,ArkError:()=>y,ArkLoginRequiredError:()=>x,ArkNetworkError:()=>$,ArkOAuthError:()=>w,ArkPopupError:()=>E,ArkTokenError:()=>p,DEFAULT_POST_LOGOUT_PATH:()=>F,DEFAULT_REDIRECT_PATH:()=>ee,DEFAULT_SCOPES:()=>pe,INITIAL_SNAPSHOT:()=>K,JwksCache:()=>H,MemoryStorage:()=>j,MetadataResolver:()=>D,SUPPORTED_ALGORITHMS:()=>be,TokenSet:()=>I,VERSION:()=>Y,base64UrlDecode:()=>B,base64UrlEncode:()=>U,codeChallengeFor:()=>ve,createArkClient:()=>et,createCodeVerifier:()=>xe,createNonce:()=>oe,createPkcePair:()=>ae,createState:()=>W,decodeJwt:()=>J,discoveryUrls:()=>we,localOrDefault:()=>R,normalizeAccountSwitch:()=>Z,normalizeConfig:()=>te,randomToken:()=>q,renderAccessDenied:()=>tt,validateClaims:()=>Ae,validateTokenHashes:()=>Te,verifyJwt:()=>ie,verifySignature:()=>_e});var Y="2.3.0";var y=class extends Error{constructor(e,t){super(e,t),this.name=new.target.name}},f=class extends y{},w=class n extends y{constructor(e,t,{status:r=0,endpoint:s=null,errorUri:i=null,body:o=null}={}){super(t?`${e}: ${t}`:e),this.error=e,this.errorDescription=t??null,this.errorUri=i,this.status=r,this.endpoint=s,this.body=o}static fromResponse(e,t,r){return t&&typeof t=="object"&&typeof t.error=="string"?new n(t.error,t.error_description,{status:e,endpoint:r,errorUri:t.error_uri??null,body:t}):new n("server_error",`the endpoint returned HTTP ${e}.`,{status:e,endpoint:r,body:t})}},p=class extends y{constructor(e,{claim:t=null}={}){super(e),this.claim=t}},T=class extends y{},$=class extends y{},x=class extends y{constructor(e="no user is signed in, or the session has ended. Call signinRedirect() to sign in."){super(e),this.error="login_required"}},E=class extends y{constructor(e,t){super(t),this.reason=e}};var Q=Object.freeze({NO_APP_ACCESS:"no_app_access",FORBIDDEN:"forbidden"}),X=Object.freeze({requireArkClaims:!1,requiredClaims:Object.freeze([]),accessDeniedPath:null,prompt:"login",endProviderSessionOnSwitch:!1,appDisplayName:null,showSignedInAccount:!0,allowFullSignOut:!0,homePath:"/",supportUrl:null,supportEmail:null});function R(n,e="/"){let t=typeof e=="string"&&e.trim()?e:e===null?null:"/";if(typeof n!="string"||!n.trim())return t;let r=n.trim();return!r.startsWith("/")||r.startsWith("//")||r.startsWith("/\\")||/[\u0000-\u001f\u007f]/.test(r)?t:r}function Z(n={}){let e={...X};for(let[t,r]of Object.entries(n??{}))Object.prototype.hasOwnProperty.call(X,t)&&r!==void 0&&(e[t]=r);for(let t of["accessDeniedPath","homePath"])if(e[t]!==null&&R(e[t],null)!==e[t])throw new f(`ark_oauth_client: accountSwitch.${t} must be a local path starting with '/', but is '${e[t]}'.`);if(e.supportUrl&&!/^https?:\/\//i.test(e.supportUrl))throw new f(`ark_oauth_client: accountSwitch.supportUrl must be an http(s) URL, but is '${e.supportUrl}'.`);return e.requiredClaims=Object.freeze([...e.requiredClaims??[]].map(String)),Object.freeze(e)}var fe=Object.freeze({switchUser(n=null,e=null,t="login"){return{returnTo:n||"/",prompt:t||"login",...e?{loginHint:e}:{}}},selectAccount(n=null){return fe.switchUser(n,null,"select_account")}});async function Pe(n,e,{claims:t={},arkClaims:r=[],tokens:s=null}={}){let i=n.requiredClaims.map(a=>a.toLowerCase()),o=!n.requireArkClaims||(i.length?r.some(a=>i.includes(String(a).toLowerCase())):r.length>0);return typeof e!="function"?o:!!await e({claims:{...t},arkClaims:[...r],allowedByConfiguration:o,tokens:s})}function Ue(n,e,t,r){let s=(...i)=>{for(let o of i)if(e?.[o])return String(e[o]);return null};return{reason:n,subject:s("sub"),email:s("email","preferred_username"),name:s("name"),arkClaims:[...t??[]],returnTo:r??null}}var pe=Object.freeze(["openid","profile","email","offline_access"]),ee="/signin-oidc",F="/signout-callback-oidc";function Me(n){return["localhost","127.0.0.1","[::1]","::1"].includes(n.hostname)}function me(n,e){let t;try{t=new URL(n)}catch{throw new f(`ark_oauth_client: '${e}' must be an absolute URL, but is '${n}'.`)}if(t.protocol!=="https:"&&t.protocol!=="http:")throw new f(`ark_oauth_client: '${e}' must be an http or https URL, but is '${n}'.`);return t}function Ie(n,e){if(n==null||n==="")return null;let t=String(n);if(t.startsWith("/")&&!t.startsWith("//")){if(t.includes("#"))throw new f(`ark_oauth_client: '${e}' must not contain a fragment: ${t}`);return t}let r=me(t,e);if(r.hash)throw new f(`ark_oauth_client: '${e}' must not contain a fragment: ${t}`);if(r.protocol!=="https:"&&!Me(r))throw new f(`ark_oauth_client: '${e}' is ${t}. The server accepts http only for loopback addresses (RFC 8252 \xA77.3).`);return t}function St(n){return Object.freeze([...n??[]].map(e=>{if(e==="*")throw new f("ark_oauth_client: 'apiOrigins' cannot be '*'. List the exact origins the access token may be sent to.");return me(String(e),"apiOrigins").origin}))}function te(n={}){let{authority:e,authServerUrl:t,tenantId:r,clientId:s,clientSecret:i,privateKeyJwt:o,tokenEndpointAuthMethod:a,usePar:h,redirectUri:d=ee,postLogoutRedirectUri:u=F,scopes:c,responseMode:l="query",prompt:k=null,acrValues:g=null,extraAuthorizationParams:_=null,storage:S="session",automaticRefresh:b=!0,refreshBeforeSeconds:m=60,apiOrigins:C=[],syncTabs:G=!0,accountSwitch:ue,onEvaluateAccess:rt=null,onRedirectCallback:nt=null,navigate:st=null,redirect:it=null,popup:ot={},transactionTtlSeconds:at=600,clockToleranceSeconds:ct=60,requireHttps:Ee=!0,requireTokenHashes:ht=!0,idTokenSigningAlgorithms:Re=null,timeoutMs:lt=1e4,metadataTtlMs:ut=5*6e4,jwksTtlMs:dt=5*6e4,jwksMinRefreshIntervalMs:ft=1e4,fetch:pt=void 0}=n,P=String(e??"").trim();if(!P&&t&&r&&(P=`${String(t).replace(/\/+$/,"")}/${r}`),!P)throw new f("ark_oauth_client: set 'authority' to the issuer URL of your Ark tenant, {BaseUrl}/{TenantId}, e.g. https://idp.example.com/my_idp. (Or set authServerUrl + tenantId and they are joined for you.)");P=P.replace(/\/+$/,"");let Oe=me(P,"authority");if(Ee&&Oe.protocol!=="https:"&&!Me(Oe))throw new f(`ark_oauth_client: 'authority' is ${P}, which is plain http. Tokens would cross the network in the clear. Use https, or set requireHttps:false, only ever for local development.`);if(!s||typeof s!="string")throw new f("ark_oauth_client: 'clientId' is required: the client id registered with the tenant.");if(i||o||a&&a!=="none")throw new f("ark_oauth_client: a browser app cannot keep a client secret or a private key: anything in the bundle is readable by every visitor. Register this app as a public client (token endpoint auth method 'none'; PKCE protects the code), or keep the confidential client on a server with ark-oauth-client-node (Node), ark-oauth-client (Python) or Ark.oAuth.Client (.NET).");if(h)throw new f("ark_oauth_client: 'usePar' is not available in a browser app: /oauth2/par needs client authentication and serves no CORS. Leave PAR to a server-side client.");if(!["query","fragment"].includes(l))throw new f(`ark_oauth_client: 'responseMode' is '${l}'. A browser app reads the response from its own URL, so use 'query' or 'fragment'`+(l==="form_post"?"; form_post POSTs to a server, which a single-page app does not have.":"."));if(!Number.isFinite(m)||m<0)throw new f(`ark_oauth_client: 'refreshBeforeSeconds' must be a number of seconds, not '${m}'.`);return Object.freeze({authority:P,clientId:s,redirectUri:Ie(d,"redirectUri")??ee,postLogoutRedirectUri:Ie(u,"postLogoutRedirectUri"),scopes:Object.freeze(c?.length?[...c]:[...pe]),responseMode:l,prompt:k,acrValues:g,extraAuthorizationParams:_?Object.freeze({..._}):null,storage:S,automaticRefresh:!!b,refreshBeforeSeconds:m,apiOrigins:St(C),syncTabs:!!G,accountSwitch:Z(ue),onEvaluateAccess:rt,onRedirectCallback:nt,navigate:st,redirect:it,popup:Object.freeze({width:520,height:680,timeoutMs:5*6e4,...ot}),transactionTtlSeconds:at,clockToleranceSeconds:ct,requireHttps:Ee,requireTokenHashes:ht,idTokenSigningAlgorithms:Re?Object.freeze([...Re]):null,timeoutMs:lt,metadataTtlMs:ut,jwksTtlMs:dt,jwksMinRefreshIntervalMs:ft,fetch:pt})}var Le=1e4;function ze(n,e){let t;if(typeof AbortSignal.timeout=="function")t=AbortSignal.timeout(e);else{let i=new AbortController;setTimeout(()=>i.abort(new DOMException("The operation timed out.","TimeoutError")),e),t=i.signal}if(!n)return t;if(typeof AbortSignal.any=="function")return AbortSignal.any([n,t]);let r=new AbortController,s=i=>()=>r.abort(i.reason);return n.aborted&&r.abort(n.reason),n.addEventListener("abort",s(n),{once:!0}),t.addEventListener("abort",s(t),{once:!0}),r.signal}async function _t(n){let e=await n.text();if(!e)return null;let t=n.headers.get("content-type")??"",r=e.trimStart();if(t.includes("json")||r.startsWith("{")||r.startsWith("["))try{return JSON.parse(e)}catch{return e}return e}function At(){try{return globalThis.location?.origin??null}catch{return null}}function De(n,e,t,r){if(t?.name==="TimeoutError"||t?.cause?.name==="TimeoutError")return`${n} ${e} timed out after ${r}ms.`;if(t?.name==="AbortError")return`${n} ${e} was aborted.`;let i=At();return`${n} ${e} failed: ${t?.message??t}. In a browser this is most often CORS: the provider must list this app's origin${i&&i!=="null"?` (${i})`:""} in ark_oauth_server:Oidc:CorsOrigins (the Protocol step of the setup wizard). Otherwise the provider is unreachable from here: wrong host or port, offline, or stopped.`}async function qe(n,e={}){let{method:t="GET",form:r,headers:s={},cache:i,timeoutMs:o=Le,signal:a,fetch:h=globalThis.fetch}=e;if(typeof h!="function")throw new $("no fetch implementation is available; pass `fetch` in the client options.");let d={method:t,headers:{Accept:"application/json",...s},signal:ze(a,o),cache:i??"no-store",credentials:"omit",redirect:t==="GET"?"follow":"manual"};if(r){let l=new URLSearchParams;for(let[k,g]of Object.entries(r))g==null||g===""||l.set(k,String(g));d.body=l,d.headers["Content-Type"]="application/x-www-form-urlencoded"}let u;try{u=await h(n,d)}catch(l){throw new $(De(t,n,l,o),{cause:l})}if(u.type==="opaqueredirect"||u.status>=300&&u.status<400)throw new w("server_error",`${t} ${n} answered with a redirect, which is not followed for a token request.`,{status:u.status,endpoint:n});let c=await _t(u);if(!u.ok)throw w.fromResponse(u.status,c,n);return{status:u.status,body:c,headers:u.headers}}async function L(n,e){let{body:t}=await qe(n,{...e,method:"GET"});if(!t||typeof t!="object")throw new w("server_error",`${n} did not return a JSON object.`,{endpoint:n,body:t});return t}async function ge(n,e,t){let{body:r,status:s}=await qe(n,{...t,method:"POST",form:e});if(r===null)return{};if(typeof r!="object")throw new w("server_error",`${n} returned HTTP ${s} with a non-JSON body.`,{endpoint:n,status:s,body:r});return r}async function He(n,e,{timeoutMs:t=Le,fetch:r=globalThis.fetch}={}){let s=new URLSearchParams;for(let[i,o]of Object.entries(e))o!=null&&o!==""&&s.set(i,String(o));try{await r(n,{method:"POST",mode:"no-cors",credentials:"omit",cache:"no-store",keepalive:!0,body:s,signal:ze(void 0,t)})}catch(i){throw new $(De("POST",n,i,t),{cause:i})}}var Tt=5*6e4;function we(n){let e=n.replace(/\/+$/,""),t=new URL(e),r=t.pathname.replace(/\/+$/,"");return[`${e}/.well-known/openid-configuration`,`${t.origin}/.well-known/oauth-authorization-server${r}`]}var D=class{#e;#r;#p;#o=null;constructor(e,{ttlMs:t=Tt,...r}={}){this.#e=e.replace(/\/+$/,""),this.#r=t,this.#p=r}get(e=!1){let t=this.#o;if(t&&!e&&(t.pending||Date.now()-t.fetchedAt<=this.#r))return t.promise;let r={fetchedAt:Date.now(),pending:!0};return r.promise=this.#n(e).then(s=>(r.pending=!1,s),s=>{throw this.#o===r&&(this.#o=null),s}),this.#o=r,r.promise}clear(){this.#o=null}async#n(e){let[t,r]=we(this.#e),s={...this.#p,cache:e?"no-cache":"default"},i;try{i=await L(t,s)}catch(o){if(o instanceof w&&o.status===404)i=await L(r,s);else throw o}if(!i.issuer)throw new w("server_error",`${t} returned a document with no 'issuer'.`,{endpoint:t});if(i.issuer.replace(/\/+$/,"")!==this.#e)throw new f(`the provider at ${t} identifies itself as '${i.issuer}', but this client is configured for '${this.#e}'. Set 'authority' to exactly the issuer value: for Ark that is {BaseUrl}/{TenantId}.`);return Object.freeze(i)}};function je(){let n=globalThis.crypto;if(!n?.getRandomValues)throw new f("ark_oauth_client: this environment has no Web Crypto API (globalThis.crypto).");return n}function re(){let n=je().subtle;if(!n)throw new f("ark_oauth_client: crypto.subtle is unavailable because this page is not a secure context. Serve the app over https, or over http only on localhost / 127.0.0.1 during development.");return n}var ke=new TextEncoder,xt=new TextDecoder;function Ne(n){return n instanceof Uint8Array?n:n instanceof ArrayBuffer?new Uint8Array(n):ArrayBuffer.isView(n)?new Uint8Array(n.buffer,n.byteOffset,n.byteLength):ke.encode(String(n))}function U(n){let e=Ne(n),t="";for(let r=0;r<e.length;r+=32768)t+=String.fromCharCode.apply(null,e.subarray(r,r+32768));return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function B(n){let e=String(n).replace(/-/g,"+").replace(/_/g,"/"),t=e+"=".repeat((4-e.length%4)%4),r;try{r=atob(t)}catch(i){throw new p("a token segment is not valid base64url.",{cause:i})}let s=new Uint8Array(r.length);for(let i=0;i<r.length;i++)s[i]=r.charCodeAt(i);return s}function ye(n){return xt.decode(B(n))}function q(n=32){let e=new Uint8Array(n);return je().getRandomValues(e),U(e)}async function Fe(n,e="SHA-256"){return new Uint8Array(await re().digest(e,Ne(n)))}function ne(n){return Fe(n,"SHA-256")}async function Be(n,e="SHA-256"){let t=await Fe(n,e);return U(t.subarray(0,t.length/2))}function Je(n,e){if(typeof n!="string"||typeof e!="string")return!1;let t=ke.encode(n),r=ke.encode(e),s=t.length^r.length;for(let i=0;i<Math.max(t.length,r.length);i++)s|=(t[i]??0)^(r[i]??0);return s===0}var se={RS256:{kty:"RSA",hash:"SHA-256",importParams:{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},verifyParams:{name:"RSASSA-PKCS1-v1_5"}},RS384:{kty:"RSA",hash:"SHA-384",importParams:{name:"RSASSA-PKCS1-v1_5",hash:"SHA-384"},verifyParams:{name:"RSASSA-PKCS1-v1_5"}},RS512:{kty:"RSA",hash:"SHA-512",importParams:{name:"RSASSA-PKCS1-v1_5",hash:"SHA-512"},verifyParams:{name:"RSASSA-PKCS1-v1_5"}},PS256:{kty:"RSA",hash:"SHA-256",importParams:{name:"RSA-PSS",hash:"SHA-256"},verifyParams:{name:"RSA-PSS",saltLength:32}},PS384:{kty:"RSA",hash:"SHA-384",importParams:{name:"RSA-PSS",hash:"SHA-384"},verifyParams:{name:"RSA-PSS",saltLength:48}},PS512:{kty:"RSA",hash:"SHA-512",importParams:{name:"RSA-PSS",hash:"SHA-512"},verifyParams:{name:"RSA-PSS",saltLength:64}},ES256:{kty:"EC",hash:"SHA-256",crv:"P-256",importParams:{name:"ECDSA",namedCurve:"P-256"},verifyParams:{name:"ECDSA",hash:"SHA-256"}},ES384:{kty:"EC",hash:"SHA-384",crv:"P-384",importParams:{name:"ECDSA",namedCurve:"P-384"},verifyParams:{name:"ECDSA",hash:"SHA-384"}},ES512:{kty:"EC",hash:"SHA-512",crv:"P-521",importParams:{name:"ECDSA",namedCurve:"P-521"},verifyParams:{name:"ECDSA",hash:"SHA-512"}}},be=Object.freeze(Object.keys(se));function vt(n){return se[n]?.hash??"SHA-256"}var We=n=>n!==null&&typeof n=="object"&&!Array.isArray(n);function J(n){if(typeof n!="string")throw new p("the token is not a string.");let e=n.split(".");if(e.length!==3)throw new p(`the token is not a compact JWS: expected 3 segments, found ${e.length}.`);let t,r;try{t=JSON.parse(ye(e[0])),r=JSON.parse(ye(e[1]))}catch(s){throw new p("the token header or payload is not valid JSON.",{cause:s})}if(!We(t)||!We(r))throw new p("the token header and payload must both be JSON objects.");return{header:t,payload:r,signature:B(e[2]),signingInput:`${e[0]}.${e[1]}`}}async function Se(n,e){let t=se[e];if(!t)throw new p(`unsupported signing algorithm '${e}'.`);let r=t.kty==="RSA"?{kty:"RSA",n:n.n,e:n.e}:{kty:"EC",crv:n.crv,x:n.x,y:n.y};try{return await re().importKey("jwk",{...r,ext:!0},t.importParams,!1,["verify"])}catch(s){throw new p(`the published key for kid '${n.kid}' could not be imported: ${s?.message??s}`,{cause:s})}}async function _e(n,e,{algorithms:t,key:r}={}){let s=n.header.alg;if(!s||s==="none")throw new p(`the token declares alg '${s??"missing"}'; unsigned tokens are never accepted.`);let i=t??be;if(!i.includes(s))throw new p(`the token is signed with ${s}, which this client does not accept (allowed: ${i.join(", ")}).`);let o=se[s];if(!o)throw new p(`unsupported signing algorithm '${s}'.`);if(e.kty!==o.kty)throw new p(`the signing key is a ${e.kty} key but the token declares ${s}.`);if(e.alg&&e.alg!==s)throw new p(`the key published for kid '${e.kid}' is registered for ${e.alg}, not ${s}.`);if(e.use&&e.use!=="sig")throw new p(`the key published for kid '${e.kid}' is for '${e.use}', not signing.`);if(o.crv&&e.crv!==o.crv)throw new p(`the key for kid '${e.kid}' is on ${e.crv}, but ${s} needs ${o.crv}.`);let a=r??await Se(e,s);if(!await re().verify(o.verifyParams,a,n.signature,new TextEncoder().encode(n.signingInput)))throw new p("the token signature does not verify against the published key.");return!0}function Ae(n,e={}){let{issuer:t,audience:r,subject:s,nonce:i,maxAgeSeconds:o,clockToleranceSeconds:a=60,requireExp:h=!0,requireIat:d=!1,now:u=Math.floor(Date.now()/1e3)}=e,c=(l,k)=>{throw new p(l,{claim:k})};if(t&&(n.iss||c("the token has no `iss` claim.","iss"),n.iss!==t&&c(`the token was issued by '${n.iss}', not by '${t}'.`,"iss")),r){let l=Array.isArray(n.aud)?n.aud:n.aud?[n.aud]:[];l.length===0&&c("the token has no `aud` claim.","aud"),l.includes(r)||c(`the token is addressed to ${l.map(k=>`'${k}'`).join(", ")}, not to '${r}'.`,"aud"),l.length>1&&n.azp&&n.azp!==r&&c(`the token names '${n.azp}' as its authorized party, not '${r}'.`,"azp")}s&&n.sub!==s&&c(`the token belongs to subject '${n.sub}', not '${s}'.`,"sub"),n.exp===void 0?h&&c("the token has no `exp` claim.","exp"):(typeof n.exp!="number"||u>=n.exp+a)&&c(`the token expired at ${new Date((Number(n.exp)||0)*1e3).toISOString()}.`,"exp");for(let l of["nbf","iat"])n[l]!==void 0&&(typeof n[l]!="number"||!Number.isFinite(n[l]))&&c(`the token's \`${l}\` is not a NumericDate.`,l);return n.nbf!==void 0&&u+a<n.nbf&&c(`the token is not valid before ${new Date(n.nbf*1e3).toISOString()}.`,"nbf"),n.iat===void 0?d&&c("the token has no `iat` claim.","iat"):u+a<n.iat&&c(`the token was issued in the future, at ${new Date(n.iat*1e3).toISOString()}.`,"iat"),i!=null&&(n.nonce||c("the ID token has no `nonce`, so it cannot be tied to this sign-in.","nonce"),n.nonce!==i&&c("the ID token `nonce` does not match the one sent with the authorization request.","nonce")),o!=null&&(typeof n.auth_time!="number"&&c("`max_age` was requested but the ID token carries no `auth_time`.","auth_time"),u-n.auth_time>o+a&&c(`the user authenticated ${u-n.auth_time}s ago, beyond the requested max_age of ${o}s.`,"auth_time")),n}async function Te(n,{alg:e="RS256",accessToken:t,code:r,require:s=!0}={}){let i=vt(e);for(let[o,a]of[["at_hash",t],["c_hash",r]]){if(!a)continue;let h=n[o];if(!h){if(s)throw new p(`the ID token has no \`${o}\`, so the ${o==="at_hash"?"access token":"authorization code"} it arrived with cannot be tied to it.`,{claim:o});continue}if(h!==await Be(a,i))throw new p(`the ID token \`${o}\` does not cover the value it arrived with; it may have been substituted.`,{claim:o})}return n}async function ie(n,e,t={}){let r=J(n),{jwk:s,key:i}=await e.getSigningKey(r.header.kid,r.header.alg);return await _e(r,s,{algorithms:t.algorithms,key:i}),Ae(r.payload,t),(t.accessToken||t.code)&&await Te(r.payload,{alg:r.header.alg,accessToken:t.accessToken,code:t.code,require:t.requireTokenHashes!==!1}),r.payload}var $t={RS:"RSA",PS:"RSA",ES:"EC"},Ct=64,H=class{#e;#r;#p;#o;#n=null;#y=0;#b=0;#S=null;#c=new Set;#d=new Map;constructor(e,{ttlMs:t=5*6e4,minRefreshIntervalMs:r=1e4,...s}={}){this.#e=e,this.#r=t,this.#p=r,this.#o=s}get uri(){return this.#e}async keys({force:e=!1}={}){let t=Date.now()-this.#y>this.#r;return this.#n&&!e&&!t?this.#n:this.#_(e)}async getSigningKey(e,t){let r=this.#s(await this.keys(),e,t);if(r.length===0){let a=e??"\0none";!this.#c.has(a)&&Date.now()-this.#b>=this.#p&&(r=this.#s(await this.keys({force:!0}),e,t)),r.length===0&&(this.#c.size>=Ct&&this.#c.clear(),this.#c.add(a))}if(r.length===0)throw new p(e?`no key with kid '${e}' is published at ${this.#e}; the token may have been signed by a different provider.`:`the token carries no 'kid' and ${this.#e} publishes more than one key, so the signing key is ambiguous.`);let s=r[0],i=`${s.kid??""}|${t}|${s.n??s.x??""}`,o=this.#d.get(i);return o||(o=await Se(s,t),this.#d.set(i,o)),{jwk:s,key:o}}clear(){this.#n=null,this.#y=0,this.#b=0,this.#c.clear(),this.#d.clear()}#s(e,t,r){let s=$t[String(r??"").slice(0,2)],i=e.filter(o=>(!o.use||o.use==="sig")&&(!s||o.kty===s)&&(!o.alg||!r||o.alg===r));return t?i.filter(o=>o.kid===t):i.length===1?i:[]}async#_(e){return e&&(this.#b=Date.now()),this.#S??=(async()=>{try{let t=await L(this.#e,{...this.#o,cache:e?"no-cache":"default"}),r=Array.isArray(t.keys)?t.keys:[];if(r.length===0)throw new p(`${this.#e} published no keys.`);return this.#n=r,this.#y=Date.now(),this.#c.clear(),r}finally{this.#S=null}})(),this.#S}};var I=class n{constructor(e={},{issuedAt:t=Math.floor(Date.now()/1e3),claims:r=null}={}){this.accessToken=e.access_token??null,this.tokenType=e.token_type??"Bearer",this.refreshToken=e.refresh_token??null,this.idToken=e.id_token??null,this.scope=e.scope??null,this.issuedAt=t,this.expiresAt=typeof e.expires_in=="number"?t+e.expires_in:e.expires_at??null,this.claims=r}expiresIn(e=Math.floor(Date.now()/1e3)){return this.expiresAt===null?null:this.expiresAt-e}expired(e=0,t=Math.floor(Date.now()/1e3)){return this.expiresAt===null?!1:t>=this.expiresAt-e}scopes(){return this.scope?this.scope.split(" ").filter(Boolean):[]}hasScope(...e){let t=new Set(this.scopes());return e.flat().every(r=>t.has(r))}arkClaims(){let e=this.accessTokenClaims()?.ark_claims;return Array.isArray(e)?e.map(String):typeof e=="string"?[e]:[]}accessTokenClaims(){if(!this.accessToken)return null;try{return J(this.accessToken).payload}catch{return null}}get subject(){return this.claims?.sub??this.accessTokenClaims()?.sub??null}authorizationHeader(){return`${this.tokenType} ${this.accessToken}`}toJSON(){return{access_token:this.accessToken,token_type:this.tokenType,refresh_token:this.refreshToken,id_token:this.idToken,scope:this.scope,expires_at:this.expiresAt,issued_at:this.issuedAt,claims:this.claims}}static fromJSON(e){return e?e instanceof n?e:new n(e,{issuedAt:e.issued_at??Math.floor(Date.now()/1e3),claims:e.claims??null}):null}};function xe(){return q(32)}async function ve(n){return U(await ne(n))}function W(){return q(24)}function oe(){return q(24)}async function ae(){let n=xe();return{codeVerifier:n,codeChallenge:await ve(n),codeChallengeMethod:"S256"}}var K=Object.freeze({status:"loading",isLoading:!0,isAuthenticated:!1,user:null,arkClaims:Object.freeze([]),scopes:Object.freeze([]),expiresAt:null,error:null,denial:null}),ce=class{#e=K;#r=new Set;get(){return this.#e}set(e){let t={...this.#e,...e};if(t.isLoading=t.status==="loading",t.isAuthenticated=t.status==="authenticated",Object.keys(t).every(r=>Object.is(t[r],this.#e[r])))return this.#e;this.#e=Object.freeze(t);for(let r of[...this.#r])try{r(this.#e)}catch(s){queueMicrotask(()=>{throw s})}return this.#e}subscribe(e){return this.#r.add(e),()=>this.#r.delete(e)}};var j=class{#e=new Map;getItem(e){return this.#e.has(e)?this.#e.get(e):null}setItem(e,t){this.#e.set(e,String(t))}removeItem(e){this.#e.delete(e)}key(e){return[...this.#e.keys()][e]??null}get length(){return this.#e.size}clear(){this.#e.clear()}};function Et(n){return n&&typeof n.getItem=="function"&&typeof n.setItem=="function"&&typeof n.removeItem=="function"}function Rt(n){try{let e="__ark_probe__";return n.setItem(e,"1"),n.removeItem(e),n}catch{return null}}function he(n,e){if(Et(n))return{storage:n,kind:"custom"};if(n==="memory"||!e)return{storage:new j,kind:"memory"};if(n==="session"||n==="local"){let t=null;try{t=n==="session"?e.sessionStorage:e.localStorage}catch{t=null}let r=t?Rt(t):null;return r?{storage:r,kind:n}:{storage:new j,kind:"memory"}}throw new f(`ark_oauth_client: 'storage' must be 'session', 'local', 'memory' or a Storage-like object, not '${n}'.`)}function O(n,e){try{let t=n.getItem(e);return t?JSON.parse(t):null}catch{return null}}function N(n,e,t){try{return n.setItem(e,JSON.stringify(t)),!0}catch{return!1}}function z(n,e){try{n.removeItem(e)}catch{}}function Ke(n,e){let t=[];try{let r=n.length??0;for(let s=0;s<r;s++){let i=n.key(s);i&&i.startsWith(e)&&t.push(i)}}catch{}return t}async function Ve(n,e,t){let r=t?.navigator?.locks??globalThis.navigator?.locks;return r&&typeof r.request=="function"?r.request(n,{mode:"exclusive"},()=>e()):e()}var Ge="ark-oidc:callback";function $e(n,e){return`ark-oidc:${n}|${e}:popup`}function Ye(n,{width:e=520,height:t=680}={}){let r=n.screenX??n.screenLeft??0,s=n.screenY??n.screenTop??0,i=n.outerWidth??e,o=n.outerHeight??t,a=Math.max(0,Math.round(r+(i-e)/2)),h=Math.max(0,Math.round(s+(o-t)/2)),d=`popup=yes,width=${e},height=${t},left=${a},top=${h},resizable=yes,scrollbars=yes`,u=null;try{u=n.open("","ark-oidc-popup",d)}catch{u=null}if(!u)throw new E("blocked","the browser blocked the sign-in popup. Call signinPopup() directly from a click handler, before any await, or use signinRedirect().");return u}function Xe(n,e,{state:t,channelName:r,timeoutMs:s}){let i;return{promise:new Promise((a,h)=>{let d=!1,u=null,c=null,l=null,k=null,g=()=>{d=!0,n.removeEventListener("message",S),u&&(u.onmessage=null,u.close()),clearInterval(c),clearTimeout(l),clearTimeout(k)},_=m=>{d||!m||m.type!==Ge||m.state!==t||typeof m.url!="string"||(g(),a(m.url))},S=m=>{m.origin===n.location.origin&&_(m.data)};n.addEventListener("message",S);let b=n.BroadcastChannel??globalThis.BroadcastChannel;typeof b=="function"&&(u=new b(r),u.onmessage=m=>_(m.data)),c=setInterval(()=>{let m=!1;try{m=e.closed}catch{m=!1}m&&!d&&!l&&(l=setTimeout(()=>{d||(g(),h(new E("closed","the sign-in popup was closed before the sign-in finished.")))},400))},250),k=setTimeout(()=>{if(!d){g();try{e.close()}catch{}h(new E("timeout",`the sign-in popup did not finish within ${Math.round(s/1e3)}s.`))}},s),i=m=>{d||(g(),h(m))}}),cancel:a=>i(a??new E("closed","the sign-in popup was cancelled."))}}function Qe(n,e,t,r){let s=!1,i={type:Ge,url:e,state:t};try{let a=n.opener;a&&a!==n&&(a.postMessage(i,n.location.origin),s=!0)}catch{}let o=n.BroadcastChannel??globalThis.BroadcastChannel;if(typeof o=="function")try{let a=new o(r);a.postMessage(i),a.close(),s=s||!!n.opener||n.name==="ark-oidc-popup"}catch{}return s}var le=["code","state","iss","error","error_description","error_uri","session_state"],Ot=300,Pt=15e3,Ut=50,It=2147483647,Ze=["signedIn","signedOut","tokensRefreshed","refreshFailed","sessionExpired","accessDenied","error"],M=()=>Math.floor(Date.now()/1e3),Mt=0;function Ce(n){return n&&typeof n.unref=="function"&&n.unref(),n}var V=class{#e;#r;#p;#o=null;#n=new ce;#y=new Map(Ze.map(e=>[e,new Set]));#b=`ark-${++Mt}-${Math.random().toString(36).slice(2,8)}`;#S=!1;#c=null;#d="memory";#s=null;#_=null;#i;#t=null;#$={claims:null,arkClaims:Object.freeze([]),scopes:Object.freeze([])};#m=null;#C=null;#O=null;#f=null;#k=null;#P=[];#T=!1;constructor(e={}){this.#e=te(e),this.#r=e.window!==void 0?e.window:typeof window<"u"?window:null,this.#i=`ark.oidc:${this.#e.clientId}@${this.#e.authority}:`,this.#p=new D(this.#e.authority,{ttlMs:this.#e.metadataTtlMs,timeoutMs:this.#e.timeoutMs,fetch:this.#e.fetch}),this.subscribe=this.subscribe.bind(this),this.getSnapshot=this.getSnapshot.bind(this),this.getServerSnapshot=this.getServerSnapshot.bind(this),this.fetch=this.fetch.bind(this),this.getAccessToken=this.getAccessToken.bind(this)}get config(){return this.#e}get authority(){return this.#e.authority}get clientId(){return this.#e.clientId}get isBrowser(){return!!this.#r}getSnapshot(){return this.#n.get()}getServerSnapshot(){return K}subscribe(e){return this.#n.subscribe(e)}get state(){return{subscribe:e=>(e(this.#n.get()),this.#n.subscribe(e))}}getUser(){return this.#n.get().user}on(e,t){let r=this.#y.get(e);if(!r)throw new f(`ark_oauth_client: unknown event '${e}'. Known events: ${Ze.join(", ")}.`);return r.add(t),()=>r.delete(t)}hasArkClaims(...e){let t=this.#n.get().arkClaims;return e.flat().every(r=>t.includes(r))}hasAnyArkClaim(...e){let t=this.#n.get().arkClaims;return e.flat().some(r=>t.includes(r))}hasScopes(...e){let t=this.#n.get().scopes;return e.flat().every(r=>t.includes(r))}init(e={}){return this.#r?(this.#C??=this.#Q(e),this.#C):Promise.resolve(this.#n.get())}async#Q({handleCallback:e=!0,onRedirectCallback:t}={}){this.#h(),this.#he(),this.#ce();let r=this.#r.location.href,s=(i,o)=>{let a=t??this.#e.onRedirectCallback;if(!a)return this.#Y(i);try{Promise.resolve(a(i,o)).catch(h=>this.#a("error",h))}catch(h){this.#a("error",h)}};try{let i=e?this.#H(r):null;if(i==="signin"){let o;try{o=await this.handleRedirectCallback(r)}catch(a){return this.#I(),await this.#M(),this.#W(a)}return o.relayed?this.#n.get():(s(o.returnTo,o),this.#n.get())}if(i==="signout"){let o=this.#ae(r);return o?.then==="signin"?(await this.signinRedirect({prompt:o.prompt??this.#e.accountSwitch.prompt,returnTo:o.returnTo,loginHint:o.loginHint}),this.#n.get()):(this.#l({error:null}),s(o?.returnTo??R(this.#e.accountSwitch.homePath),{signedOut:!0}),this.#n.get())}this.#I(),await this.#M(),this.#l(),this.#A()}catch(i){return this.#W(i)}return this.#n.get()}async createAuthorizationUrl(e={}){let t=this.#w(),r=this.#e,s=await this.metadata();if(s.require_pushed_authorization_requests===!0)throw new f("the tenant requires pushed authorization requests, which a browser app cannot make (/oauth2/par needs client authentication and serves no CORS). Turn RequirePushedAuthorizationRequests off for this tenant, or the client's require_par flag, or sign in through a server-side client.");if(!s.authorization_endpoint)throw new w("server_error","the provider's metadata has no 'authorization_endpoint'.",{endpoint:r.authority});let i=this.#v(e.redirectUri??r.redirectUri),o=e.scopes?.length?[...e.scopes]:[...r.scopes],{codeVerifier:a,codeChallenge:h,codeChallengeMethod:d}=await ae(),u=W(),c=o.includes("openid")?oe():null,l=e.prompt??r.prompt,k=e.acrValues??r.acrValues,g=e.responseMode??r.responseMode,_={...r.extraAuthorizationParams,...e.extra,response_type:"code",client_id:r.clientId,redirect_uri:i,scope:o.join(" "),state:u,code_challenge:h,code_challenge_method:d,response_mode:g,...c?{nonce:c}:{},...l?{prompt:l}:{},...e.loginHint?{login_hint:e.loginHint}:{},...e.maxAge!==void 0&&e.maxAge!==null?{max_age:String(e.maxAge)}:{},...k?{acr_values:k}:{}},S=new URLSearchParams(Object.entries(_).filter(([,C])=>C!=null&&C!=="")),b=`${t.location.pathname}${t.location.search}${t.location.hash}`,m=R(e.returnTo??(this.#H(t.location.href)?"/":b),"/");return{url:`${s.authorization_endpoint}${s.authorization_endpoint.includes("?")?"&":"?"}${S}`,transaction:{state:u,nonce:c,codeVerifier:a,redirectUri:i,responseMode:g,scope:o.join(" "),maxAge:e.maxAge??null,returnTo:m,createdAt:M()}}}async signinRedirect(e={}){this.#h();let{url:t,transaction:r}=await this.createAuthorizationUrl(e);this.#ie(r),await this.#G(t)}async signinPopup(e={}){let t=this.#w(),r=e.popupWindow??Ye(t,this.#e.popup),s=null;try{this.#h();let{url:i,transaction:o}=await this.createAuthorizationUrl(e);s=Xe(t,r,{state:o.state,channelName:$e(this.#e.authority,this.#e.clientId),timeoutMs:this.#e.popup.timeoutMs}),r.location.href=i;let a=await s.promise,h=this.#R(new URL(a),o.responseMode);if(h.error)throw this.#V(h);return await this.#N(h,o)}catch(i){throw s?.cancel(i),this.#l({error:i instanceof y?i:new y(String(i?.message??i))}),this.#a("error",i),i}finally{try{r.closed||r.close()}catch{}}}isSigninCallback(e){return this.#H(String(e??this.#w().location.href))==="signin"}async handleRedirectCallback(e){let t=this.#w();this.#h();let r=String(e??t.location.href),s=new URL(r,t.location.href),i=this.#R(s),o=i.state?this.#oe(i.state):null;if(!o&&i.state&&Qe(t,r,i.state,$e(this.#e.authority,this.#e.clientId)))return setTimeout(()=>{try{t.close()}catch{}},50),{relayed:!0,returnTo:null,user:null,denied:!1};if(this.#K(s),i.error)throw this.#V(i);if(!i.state)throw new T("the authorization response carried no `state`.");if(!o)throw new T("the authorization response does not belong to a sign-in started in this tab (unknown or expired `state`). Start the sign-in again. If this keeps happening, check that the redirect URI is served by this same origin, and that storage is not being cleared between the two pages.");if(!Je(String(i.state),String(o.state)))throw new T("the authorization response `state` does not match the request. Treat this as a CSRF attempt.");return this.#N(i,o)}async#N(e,t){let r=await this.metadata();if(e.iss||r.authorization_response_iss_parameter_supported){if(!e.iss)throw new T("the provider advertises `iss` in authorization responses but this one has none.");if(e.iss!==r.issuer)throw new T(`the authorization response came from '${e.iss}', not from '${r.issuer}'.`)}if(!e.code)throw new T("the authorization response carried no `code`.");let s=await this.#te({code:e.code,codeVerifier:t.codeVerifier,redirectUri:t.redirectUri,nonce:t.nonce??null,maxAge:t.maxAge??null}),i=R(t.returnTo,"/"),o=s.arkClaims();if(!await Pe(this.#e.accountSwitch,this.#e.onEvaluateAccess,{claims:s.claims??{},arkClaims:o,tokens:s})){let h=Ue(Q.NO_APP_ACCESS,s.claims,o,i);return this.#x({...h,idTokenHint:s.idToken,createdAt:M()}),this.#g(null),s.refreshToken&&this.#E(s.refreshToken),this.#l({error:null}),this.#a("accessDenied",this.#n.get().denial),{returnTo:this.#e.accountSwitch.accessDeniedPath??i,user:s.claims,denied:!0}}return this.#x(null),this.#g(s),this.#l({error:null}),this.#A(),this.#a("signedIn",{user:s.claims,returnTo:i}),this.#j("signed-in"),{returnTo:i,user:s.claims,denied:!1}}async getAccessToken({forceRefresh:e=!1}={}){if(!this.#r||(this.#h(),this.#C?await this.#C:this.#I(),!this.#t))return null;if(e||this.#t.expired(this.#D(this.#t))){if(!this.#t.refreshToken)return this.#t.expired(0)?(this.#u("expired",{broadcast:!1}),this.#a("sessionExpired",{reason:"expired"}),null):this.#t.accessToken;try{await this.refresh()}catch(t){if(!this.#t)return null;if(this.#t.expired(0))throw t}}return this.#t?.accessToken??null}refresh(){return this.#O??=this.#Z().finally(()=>{this.#O=null}),this.#O}async#Z(){if(this.#h(),!this.#t?.refreshToken)throw new x("there is no refresh token to renew the session with.");return Ve(`${this.#i}refresh`,async()=>{if(this.#T)throw new y("the client was destroyed.");let e=this.#t;if(!e?.refreshToken)throw new x;if(this.#d!=="memory"){let r=this.#U();if(!r)throw this.#u("signout",{broadcast:!1}),new x;if(r.refreshToken!==e.refreshToken){if(!r.expired(this.#D(r)))return this.#g(r,{persist:!1}),this.#l({error:null}),this.#A(),r;e=r}}if(await this.#re(e.refreshToken))throw this.#u("expired",{broadcast:!1}),this.#a("sessionExpired",{reason:"refresh_token_spent"}),new x("this tab's refresh token was already redeemed by a copy of it (a duplicated tab). Sign in again.");let t;try{let r=await this.metadata(),s=await this.#F(r.token_endpoint,{grant_type:"refresh_token",refresh_token:e.refreshToken});s.refresh_token&&s.refresh_token!==e.refreshToken&&(await this.#ne(e.refreshToken),e=I.fromJSON({...e.toJSON(),refresh_token:s.refresh_token}),this.#g(e)),t=await this.#B(s,{nonce:null,subject:e.claims?.sub??null,previous:e})}catch(r){throw this.#ee(r),r}return this.#g(t),this.#T||(this.#l({error:null}),this.#A(),this.#a("tokensRefreshed",{expiresAt:t.expiresAt}),this.#j("tokens")),t},this.#r)}#ee(e){if(e instanceof p||e instanceof w&&["invalid_grant","invalid_client","unauthorized_client"].includes(e.error)){let r=e instanceof p?this.#t?.refreshToken:null;this.#u("expired",{broadcast:this.#L()}),r&&this.#E(r),this.#a("sessionExpired",{reason:"refresh_refused",error:e});return}this.#a("refreshFailed",{error:e}),this.#e.automaticRefresh&&this.#t&&!this.#T&&(clearTimeout(this.#f),this.#f=Ce(setTimeout(()=>this.refresh().catch(()=>{}),Pt)))}isApiUrl(e){let t=this.#r,r;try{r=new URL(String(e),t?.location?.href)}catch{return!1}let s=t?.location?.origin;return r.origin===s||this.#e.apiOrigins.includes(r.origin)}async fetch(e,t={}){let r=this.#w(),s=typeof e=="string"||e instanceof URL?String(e):e?.url;if(!this.isApiUrl(s)){let u=(()=>{try{return new URL(s,r.location.href).origin}catch{return s}})();throw new f(`ark_oauth_client: refusing to send the access token to ${u}. Add that origin to 'apiOrigins' if it is your API, or call it with plain fetch().`)}let i=this.#e.fetch??globalThis.fetch,o=u=>{let c=new Headers(t.headers??(typeof Request<"u"&&e instanceof Request?e.headers:void 0));return c.set("Authorization",`Bearer ${u}`),i(e,{...t,headers:c})},a=await this.getAccessToken();if(!a)throw new x;let h=await o(a),d=!(typeof Request<"u"&&e instanceof Request)&&!(t.body&&typeof t.body.getReader=="function");if(h.status===401&&d&&this.#t?.refreshToken){let u=h.headers.get("WWW-Authenticate")??"";if(!u||/invalid_token/i.test(u)){let c=await this.getAccessToken({forceRefresh:!0}).catch(()=>null);c&&(h=await o(c))}}return h}async userInfo(){let e=await this.getAccessToken();if(!e)throw new x;let t=await this.metadata();return L(t.userinfo_endpoint,{headers:{Authorization:`Bearer ${e}`},timeoutMs:this.#e.timeoutMs,fetch:this.#e.fetch})}async signoutRedirect({returnTo:e,postLogoutRedirectUri:t,revoke:r=!0,...s}={}){this.#w(),this.#h();let i=this.#t?.idToken??this.#m?.idTokenHint??null,o=this.#t?.refreshToken??null,a=null;try{a=await this.metadata()}catch{a=null}this.#u("signout",{broadcast:!0}),r&&o&&a?.revocation_endpoint&&await this.#E(o,a);let h=R(e??this.#e.accountSwitch.homePath,"/");if(!a?.end_session_endpoint){this.#Y(h);return}let d=new URLSearchParams({client_id:this.#e.clientId});i&&d.set("id_token_hint",i);let u=t??this.#e.postLogoutRedirectUri;if(u){let l=W();d.set("post_logout_redirect_uri",this.#v(u)),d.set("state",l),N(this.#s,`${this.#i}logout:${l}`,{returnTo:h,then:s.then??null,prompt:s.prompt??null,loginHint:s.loginHint??null,createdAt:M()})}let c=a.end_session_endpoint;await this.#G(`${c}${c.includes("?")?"&":"?"}${d}`)}async signoutLocal({revoke:e=!0}={}){this.#h();let t=this.#t?.refreshToken??null;this.#u("signout",{broadcast:!0}),e&&t&&await this.#E(t)}async switchUser({returnTo:e,loginHint:t}={}){let r=this.#e.accountSwitch,s=R(e??this.#m?.returnTo??null,r.homePath);if(r.endProviderSessionOnSwitch){await this.signoutRedirect({returnTo:s,then:"signin",prompt:r.prompt,loginHint:t});return}await this.signoutLocal(),await this.signinRedirect({prompt:r.prompt||"login",returnTo:s,loginHint:t})}clearDenial(){this.#h(),this.#x(null),this.#l()}metadata({force:e=!1}={}){return this.#p.get(e)}async jwks(){let{jwks_uri:e}=await this.metadata();if(!e)throw new w("server_error","the provider's metadata has no 'jwks_uri'.",{endpoint:this.#e.authority});return(!this.#o||this.#o.uri!==e)&&(this.#o=new H(e,{ttlMs:this.#e.jwksTtlMs,minRefreshIntervalMs:this.#e.jwksMinRefreshIntervalMs,timeoutMs:this.#e.timeoutMs,fetch:this.#e.fetch})),this.#o}async verifyIdToken(e,{nonce:t=null,accessToken:r=null,code:s=null,maxAge:i=null,subject:o=null}={}){let a=await this.metadata();return ie(e,await this.jwks(),{issuer:a.issuer,audience:this.#e.clientId,subject:o??void 0,nonce:t,accessToken:r,code:s,maxAgeSeconds:i,requireTokenHashes:this.#e.requireTokenHashes,requireIat:!0,clockToleranceSeconds:this.#e.clockToleranceSeconds,algorithms:this.#e.idTokenSigningAlgorithms??a.id_token_signing_alg_values_supported??void 0})}async checkSetup(){let e=this.#r,t=this.#e,r=t.authority.lastIndexOf("/"),s=t.authority.slice(r+1),i={authority:t.authority,clientId:t.clientId,tenantId:s,origin:e?.location?.origin??null,secureContext:!!(e?.isSecureContext??globalThis.isSecureContext),webCrypto:!!globalThis.crypto?.subtle,storage:(this.#h(),this.#d),scopes:[...t.scopes],responseMode:t.responseMode,redirectUri:e?this.#v(t.redirectUri):t.redirectUri,postLogoutRedirectUri:t.postLogoutRedirectUri&&e?this.#v(t.postLogoutRedirectUri):t.postLogoutRedirectUri,adminConsoleUrl:`${t.authority}/admin`,integrationPageUrl:`${t.authority}/oauth2/integrate/${encodeURIComponent(t.clientId)}`,discoveryUrl:`${t.authority}/.well-known/openid-configuration`,discoveryOk:!1,jwksOk:!1,tokenEndpointCorsOk:null,provider:null,signingKeys:[],problems:[]};(!i.secureContext||!i.webCrypto)&&i.problems.push("This page is not a secure context, so crypto.subtle is unavailable. Serve it over https, or over http on localhost only.");let o;try{o=await this.metadata({force:!0}),i.discoveryOk=!0}catch(c){return i.problems.push(`The provider's discovery document could not be read: ${c.message}`),i}i.provider={issuer:o.issuer,authorizationEndpoint:o.authorization_endpoint,tokenEndpoint:o.token_endpoint,userInfoEndpoint:o.userinfo_endpoint,jwksUri:o.jwks_uri,endSessionEndpoint:o.end_session_endpoint??null,revocationEndpoint:o.revocation_endpoint??null,scopesSupported:o.scopes_supported??[],grantTypesSupported:o.grant_types_supported??[],responseModesSupported:o.response_modes_supported??[],codeChallengeMethodsSupported:o.code_challenge_methods_supported??[],tokenEndpointAuthMethodsSupported:o.token_endpoint_auth_methods_supported??[],requirePushedAuthorizationRequests:o.require_pushed_authorization_requests===!0};try{let c=await(await this.jwks()).keys({force:!0});i.jwksOk=!0,i.signingKeys=c.map(l=>({kid:l.kid??null,kty:l.kty,alg:l.alg??null,use:l.use??null}))}catch(c){i.problems.push(`The provider's signing keys could not be read: ${c.message}`)}try{await ge(o.token_endpoint,{grant_type:"refresh_token",refresh_token:"ark-setup-probe",client_id:t.clientId},{timeoutMs:t.timeoutMs,fetch:t.fetch}),i.tokenEndpointCorsOk=!0}catch(c){i.tokenEndpointCorsOk=!(c instanceof $),i.tokenEndpointCorsOk?c instanceof w&&["invalid_client","unauthorized_client"].includes(c.error)&&i.problems.push(`The token endpoint refused client '${t.clientId}' (${c.error}${c.errorDescription?`: ${c.errorDescription}`:""}). Check the client id, that the client is active, and that it is registered as a public client ('none') for authorization_code and refresh_token.`):i.problems.push(`The token endpoint is not reachable from this page: ${c.message}`)}let a=new Set(o.scopes_supported??[]),h=a.size?t.scopes.filter(c=>!a.has(c)):[];h.length&&i.problems.push(`The tenant does not publish the scope(s) ${h.join(", ")}. A scope the client is not registered for is rejected outright, not dropped.`),(o.code_challenge_methods_supported??[]).includes("S256")||i.problems.push("The tenant does not advertise the S256 PKCE method, which this client always sends.");let d=o.token_endpoint_auth_methods_supported??[];d.length&&!d.includes("none")&&i.problems.push("The tenant does not list the 'none' token endpoint auth method, which a browser (public) client needs.");let u=o.response_modes_supported??[];return u.length&&!u.includes(t.responseMode)&&i.problems.push(`The tenant does not support response_mode '${t.responseMode}' (it lists ${u.join(", ")}).`),t.scopes.includes("offline_access")&&!(o.grant_types_supported??["refresh_token"]).includes("refresh_token")&&i.problems.push("offline_access is requested but the tenant does not serve the refresh_token grant."),t.scopes.includes("offline_access")||i.problems.push("offline_access is not requested, so there is no refresh token: the session ends when the access token expires."),o.require_pushed_authorization_requests===!0&&i.problems.push("The tenant requires pushed authorization requests, which a browser app cannot make."),o.end_session_endpoint||i.problems.push("The provider has no end_session_endpoint, so sign-out can only end the local session."),i}destroy(){this.#T=!0,clearTimeout(this.#f),this.#f=null;for(let e of this.#P.splice(0))e();this.#k&&(this.#k.onmessage=null,this.#k.close(),this.#k=null)}async#te({code:e,codeVerifier:t,redirectUri:r,nonce:s,maxAge:i}){let o=await this.metadata(),a=await this.#F(o.token_endpoint,{grant_type:"authorization_code",code:e,redirect_uri:r,code_verifier:t});return this.#B(a,{nonce:s,code:e,maxAge:i})}#F(e,t){if(!e)throw new w("server_error","the provider's metadata has no 'token_endpoint'.",{endpoint:this.#e.authority});return ge(e,{...t,client_id:this.#e.clientId},{timeoutMs:this.#e.timeoutMs,fetch:this.#e.fetch})}async#B(e,{nonce:t,code:r=null,maxAge:s=null,subject:i=null,previous:o=null}){if(!e.access_token)throw new p("the token response contains no access_token.");let a=null;if(e.id_token)a=await this.verifyIdToken(e.id_token,{nonce:t,accessToken:e.access_token,code:r,maxAge:s,subject:i});else if(t!==null&&String(e.scope??"").split(" ").includes("openid"))throw new p("the token response contains no id_token, although the openid scope was granted.");let h={...e};return o&&(h.refresh_token??=o.refreshToken,h.id_token??=o.idToken),new I(h,{claims:a??o?.claims??null})}#g(e,{persist:t=!0}={}){this.#t=e,this.#$=e?{claims:e.claims?Object.freeze({...e.claims}):null,arkClaims:Object.freeze(e.arkClaims()),scopes:Object.freeze(e.scopes())}:{claims:null,arkClaims:Object.freeze([]),scopes:Object.freeze([])},t&&(e?N(this.#c,`${this.#i}tokens`,e.toJSON()):z(this.#c,`${this.#i}tokens`))}#U(){let e=O(this.#c,`${this.#i}tokens`);return e?.access_token?I.fromJSON(e):null}#I(){if(!this.#t){let e=this.#U();e&&this.#g(e,{persist:!1})}if(!this.#m){let e=O(this.#s,`${this.#i}denied`);e&&M()-(e.createdAt??0)<=Ot?this.#m=e:e&&z(this.#s,`${this.#i}denied`)}}async#M(){if(!(!this.#t||!this.#t.expired(this.#D(this.#t)))){if(!this.#t.refreshToken){this.#t.expired(0)&&this.#u("expired",{broadcast:!1});return}try{await this.refresh()}catch{}}}#u(e,{broadcast:t}){let r=!!(this.#t||this.#m);clearTimeout(this.#f),this.#f=null,this.#g(null),this.#x(null),this.#l(),r&&this.#a("signedOut",{reason:e}),t&&this.#j("signed-out")}async#E(e,t=null){try{let r=t??await this.metadata();if(!r.revocation_endpoint)return;await He(r.revocation_endpoint,{token:e,token_type_hint:"refresh_token",client_id:this.#e.clientId},{timeoutMs:Math.min(this.#e.timeoutMs,5e3),fetch:this.#e.fetch})}catch{}}#A(){clearTimeout(this.#f),this.#f=null;let e=this.#t;if(this.#T||!e||e.expiresAt===null||!this.#r)return;let t=!!(this.#e.automaticRefresh&&e.refreshToken);if(!t&&e.refreshToken)return;let r=t?e.expiresAt-this.#z(e):e.expiresAt,s=Math.min(It,Math.max(0,(r-M())*1e3));this.#f=Ce(setTimeout(()=>{t?this.refresh().catch(()=>{}):this.#t===e&&(this.#u("expired",{broadcast:!1}),this.#a("sessionExpired",{reason:"expired"}))},s))}#L(){return this.#d==="local"||this.#d==="custom"}#z(e,t=this.#e.refreshBeforeSeconds){if(!e||e.expiresAt===null)return t;let r=e.expiresAt-e.issuedAt;return r>0?Math.min(t,r/2):t}#D(e){return this.#z(e,Math.min(30,this.#e.refreshBeforeSeconds))}async#J(e){return U(await ne(`${this.#e.clientId}|${e}`)).slice(0,24)}async#re(e){let t=await this.#J(e);return(O(this.#_,`${this.#i}spent`)??[]).some(r=>r?.h===t)}async#ne(e){let t=await this.#J(e),r=(O(this.#_,`${this.#i}spent`)??[]).filter(s=>s&&s.h!==t);r.push({h:t,at:M()}),N(this.#_,`${this.#i}spent`,r.slice(-Ut))}#h(){if(this.#S)return;this.#S=!0;let{storage:e,kind:t}=he(this.#e.storage,this.#r);this.#c=e,this.#d=t,this.#s=t==="session"?e:he("session",this.#r).storage,this.#_=t==="local"?e:he("local",this.#r).storage}#l(e={}){let t=this.#t,r=this.#m;this.#n.set({status:t?"authenticated":r?"denied":"unauthenticated",user:this.#$.claims,arkClaims:this.#$.arkClaims,scopes:this.#$.scopes,expiresAt:t?.expiresAt??null,denial:r?this.#se(r):null,...e})}#se(e){if(this.#q?.source===e)return this.#q.value;let{idTokenHint:t,createdAt:r,...s}=e,i=Object.freeze({...s,arkClaims:Object.freeze([...s.arkClaims??[]])});return this.#q={source:e,value:i},i}#q=null;#x(e){this.#m=e,e?N(this.#s,`${this.#i}denied`,e):z(this.#s,`${this.#i}denied`)}#W(e){let t=e instanceof y?e:new y(String(e?.message??e),{cause:e});return this.#l({error:t}),this.#A(),this.#a("error",t),this.#n.get()}#ie(e){N(this.#s,`${this.#i}tx:${e.state}`,e)}#oe(e){let t=`${this.#i}tx:${e}`,r=O(this.#s,t);return z(this.#s,t),!r||M()-(r.createdAt??0)>this.#e.transactionTtlSeconds?null:r}#ae(e){let t=this.#R(new URL(e)).state;if(!t)return null;let r=`${this.#i}logout:${t}`,s=O(this.#s,r);return z(this.#s,r),this.#K(new URL(e)),s}#ce(){let e=this.#e.transactionTtlSeconds;for(let t of Ke(this.#s,this.#i)){if(!t.includes(":tx:")&&!t.includes(":logout:"))continue;let r=O(this.#s,t);(!r||M()-(r.createdAt??0)>e)&&z(this.#s,t)}}#w(){if(!this.#r)throw new f("ark_oauth_client: this needs a browser window. On the server (SSR), create the client but call its methods from the browser only, e.g. in an effect.");return this.#r}#v(e){return!e||/^https?:\/\//i.test(e)?e:new URL(e,this.#w().location.origin).toString()}#R(e,t=this.#e.responseMode){let r=e.searchParams,s=new URLSearchParams(e.hash.startsWith("#")?e.hash.slice(1):e.hash),i=t==="fragment"?[s,r]:[r,s],o=i.find(h=>h.has("state")||h.has("code")||h.has("error"))??i[0],a={};for(let h of le){let d=o.get(h);d!==null&&(a[h]=d)}return a}#H(e){if(!this.#r)return null;let t;try{t=new URL(e,this.#r.location.href)}catch{return null}let r=i=>{if(!i)return!1;let o=new URL(this.#v(i));return o.origin===t.origin&&o.pathname===t.pathname},s=this.#R(t);return r(this.#e.redirectUri)&&(s.code||s.error)?"signin":r(this.#e.postLogoutRedirectUri??F)&&s.state&&(this.#h(),O(this.#s,`${this.#i}logout:${s.state}`))?"signout":null}#K(e){let t=this.#r;if(!t?.history?.replaceState)return;let r=new URL(e.toString());for(let i of le)r.searchParams.delete(i);if(r.hash){let i=new URLSearchParams(r.hash.slice(1));if(le.some(o=>i.has(o))){for(let a of le)i.delete(a);let o=i.toString();r.hash=o?`#${o}`:""}}let s=`${r.pathname}${r.search}${r.hash}`;try{t.history.replaceState(t.history.state,"",s)}catch{}}#V(e){return new w(e.error,e.error_description,{endpoint:`${this.#e.authority}/oauth2/authorize`,errorUri:e.error_uri??null,body:e})}async#G(e){if(this.#e.redirect)return this.#e.redirect(e);this.#w().location.assign(e)}#Y(e){if(this.#e.navigate)return this.#e.navigate(e);let t=this.#r;if(t)try{t.history.replaceState(null,"",e);let r=t.PopStateEvent??globalThis.PopStateEvent;typeof r=="function"&&t.dispatchEvent(new r("popstate",{state:null}))}catch{t.location.replace(e)}}#a(e,t){for(let r of[...this.#y.get(e)??[]])try{r(t)}catch(s){queueMicrotask(()=>{throw s})}}#j(e){try{this.#k?.postMessage({type:e,from:this.#b})}catch{}}#he(){let e=this.#r;if(!e||this.#P.length)return;if(this.#e.syncTabs){let r=e.BroadcastChannel??globalThis.BroadcastChannel;typeof r=="function"&&(this.#k=Ce(new r(`ark-oidc:${this.#e.authority}|${this.#e.clientId}`)),this.#k.onmessage=s=>this.#le(s.data))}let t=e.document;if(t?.addEventListener){let r=()=>{t.visibilityState!=="visible"||!this.#t||(this.#L()&&this.#X(),this.#t?.expired(this.#z(this.#t))&&this.#M())};t.addEventListener("visibilitychange",r),this.#P.push(()=>t.removeEventListener("visibilitychange",r))}}#le(e){if(!(!e||e.from===this.#b)){if(e.type==="signed-out"){(this.#t||this.#m)&&this.#u("signout",{broadcast:!1});return}(e.type==="tokens"||e.type==="signed-in")&&this.#L()&&this.#X()}}#X(){let e=this.#U();if(!e){this.#t&&this.#u("signout",{broadcast:!1});return}e.accessToken!==this.#t?.accessToken&&(this.#g(e,{persist:!1}),this.#x(null),this.#l({error:null}),this.#A())}};function et(n){return new V(n)}var Lt={light:{bg:"#f7f7f8",surface:"#ffffff",border:"#e2e2e6",fg:"#17171a",muted:"#6a6a73",accent:"#4f46e5",accentFg:"#ffffff"},dark:{bg:"#111114",surface:"#1a1a1f",border:"#313139",fg:"#ececf1",muted:"#9a9aa5",accent:"#8b85ff",accentFg:"#16161c"}};function A(n,e,t,r){let s=n.createElement(e);return t&&(s.className=t),r!==void 0&&(s.textContent=r),s}function v(n,e){for(let[t,r]of Object.entries(e))n.style.setProperty(t,r)}function tt(n,e,t={}){let r=n.ownerDocument??globalThis.document,s=e.config.accountSwitch,i=e.getSnapshot().denial,o=(t.appName??s.appDisplayName??"").trim()||e.clientId||"this application",a=s.showSignedInAccount?i?.email??i?.name??i?.subject??null:null,h=!!r.defaultView?.matchMedia?.("(prefers-color-scheme: dark)").matches,d=Lt[h?"dark":"light"],u=!t.unstyled,c=A(r,"main","ark-denied");c.setAttribute("role","alert");let l=A(r,"div","ark-denied__card");c.append(l),l.append(A(r,"h1","ark-denied__title",`You do not have access to ${o}`));let k=A(r,"p","ark-denied__lede");a?k.append("You are signed in as ",A(r,"strong",null,a),`, and that account does not have access to ${o}.`):k.textContent=`The account you are signed in with does not have access to ${o}.`,l.append(k),l.append(A(r,"p","ark-denied__hint",`If somebody else was using this browser, their sign-in is still active and it is the one being offered to ${o}. Choose \u201CSign in as a different user\u201D to enter your own credentials.`));let g=A(r,"div","ark-denied__actions"),_=A(r,"button","ark-denied__switch","Sign in as a different user");_.type="button",_.addEventListener("click",()=>e.switchUser({returnTo:i?.returnTo??void 0})),g.append(_);let S=null;s.allowFullSignOut&&(S=A(r,"button","ark-denied__signout","Sign out completely"),S.type="button",S.addEventListener("click",()=>e.signoutRedirect({returnTo:s.homePath})),g.append(S)),l.append(g);let b=null;if(s.supportUrl||s.supportEmail){b=A(r,"p","ark-denied__foot",`Need access to ${o}? `);let C=A(r,"a",null,s.supportUrl?"Request it here":s.supportEmail);C.href=s.supportUrl?s.supportUrl:`mailto:${s.supportEmail}`,b.append(C),l.append(b)}let m=A(r,"p","ark-denied__version",`ark-oauth-client-js ${Y}`);if(l.append(m),u){v(c,{"min-height":"100vh",display:"flex","align-items":"center","justify-content":"center",padding:"24px","box-sizing":"border-box",background:d.bg,color:d.fg,font:'15px/1.55 ui-sans-serif, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif'}),v(l,{width:"100%","max-width":"480px",background:d.surface,border:`1px solid ${d.border}`,"border-radius":"12px",padding:"28px","box-sizing":"border-box"});for(let ue of l.querySelectorAll("p"))v(ue,{margin:"0 0 14px",color:d.muted});v(k,{color:d.fg}),v(l.querySelector("h1"),{margin:"0 0 10px","font-size":"19px","font-weight":"640"}),v(g,{display:"flex","flex-direction":"column",gap:"10px","margin-top":"20px"});let G={width:"100%",padding:"11px 14px","border-radius":"8px",font:"inherit","font-weight":"560",cursor:"pointer"};v(_,{...G,border:`1px solid ${d.accent}`,background:d.accent,color:d.accentFg}),S&&v(S,{...G,border:`1px solid ${d.border}`,background:"transparent",color:d.fg}),b&&(v(b,{"margin-top":"18px","padding-top":"14px","border-top":`1px solid ${d.border}`,"font-size":"13px"}),v(b.querySelector("a"),{color:d.accent})),v(m,{margin:"18px 0 0","padding-top":"14px","border-top":b?"0":`1px solid ${d.border}`,"font-size":"12px","text-align":"center"})}return n.replaceChildren(c),()=>c.remove()}return bt(zt);})();
3
3
  //# sourceMappingURL=ark-oauth-client.global.min.js.map