@muze-nl/metro-oidc 0.9.1 → 0.9.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser.js +364 -114
- package/dist/browser.js.map +3 -3
- package/dist/browser.min.js +3 -3
- package/dist/browser.min.js.map +3 -3
- package/docs/reference.md +23 -5
- package/package.json +1 -1
- package/src/oidc.discovery.mjs +88 -5
- package/src/oidc.mockserver.mjs +7 -2
- package/src/oidcmw.mjs +204 -39
package/dist/browser.min.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
(()=>{var Zt=Object.defineProperty;var ft=(e,t)=>{for(var r in t)Zt(e,r,{get:t[r],enumerable:!0})};var D={};ft(D,{Client:()=>de,client:()=>C,deepClone:()=>pe,metroError:()=>m,request:()=>J,response:()=>z,url:()=>b});var q="https://metro.muze.nl/details/";Symbol.metroProxy||(Symbol.metroProxy=Symbol("isProxy"));Symbol.metroSource||(Symbol.metroSource=Symbol("source"));var de=class e{clientOptions={url:b(typeof window<"u"?window.location:"https://localhost"),verbs:["get","post","put","delete","patch","head","options","query"]};static tracers={};constructor(...t){for(let r of t)if(typeof r=="string"||r instanceof String)this.clientOptions.url=b(this.clientOptions.url.href,r);else if(r instanceof e)Object.assign(this.clientOptions,r.clientOptions);else if(r instanceof Function)this.#e([r]);else if(r&&typeof r=="object")for(let n in r)n=="middlewares"?this.#e(r[n]):n=="url"?this.clientOptions.url=b(this.clientOptions.url.href,r[n]):typeof r[n]=="function"?this.clientOptions[n]=r[n](this.clientOptions[n],this.clientOptions):this.clientOptions[n]=r[n];for(let r of this.clientOptions.verbs)this[r]=async function(...n){return this.fetch(J(this.clientOptions,...n,{method:r.toUpperCase()}),tr(...n))}}#e(t){typeof t=="function"&&(t=[t]);let r=t.findIndex(n=>typeof n!="function");if(r>=0)throw m("metro.client: middlewares must be a function or an array of functions "+q+"client/invalid-middlewares/",t[r]);Array.isArray(this.clientOptions.middlewares)||(this.clientOptions.middlewares=[]),this.clientOptions.middlewares=this.clientOptions.middlewares.concat(t)}fetch(t,r){if(t=J(t,r),!t.url)throw m("metro.client."+t.method.toLowerCase()+": Missing url parameter "+q+"client/fetch-missing-url/",t);if(r||(r={}),typeof r!="object"||r instanceof String)throw m("metro.client.fetch: Invalid options parameter "+q+"client/fetch-invalid-options/",r);let o=[async function(l){l[Symbol.metroProxy]&&(l=l[Symbol.metroSource]);let p=await fetch(l);return z(p)}].concat(this.clientOptions?.middlewares?.slice()||[]);r=Object.assign({},this.clientOptions,r);let i=rr(t,r),s=ir(this,r,i),a;for(let d of o)a=(function(l,p){return async function(g){let A,R=i.tracers;le(R,"request",g,p,i);try{A=await p(g,l,s)}catch(c){throw le(R,"error",c,g,p,i),c}return le(R,"response",A,p,i),A}})(a,d);return a(t)}with(...t){return new e(pe(this.clientOptions),...t)}get location(){return this.clientOptions.url}},Qt=0,er=["trace","tracer","tracers"];function tr(...e){let t={};for(let r of e)if(dt(r))for(let n of er)n in r&&(t[n]=r[n]);return t}function rr(e,t={}){let r=nr(t.trace||t.tracer||t.tracers),n=[];r?n=r.localTracers||[]:n=ue(t.trace).concat(ue(t.tracer)).concat(ue(t.tracers));let o=Object.values(de.tracers||{});return{__metroTraceContext:!0,id:"metro-trace-context-"+ ++Qt,parent:r,request:e,options:t,globalTracers:o,localTracers:n,tracers:o.concat(n)}}function nr(e){return e?e.context?.__metroTraceContext?e.context:e.__metroTraceContext?e:null:null}function ue(e){return!e||e.__metroTraceContext||e.context?.__metroTraceContext?[]:Array.isArray(e)?e.flatMap(ue):or(e)?[e]:dt(e)?Object.values(e).flatMap(ue):[]}function or(e){return e&&typeof e=="object"&&["request","response","error","event","diagnostic","span","link","current"].some(t=>typeof e[t]=="function")}function ir(e,t,r){let n=sr(r);return Object.freeze({client:e,options:t,trace:n,fetch(o,i={}){return e.fetch(o,Object.assign({},i,{trace:n}))}})}function sr(e){let t={__metroTraceContext:!0,context:e,event(r,n={}){le(e.tracers,"event",r,n,e)},diagnostic(r={}){le(e.tracers,"diagnostic",r,e)},current(){for(let r of e.tracers)if(typeof r.current=="function"){let n=r.current(e);if(n)return n}return{traceId:null,spanId:null}},async span(r,n,o={}){let i=e.tracers.find(s=>typeof s.span=="function");return i?i.span(r,n,o,e):n()},link(r){let n=null;for(let o of e.tracers)typeof o.link=="function"&&(n=o.link(r,void 0,e)||n);return n},options(r={}){return Object.assign({},r,{trace:t})}};return t}function le(e,t,...r){for(let n of e)n&&typeof n[t]=="function"&&ar(n,t,r)}function ar(e,t,r){let n=o=>{pt.error("metro: tracer."+t+"() failed",o)};try{let o=e[t].call(e,...r);typeof o?.then=="function"&&o.then(void 0,n)}catch(o){n(o)}}function dt(e){return e&&typeof e=="object"&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null)}function C(...e){return new de(...pe(e))}function cr(e,t){let r=t||{};!r.url&&t.url&&(r.url=t.url);for(let n of["method","headers","body","mode","credentials","cache","redirect","referrer","referrerPolicy","integrity","keepalive","signal","priority","url"]){let o=e[n];if(!(typeof o>"u"||o==null))if(o?.[Symbol.metroProxy]&&(o=o[Symbol.metroSource]),typeof o=="function")r[n]=o(r[n],r);else if(n=="url")r.url=b(r.url,o);else if(n=="headers"){r.headers=new Headers(t.headers),o instanceof Headers||(o=new Headers(e.headers));for(let[i,s]of o.entries())r.headers.set(i,s)}else r[n]=o}return e instanceof Request&&e.data&&(r.body=e.data),r}function J(...e){let t={url:b(typeof window<"u"?window.location:"https://localhost/"),duplex:"half"};for(let o of e)typeof o=="string"||o instanceof URL||o instanceof URLSearchParams?t.url=b(t.url,o):o&&(o instanceof FormData||o instanceof ReadableStream||o instanceof Blob||o instanceof ArrayBuffer||o instanceof DataView)?t.body=o:o&&typeof o=="object"&&Object.assign(t,cr(o,t));let r=new Request(t.url,t),n=t.body;return n&&typeof n=="object"&&!(n instanceof String)&&!(n instanceof ReadableStream)&&!(n instanceof Blob)&&!(n instanceof ArrayBuffer)&&!(n instanceof DataView)&&!(n instanceof FormData)&&!(n instanceof URLSearchParams)&&globalThis.ArrayBuffer&&ArrayBuffer.isView(n)&&typeof n.toString=="function"&&(t.body=n.toString({headers:r.headers}),r=new Request(t.url,t)),Object.freeze(r),new Proxy(r,{get(o,i){let s;switch(i){case Symbol.metroSource:s=o;break;case Symbol.metroProxy:s=!0;break;case"with":s=function(...a){return typeof n<"u"&&a.unshift({body:n}),J(o,...a)};break;case"data":s=n;break;default:o[i]instanceof Function?i==="clone"?s=function(){let a=o.clone();return typeof n<"u"&&!(typeof ReadableStream<"u"&&n instanceof ReadableStream)?J(a,{body:n}):J(a)}:s=o[i].bind(o):s=o[i];break}return s}})}function ut(e,t){let r=t||{};!r.url&&t.url&&(r.url=t.url);for(let n of["status","statusText","headers","body","url","type","redirected"]){let o=e[n];typeof o>"u"||o==null||(o?.[Symbol.metroProxy]&&(o=o[Symbol.metroSource]),typeof o=="function"?r[n]=o(r[n],r):n=="url"?r.url=new URL(o,r.url||"https://localhost/"):r[n]=o)}return e instanceof Response&&e.data&&(r.body=e.data),r}function z(...e){let t={};for(let o of e)typeof o=="string"?t.body=o:o instanceof Response?Object.assign(t,ut(o,t)):o&&typeof o=="object"&&(o instanceof FormData||o instanceof Blob||o instanceof ArrayBuffer||o instanceof DataView||o instanceof ReadableStream||o instanceof URLSearchParams||o instanceof String||typeof globalThis.TypedArray<"u"&&o instanceof globalThis.TypedArray?t.body=o:Object.assign(t,ut(o,t)));let r;t.body&&(r=t.body),[101,204,205,304].includes(t.status)&&(t.body=null);let n=new Response(t.body,t);return Object.freeze(n),new Proxy(n,{get(o,i){let s;switch(i){case Symbol.metroProxy:s=!0;break;case Symbol.metroSource:s=o;break;case"with":s=function(...a){return z(o,...a)};break;case"data":s=r;break;case"ok":s=o.status>=200&&o.status<300;break;default:typeof o[i]=="function"?s=o[i].bind(o):s=o[i];break}return s}})}function lt(e,t){typeof t=="function"?t(e.searchParams,e):(t=new URLSearchParams(t),t.forEach((r,n)=>{e.searchParams.append(n,r)}))}function fr(e,t){let r=e[Symbol.metroSource]||e;t instanceof URLSearchParams||(t=new URLSearchParams(t));let n=r.hash||"#";return n+="?"+t,b(r,{hash:n})}function b(...e){let t=["hash","fragment","host","hostname","href","password","pathname","port","protocol","username","search","searchParams","hashParams"],r=new URL("https://localhost/"),n=null;for(let o of e)if(typeof o=="string"||o instanceof String)r=new URL(o,r);else if(o instanceof URL||typeof Location<"u"&&o instanceof Location)r=new URL(o);else if(o instanceof URLSearchParams)lt(r,o);else if(o&&typeof o=="object")for(let i in o)switch(i){case"search":typeof o.search=="function"?o.search(r.search,r):r.search=new URLSearchParams(o.search);break;case"searchParams":lt(r,o.searchParams);break;default:if(!t.includes(i))throw m("metro.url: unknown url parameter "+q+"url/unknown-param-name/",i);if(i=="fragment"){let s=o.fragment;s&&typeof s=="string"&&s[0]!="#"&&(s="#"+s),o.hash=s,i="hash"}else i=="hashParams"&&(n=o.hashParams);if(typeof o[i]=="function")o[i](r[i],r);else if(typeof o[i]=="string"||o[i]instanceof String||typeof o[i]=="number"||o[i]instanceof Number||typeof o[i]=="boolean"||o[i]instanceof Boolean)r[i]=""+o[i];else if(typeof o[i]=="object"&&o[i].toString)r[i]=o[i].toString();else throw m("metro.url: unsupported value for "+i+" "+q+"url/unsupported-param-value/",e[i]);break}else throw m("metro.url: unsupported option value "+q+"url/unsupported-option-value/",o);return n&&(r.hash||(r.hash="#"),typeof n=="string"?r.hash+=n:r=fr(r,n)),Object.freeze(r),new Proxy(r,{get(o,i){let s;switch(i){case Symbol.metroProxy:s=!0;break;case Symbol.metroSource:s=o;break;case"with":s=function(...a){return b(o,...a)};break;case"filename":s=o.pathname.split("/").pop();break;case"folderpath":s=o.pathname.substring(0,o.pathname.lastIndexOf("/")+1);break;case"authority":s=o.username??"",s+=o.password?":"+o.password:"",s+=s?"@":"",s+=o.hostname,s+=o.port?":"+o.port:"",s+="/",s=o.protocol+"//"+s;break;case"fragment":s=o.hash.substring(1);break;case"scheme":o.protocol?s=o.protocol.substring(0,o.protocol.length-1):s="";break;default:o[i]instanceof Function?s=o[i].bind(o):s=o[i];break}return s}})}var pt={error:(e,...t)=>{console.error("\u24C2\uFE0F ",e,...t)},info:(e,...t)=>{console.info("\u24C2\uFE0F ",e,...t)},group:e=>{console.group("\u24C2\uFE0F "+e)},groupEnd:e=>{console.groupEnd("\u24C2\uFE0F "+e)}};function m(e,...t){return pt.error(e,...t),new Error(e,...t)}function pe(e){if(Array.isArray(e))return e.slice().map(pe);if(e&&typeof e=="object")if(e.__proto__?.constructor==Object||!e.__proto__){let t=Object.assign({},e);return Object.keys(t).forEach(r=>{t[r]=pe(e[r])}),t}else return e;return e}var De={};ft(De,{Optional:()=>f,Recommended:()=>Y,Required:()=>_,allOf:()=>We,anyOf:()=>F,assert:()=>P,disable:()=>lr,enable:()=>ur,error:()=>w,fails:()=>K,formatIssue:()=>yt,formatIssues:()=>_t,instanceOf:()=>G,issues:()=>_r,not:()=>Z,oneOf:()=>k,validEmail:()=>Je,validURL:()=>h,warn:()=>wt});var Ce=!1;function ur(){Ce=!0}function lr(){Ce=!1}function B(e="",t){return(typeof e>"u"||e==null)&&(e=""),typeof t=="number"?`${e}[${t}]`:`${e}.${t}`}function mt(e=""){if(Array.isArray(e))return e;if(!e)return[];let t=[],r=/(?:^|\.)([^.\[\]]+)|\[(\d+)\]/g,n;for(;n=r.exec(e);)typeof n[1]<"u"?t.push(n[1]):typeof n[2]<"u"&&t.push(Number(n[2]));return t}function ve(e=[]){return typeof e=="string"?e.startsWith(".")?e.slice(1):e:e.map((t,r)=>typeof t=="number"?`[${t}]`:`${r?".":""}${t}`).join("")}function Oe(e){return e===String?"string":e===Number?"number":e===Boolean?"boolean":e.name||"function"}function ht(e,t=60){return e.length<=t?e:e.slice(0,t-1)+"\u2026"}function dr(e){return`'${ht(String(e).replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\n/g,"\\n"))}'`}function pr(e){try{let r=JSON.stringify(e);if(typeof r=="string")return ht(r)}catch{}let t=e?.constructor?.name;return t&&t!="Object"?t:Object.prototype.toString.call(e)}function X(e){return typeof e=="string"?dr(e):typeof e>"u"?"undefined":e===null?"null":typeof e=="function"?Oe(e):e instanceof RegExp?e.toString():typeof e=="number"||typeof e=="boolean"||typeof e=="bigint"?String(e):typeof e=="symbol"?e.toString():pr(e)}function V(e){return e===String||e===Number||e===Boolean||typeof e=="function"?Oe(e):e instanceof RegExp?e.toString():Array.isArray(e)?"["+e.map(V).join(", ")+"]":X(e)}function mr(e){return e.map(V).join(", ")}function hr(e,t,r){return e=="data and pattern are not equal"?`expected ${X(r)}, found ${X(t)}`:e=="data does not match pattern"||/^data\[\d+\] does not match pattern$/.test(e)?`expected ${V(r)}, found ${X(t)}`:e=="data is undefined, should match pattern"?`missing; expected ${V(r)}`:e=="data is required"?"required":e=="data is an empty string, which is not allowed"?"empty string is not allowed":e=="data is not an object, pattern is"?"data is not an object":e=="data is not an instanceof pattern"?`expected instance of ${V(r)}, found ${X(t)}`:e=="data does not match oneOf patterns"||e=="data does not match anyOf patterns"?`expected one of ${mr(r)}, found ${X(t)}`:e=="data matches pattern, when required not to"?`must not match ${V(r)}`:e}function yt(e,t={}){if(!e||typeof e!="object")return String(e);let r=e.pathString||ve(e.path||[])||"value";return`${t.indent??""}${r}: ${e.message}`}function _t(e,t={}){if(!e)return!1;let r=t.indent??" - ";return(Array.isArray(e)?e:[e]).map(n=>yt(n,{...t,indent:r}))}function yr(e){if(!e||typeof e!="object")return{path:[],pathString:"",message:String(e),expected:void 0,actual:void 0};let t=mt(e.path),r=ve(t),n=e.actual??e.found,o=V(e.expected),i=hr(e.message,n,e.expected);return{path:t,pathString:r,message:i,expected:o,actual:n}}function Ie(e){if(!e)return[];let t=[];for(let r of Array.isArray(e)?e:[e])if(r){if(r&&typeof r=="object"&&r.problems){let n=Ie(r.problems);if(n.length){t=t.concat(n);continue}}t.push(yr(r))}return t}function P(e,t){if(Ce){let r=K(e,t);if(r){let n=Ie(r),i=`Assertions failed:
|
|
2
|
-
`+
|
|
3
|
-
`);throw console.error("\u{1F170}\uFE0F "+i),new Error(i,{cause:{problems:r,issues:n,source:e}})}}}function f(e){return function(r,n,o){if(typeof r<"u"&&r!=null&&typeof e<"u")return K(r,e,n,o)}}function _(e){return function(r,n,o){return r==null||typeof r>"u"?w("data is required",r,e||"any value",o):typeof e<"u"?K(r,e,n,o):!1}}function Y(e){return function(r,n,o){return r==null||typeof r>"u"?(wt("data does not contain recommended value",r,e,o),!1):K(r,e,n,o)}}function k(...e){return function(r,n,o){for(let i of e)if(!K(r,i,n,o))return!1;return w("data does not match oneOf patterns",r,e,o)}}function F(...e){return function(r,n,o){if(!Array.isArray(r))return w("data is not an array",r,"anyOf",o);for(let[i,s]of r.entries()){let a=B(o,i);if(k(...e)(s,n,a))return w("data does not match anyOf patterns",s,e,a)}return!1}}function We(...e){return function(r,n,o){let i=[];for(let s of e)i=i.concat(K(r,s,n,o));if(i=i.filter(Boolean),i.length)return w("data does not match all given patterns",r,e,o,i)}}function h(e,t,r){try{e instanceof URL&&(e=e.href);let n=new URL(e);if(n.href!=e&&!(n.href+"/"==e||n.href==e+"/"))return w("data is not a valid url",e,"validURL",r)}catch{return w("data is not a valid url",e,"validURL",r)}}function Je(e,t,r){if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e))return w("data is not a valid email",e,"validEmail",r)}function G(e){return function(r,n,o){if(!(r instanceof e))return w("data is not an instanceof pattern",r,e,o)}}function Z(e){return function(r,n,o){if(!K(r,e,n,o))return w("data matches pattern, when required not to",r,e,o)}}function _r(e,t,r){let n=K(e,t,r);return n?Ie(n):!1}function K(e,t,r,n=""){typeof r>"u"&&(r=e);let o=[];if(t===Boolean)typeof e!="boolean"&&!(e instanceof Boolean)&&o.push(w("data is not a boolean",e,t,n));else if(t===Number)typeof e!="number"&&!(e instanceof Number)&&o.push(w("data is not a number",e,t,n));else if(t===String)typeof e!="string"&&!(e instanceof String)&&o.push(w("data is not a string",e,t,n)),e==""&&o.push(w("data is an empty string, which is not allowed",e,t,n));else if(t instanceof RegExp)if(Array.isArray(e)){let i=e.findIndex((s,a)=>K(s,t,r,B(n,a)));i>-1&&o.push(w("data["+i+"] does not match pattern",e[i],t,B(n,i)))}else typeof e>"u"?o.push(w("data is undefined, should match pattern",e,t,n)):t.test(e)||o.push(w("data does not match pattern",e,t,n));else if(t instanceof Function){let i=t(e,r,n);i&&(Array.isArray(i)?o=o.concat(i):o.push(i))}else if(Array.isArray(t))if(!Array.isArray(e))o.push(w("data is not an array",e,[],n));else for(let i of t)for(let s of e.keys()){let a=K(e[s],i,r,B(n,s));Array.isArray(a)?o=o.concat(a):a&&o.push(a)}else if(t&&typeof t=="object")if(Array.isArray(e)){let i=e.findIndex((s,a)=>K(s,t,r,B(n,a)));i>-1&&o.push(w("data["+i+"] does not match pattern",e[i],t,B(n,i)))}else if(!e||typeof e!="object")o.push(w("data is not an object, pattern is",e,t,n));else if(e instanceof URLSearchParams&&(e=Object.fromEntries(e)),t instanceof Function){let i=K(e,t,r,n);i&&(o=o.concat(i))}else for(let[i,s]of Object.entries(t)){let a=K(e[i],s,r,B(n,i));a&&(o=o.concat(a))}else t!=e&&o.push(w("data and pattern are not equal",e,t,n));return o.length?o:!1}function w(e,t,r,n="",o){let i=mt(n),s={path:n,pathString:ve(i),pathParts:i,message:e,found:t,expected:r};return o&&(s.problems=o),s}function wt(e,t,r,n){console.warn("\u{1F170}\uFE0F Assert: "+n,e,r,t)}globalThis.assert={...De};function gt(e){let t,r;if(typeof localStorage<"u")t={get:()=>localStorage.getItem("metro/state:"+e),set:n=>localStorage.setItem("metro/state:"+e,n),has:()=>localStorage.getItem("metro/state:"+e)!==null,delete:()=>localStorage.removeItem("metro/state:"+e)},r={get:n=>JSON.parse(localStorage.getItem(e+":"+n)),set:(n,o)=>localStorage.setItem(e+":"+n,JSON.stringify(o)),has:n=>localStorage.getItem(e+":"+n)!==null,delete:n=>localStorage.removeItem(e+":"+n)};else{let n=new Map;t={get:()=>n.get("metro/state:"+e),set:o=>n.set("metro/state:"+e,o),has:()=>n.has("metro/state:"+e),delete:()=>n.delete("metro/state:"+e)},r=new Map}return{state:t,tokens:r}}var wr=new Map([["bearer","Bearer"],["dpop","DPoP"]]),gr=new Set(["none","client_secret_post","client_secret_basic"]);function Ue(e){let t={client:C(),force_authorization:!1,site:"default",oauth2_configuration:{authorization_endpoint:"/authorize",token_endpoint:"/token",redirect_uri:globalThis.document?.location.href,grant_type:"authorization_code",code_verifier:Le(64)},authorize_callback:async c=>(window.location.href!=c.href&&window.location.replace(c.href),!1)};P(e,{});let r=Object.assign({},t.oauth2_configuration,e?.oauth2_configuration);e=Object.assign({},t,e),e.oauth2_configuration=r;let n=gt(e.site);e.tokens||(e.tokens=n.tokens),e.state||(e.state=n.state),P(e,{oauth2_configuration:{client_id:_(/.+/),grant_type:"authorization_code",authorization_endpoint:_(h),token_endpoint:_(h),redirect_uri:_(h)}});for(let c in r)switch(c){case"access_token":case"authorization_code":case"refresh_token":e.tokens.set(c,Sr(c,r[c]));break}return async function(c,u){if(e.force_authorization)return o(c,u);let y=await u(c);return y.ok||!St(y)?y:o(c,u)};async function o(c,u,y={}){i();let S=e.tokens.get("access_token"),T=e.tokens.get("refresh_token"),ce=Tr(S);if(!S||ce&&!T)return await s()?o(c,u):z("false");if(ce&&T)return await a()?o(c,u):z("false");{let fe=J(c,{headers:{Authorization:S.type+" "+S.value}}),ge=await u(fe);return!St(ge)||y.handledRejectedToken?ge:(e.tokens.delete("access_token"),(T?await a():await s())?o(c,u,{handledRejectedToken:!0}):z("false"))}}function i(){if(typeof window<"u"&&window?.location){let c=b(window.location),u,y,S;if(c.searchParams.has("code")||c.searchParams.has("error"))S=c.searchParams,c=c.with({search:""}),history.pushState({},"",c.href);else if(c.hash){let T=c.hash.substr(1);S=new URLSearchParams("?"+T),c=c.with({hash:""}),history.pushState({},"",c.href)}if(S){if(S.has("error"))throw m("oauth2mw: authorization failed: "+S.get("error")+(S.get("error_description")?" ("+S.get("error_description")+")":""));u=S.get("code"),y=S.get("state"),A(y),u&&e.tokens.set("authorization_code",u)}}}async function s(){if(r.grant_type==="authorization_code"&&!e.tokens.has("authorization_code")){let S=await d();if(!e.authorize_callback||typeof e.authorize_callback!="function")throw m("oauth2mw: oauth2 with grant_type:authorization_code requires a callback function in client options.authorize_callback");let T=await e.authorize_callback(S);if(T)g(T);else return!1}let c=l(),u=await e.client.post(c);if(!u.ok){let S=await u.text();throw m("OAuth2mw: fetch access_token: "+u.status+": "+u.statusText+" ("+S+")",{cause:c})}let y=await u.json();return R(y),e.tokens.delete("authorization_code"),y}async function a(){let c=l("refresh_token"),u=await e.client.post(c);if(!u.ok){let S=await u.text();throw m("OAuth2mw: refresh access_token: "+u.status+": "+u.statusText+" ("+S+")",{cause:c})}let y=await u.json();return R(y),y}async function d(){if(!r.authorization_endpoint)throw m("oauth2mw: Missing options.oauth2_configuration.authorization_endpoint");let c=b(r.authorization_endpoint,{hash:""});P(r,{client_id:/.+/,redirect_uri:/.+/,scope:/.*/});let u={response_type:"code",client_id:r.client_id,redirect_uri:r.redirect_uri,state:r.state||Or(40)};return r.response_type&&(u.response_type=r.response_type),r.response_mode&&(u.response_mode=r.response_mode),e.state.set(u.state),r.code_verifier&&(e.tokens.set("code_verifier",r.code_verifier),u.code_challenge=await Kr(r.code_verifier),u.code_challenge_method="S256"),r.scope&&(u.scope=r.scope),r.prompt&&(u.prompt=r.prompt),r.nonce&&(u.nonce=r.nonce),b(c,{search:u})}function l(c=null){if(P(r,{client_id:/.+/,redirect_uri:/.+/}),!r.token_endpoint)throw m("oauth2mw: Missing options.endpoints.token url");let u=b(r.token_endpoint,{hash:""}),y={grant_type:c||r.grant_type},S={};switch(p(y,S),r.scope&&(y.scope=r.scope),y.grant_type){case"authorization_code":y.redirect_uri=r.redirect_uri,y.code=e.tokens.get("authorization_code");let T=e.tokens.get("code_verifier");T&&(y.code_verifier=T);break;case"client_credentials":break;case"refresh_token":y.refresh_token=Rr(e.tokens.get("refresh_token"));break;default:throw new Error("Unknown grant_type: "+y.grant_type)}return J(u,{method:"POST",headers:S,body:new URLSearchParams(y)})}function p(c,u){let y=Ar(r);if(y==="none"){c.client_id=r.client_id;return}if(!r.client_secret)throw m("oauth2mw: token_endpoint_auth_method "+y+" requires oauth2_configuration.client_secret");if(y==="client_secret_post"){c.client_id=r.client_id,c.client_secret=r.client_secret;return}if(y==="client_secret_basic"){u.Authorization=xr(r.client_id,r.client_secret);return}}function g(c){let u=c;if(c&&typeof c=="object"){if(c.error)throw m("oauth2mw: authorization failed: "+c.error);A(c.state),u=c.authorization_code||c.code}if(!u)throw m("oauth2mw: authorization callback did not return an authorization code");e.tokens.set("authorization_code",u)}function A(c){let u=e.state.get();if(!c||c!==u)throw m("oauth2mw: authorization state mismatch")}function R(c){let u=br(c);e.tokens.set("access_token",u),c.refresh_token&&e.tokens.set("refresh_token",{value:c.refresh_token})}}function St(e){return e?e.status===400?!0:Cr(e.headers?.get("WWW-Authenticate"))?.error==="insufficient_scope"?!1:e.status===401:!1}function Sr(e,t){return e==="access_token"&&t&&typeof t=="object"?t:e==="access_token"?{value:t,type:"Bearer",expires:null}:t}function br(e){if(!e||typeof e!="object")throw m("OAuth2mw: token endpoint did not return a JSON object");if(!e.access_token)throw m("OAuth2mw: token response did not include access_token");if(!e.token_type)throw m("OAuth2mw: token response did not include token_type");let t=Er(e.token_type);return{value:e.access_token,expires:e.expires_in===void 0?null:kr(e.expires_in),type:t,scope:e.scope}}function Er(e){let t=wr.get(String(e).toLowerCase());if(!t)throw m("OAuth2mw: unsupported token_type "+e);return t}function Ar(e){let t=e.token_endpoint_auth_method||(e.client_secret?"client_secret_post":"none");if(!gr.has(t))throw m("oauth2mw: unsupported token_endpoint_auth_method "+t);return t}function xr(e,t){let r=bt(e)+":"+bt(t);return"Basic "+Pr(r)}function bt(e){return encodeURIComponent(e).replace(/%20/g,"+")}function Pr(e){return typeof btoa=="function"?btoa(e):Buffer.from(e,"binary").toString("base64")}function Rr(e){return e&&typeof e=="object"?e.value:e}function Tr(e){if(!e)return!0;if(!e.expires)return!1;let t=new Date(e.expires);return new Date().getTime()>t.getTime()}function kr(e){if(e instanceof Date)return new Date(e.getTime());if(typeof e=="number"){let t=new Date;return t.setSeconds(t.getSeconds()+e),t}throw new TypeError("Unknown expires type "+e)}function Le(e=64){let t=new Uint8Array(e);return globalThis.crypto.getRandomValues(t),He(t)}async function Kr(e){let r=new TextEncoder().encode(e),n=await globalThis.crypto.subtle.digest("SHA-256",r);return He(n)}function He(e){let t=Array.from(new Uint8Array(e),r=>String.fromCharCode(r)).join("");return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Or(e){let t=new Uint8Array(Math.ceil(e*3/4)+1);if(globalThis.crypto?.getRandomValues)return globalThis.crypto.getRandomValues(t),He(t).slice(0,e);let r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n="",o=0;for(;o<e;)n+=r.charAt(Math.floor(Math.random()*r.length)),o++;return n}function Et(){let e=new URL(document.location.href);if(!e.searchParams.has("code")){if(e.hash){let t=e.hash.substr(1);if(new URLSearchParams("?"+t).has("code"))return!0}return!1}return!0}function Cr(e){if(!e||typeof e!="string")return null;let t=e.trim(),r=t.search(/\s/),n=r<0?t:t.slice(0,r),o=r<0?"":t.slice(r+1);if(!["bearer","dpop"].includes(n.toLowerCase()))return null;let i={scheme:n},s=/([A-Za-z][A-Za-z0-9_-]*)=("(?:[^"\\]|\\.)*"|[^,\s]*)/g,a;for(;a=s.exec(o);){let d=a[2];d.startsWith('"')&&d.endsWith('"')&&(d=d.slice(1,-1).replace(/\\"/g,'"')),i[a[1]]=d}return i}var Ir=new TextEncoder,Wr=new TextDecoder;function Se(e){return typeof e=="string"?Ir.encode(e):Wr.decode(e)}function At(e){if(typeof e.modulusLength!="number"||e.modulusLength<2048)throw new Me(`${e.name} modulusLength must be at least 2048 bits`)}function Jr(e){switch(e.algorithm.name){case"ECDSA":return{name:e.algorithm.name,hash:"SHA-256"};case"RSA-PSS":return At(e.algorithm),{name:e.algorithm.name,saltLength:32};case"RSASSA-PKCS1-v1_5":return At(e.algorithm),{name:e.algorithm.name};case"Ed25519":return{name:e.algorithm.name}}throw new N}async function Dr(e,t,r){if(r.usages.includes("sign")===!1)throw new TypeError('private CryptoKey instances used for signing assertions must include "sign" in their "usages"');let n=`${be(Se(JSON.stringify(e)))}.${be(Se(JSON.stringify(t)))}`,o=be(await crypto.subtle.sign(Jr(r),r,Se(n)));return`${n}.${o}`}var Ne;Uint8Array.prototype.toBase64?Ne=e=>(e instanceof ArrayBuffer&&(e=new Uint8Array(e)),e.toBase64({alphabet:"base64url",omitPadding:!0})):Ne=t=>{t instanceof ArrayBuffer&&(t=new Uint8Array(t));let r=[];for(let n=0;n<t.byteLength;n+=32768)r.push(String.fromCharCode.apply(null,t.subarray(n,n+32768)));return btoa(r.join("")).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")};function be(e){return Ne(e)}var N=class extends Error{constructor(t){var r;super(t??"operation not supported"),this.name=this.constructor.name,(r=Error.captureStackTrace)===null||r===void 0||r.call(Error,this,this.constructor)}},Me=class extends Error{constructor(t){var r;super(t),this.name=this.constructor.name,(r=Error.captureStackTrace)===null||r===void 0||r.call(Error,this,this.constructor)}};function Ur(e){if(e.algorithm.hash.name==="SHA-256")return"PS256";throw new N("unsupported RsaHashedKeyAlgorithm hash name")}function Lr(e){if(e.algorithm.hash.name==="SHA-256")return"RS256";throw new N("unsupported RsaHashedKeyAlgorithm hash name")}function Hr(e){if(e.algorithm.namedCurve==="P-256")return"ES256";throw new N("unsupported EcKeyAlgorithm namedCurve")}function Nr(e){switch(e.algorithm.name){case"RSA-PSS":return Ur(e);case"RSASSA-PKCS1-v1_5":return Lr(e);case"ECDSA":return Hr(e);case"Ed25519":return"Ed25519";default:throw new N("unsupported CryptoKey algorithm name")}}function xt(e){return e instanceof CryptoKey}function Mr(e){return xt(e)&&e.type==="private"}function jr(e){return xt(e)&&e.type==="public"}function $r(){return Math.floor(Date.now()/1e3)}async function je(e,t,r,n,o,i){let s=e?.privateKey,a=e?.publicKey;if(!Mr(s))throw new TypeError('"keypair.privateKey" must be a private CryptoKey');if(!jr(a))throw new TypeError('"keypair.publicKey" must be a public CryptoKey');if(a.extractable!==!0)throw new TypeError('"keypair.publicKey.extractable" must be true');if(typeof t!="string")throw new TypeError('"htu" must be a string');if(typeof r!="string")throw new TypeError('"htm" must be a string');if(n!==void 0&&typeof n!="string")throw new TypeError('"nonce" must be a string or undefined');if(o!==void 0&&typeof o!="string")throw new TypeError('"accessToken" must be a string or undefined');if(i!==void 0&&(typeof i!="object"||i===null||Array.isArray(i)))throw new TypeError('"additional" must be an object');return Dr({alg:Nr(s),typ:"dpop+jwt",jwk:await zr(a)},Object.assign(Object.assign({},i),{iat:$r(),jti:crypto.randomUUID(),htm:r,nonce:n,htu:t,ath:o?be(await crypto.subtle.digest("SHA-256",Se(o))):void 0}),s)}async function zr(e){let{kty:t,e:r,n,x:o,y:i,crv:s}=await crypto.subtle.exportKey("jwk",e);return{kty:t,crv:s,e:r,n,x:o,y:i}}async function Pt(e,t){var r;let n;if(typeof e!="string"||e.length===0)throw new TypeError('"alg" must be a non-empty string');switch(e){case"PS256":n={name:"RSA-PSS",hash:"SHA-256",modulusLength:2048,publicExponent:new Uint8Array([1,0,1])};break;case"RS256":n={name:"RSASSA-PKCS1-v1_5",hash:"SHA-256",modulusLength:2048,publicExponent:new Uint8Array([1,0,1])};break;case"ES256":n={name:"ECDSA",namedCurve:"P-256"};break;case"Ed25519":n={name:"Ed25519"};break;default:throw new N}return crypto.subtle.generateKey(n,(r=t?.extractable)!==null&&r!==void 0?r:!1,["sign","verify"])}function $e(){return new Promise((e,t)=>{let r=globalThis.indexedDB.open("metro",1);r.onupgradeneeded=()=>r.result.createObjectStore("keyPairs",{keyPath:"domain"}),r.onerror=n=>{t(n)},r.onsuccess=n=>{let o=n.target.result;e({set:function(i,s){return new Promise((a,d)=>{let l=o.transaction("keyPairs","readwrite",{durability:"strict"}),p=l.objectStore("keyPairs");l.oncomplete=()=>{a()},l.onerror=d,p.put(i,s)})},get:function(i){return new Promise((s,a)=>{let d=o.transaction("keyPairs","readonly"),p=d.objectStore("keyPairs").get(i);p.onsuccess=()=>{s(p.result)},p.onerror=a,d.onerror=a})},clear:function(){return new Promise((i,s)=>{let a=o.transaction("keyPairs","readwrite"),l=a.objectStore("keyPairs").clear();l.onsuccess=()=>{i()},l.onerror=s,a.onerror=s})}})}})}function ze(e){return P(e,{site:_(h),authorization_endpoint:_(h),token_endpoint:_(h),dpop_signing_alg_values_supported:f([])}),async(t,r)=>{let n=await $e(),o=await n.get(e.site);if(!o){let a=await Pt("ES256");o={domain:e.site,keyPair:a},await n.set(o)}let i=b(t.url);if(t.url.startsWith(e.authorization_endpoint)){let a=t.body;a instanceof URLSearchParams||a instanceof FormData?a.set("dpop_jkt",o.keyPair.publicKey):a.dpop_jkt=o.keyPair.publicKey}else if(t.url.startsWith(e.token_endpoint)){let a=await je(o.keyPair,t.url,t.method);t=t.with({headers:{DPoP:a}})}else if(t.headers.has("Authorization")){let a=localStorage.getItem(i.host+":nonce")||void 0,d=t.headers.get("Authorization").split(" ")[1],l=await je(o.keyPair,t.url,t.method,a,d);t=t.with({headers:{Authorization:"DPoP "+d,DPoP:l}})}let s=await r(t);return s.headers.get("DPoP-Nonce")&&localStorage.setItem(i.host+":nonce",s.headers.get("DPoP-Nonce")),s}}function U(e){return e=Object.assign({contentType:"application/json",reviver:null,replacer:null,space:""},e),async function(r,n){if(r.headers.get("Accept")||(r=r.with({headers:{Accept:e.accept??e.contentType}})),r.method!=="GET"&&r.method!=="HEAD"&&r.data&&typeof r.data=="object"&&!(r.data instanceof ReadableStream)){let i=r.headers.get("Content-Type");(!i||Gr(i))&&(r=r.with({headers:{"Content-Type":e.contentType}})),Rt(r.headers.get("Content-Type"))&&(r=r.with({body:JSON.stringify(r.data,e.replacer,e.space)}))}let o=await n(r);if(o&&Rt(o.headers?.get("Content-Type"))){let s=await o.clone().text();if(s==="")return o;try{let a=JSON.parse(s,e.reviver);return o.with({body:a})}catch(a){if(!o.ok)return o;throw Vr(r,o,a)}}return o}}function Vr(e,t,r){let n="jsonmw: could not parse "+t.headers.get("Content-Type")+" response from "+e.url,o=new Error(n,{cause:r});return o.request=e,o.response=t,o}var Fr=/^application\/([a-zA-Z0-9\-_]+\+)?json\b/;function Rt(e){return Fr.exec(e)}function Gr(e){return/^text\/plain\b/.exec(e)}function L(e){return async function(r,n){let o=await n(r);if(!o.ok)if(e&&typeof e[o.status]=="function")o=e[o.status].apply(o,r);else throw new Error(o.status+": "+o.statusText,{cause:o});return o}}var me=(...e)=>(t,r)=>e.filter(n=>r.hasOwnKey(n)).length>0?!1:w("root data must have all of",r,e),M=(...e)=>t=>Array.isArray(t)&&e.filter(r=>!t.includes(r)).length==0?!1:w("data must be an array which includes",t,e);var I=["HS256","HS384","HS512","RS256","RS384","RS512","ES256","ES384","ES512"],Ee=["none","client_secret_post","client_secret_basic","client_secret_jwt","private_key_jwt"];async function Q(e={}){P(e,{client:f(G(C().constructor)),issuer:_(h)});let t={client:C().with(L()).with(U()),requireDynamicRegistration:!1};e=Object.assign({},t,e),e.client=e.client.with(L()).with(U());let r=!1;function n(d){return r}let o={issuer:_(We(e.issuer,n)),authorization_endpoint:_(h),token_endpoint:_(h),userinfo_endpoint:Y(h),jwks_uri:_(h),registration_endpoint:e.requireDynamicRegistration?_(h):Y(h),scopes_supported:Y(M("openid")),response_types_supported:e.requireDynamicRegistration?_(M("code","id_token","id_token token")):_([]),response_modes_supported:f([]),grant_types_supported:e.requireDynamicRegistration?f(M("authorization_code")):f([]),acr_values_supported:f([]),subject_types_supported:_([]),id_token_signing_alg_values_supported:_(M("RS256")),id_token_encryption_alg_values_supported:f([]),id_token_encryption_enc_values_supported:f([]),userinfo_signing_alg_values_supported:f([]),userinfo_encryption_alg_values_supported:f([]),userinfo_encryption_enc_values_supported:f([]),request_object_signing_alg_values_supported:f(M("RS256")),request_object_encryption_alg_values_supported:f([]),request_object_encryption_enc_values_supported:f([]),token_endpoint_auth_methods_supported:f(F(...Ee)),token_endpoint_auth_signing_alg_values_supported:f(M("RS256"),Z(M("none"))),display_values_supported:f(F("page","popup","touch","wap")),claim_types_supported:f(F("normal","aggregated","distributed")),claims_supported:Y([]),service_documentation:f(h),claims_locales_supported:f([]),ui_locales_supported:f([]),claims_parameter_supported:f(Boolean),request_parameter_supported:f(Boolean),request_uri_parameter_supported:f(Boolean),op_policy_uri:f(h),op_tos_uri:f(h)},i=b(e.issuer,".well-known/openid-configuration"),a=(await e.client.get(i)).data;return P(a,o),P(a.issuer,e.issuer),a}async function ee(e){let t={redirect_uris:_([h]),response_types:f([]),grant_types:f(F("authorization_code","refresh_token")),application_type:f(k("native","web")),contacts:f([Je]),client_name:f(String),logo_uri:f(h),client_uri:f(h),policy_uri:f(h),tos_uri:f(h),jwks_uri:f(h,Z(me("jwks"))),jwks:f(h,Z(me("jwks_uri"))),sector_identifier_uri:f(h),subject_type:f(String),id_token_signed_response_alg:f(k(...I)),id_token_encrypted_response_alg:f(k(...I)),id_token_encrypted_response_enc:f(k(...I),me("id_token_encrypted_response_alg")),userinfo_signed_response_alg:f(k(...I)),userinfo_encrypted_response_alg:f(k(...I)),userinfo_encrypted_response_enc:f(k(...I),me("userinfo_encrypted_response_alg")),request_object_signing_alg:f(k(...I)),request_object_encryption_alg:f(k(...I)),request_object_encryption_enc:f(k(...I)),token_endpoint_auth_method:f(k(...Ee)),token_endpoint_auth_signing_alg:f(k(...I)),default_max_age:f(Number),require_auth_time:f(Boolean),default_acr_values:f([String]),initiate_login_uri:f([h]),request_uris:f([h])};P(e,{client:f(G(C().constructor)),registration_endpoint:h,client_info:t});let r={client:C().with(L()).with(U()),client_info:{redirect_uris:[globalThis.document?.location.href]}};e=Object.assign({},r,e),e.client=e.client.with(L()).with(U()),e.client_info||(e.client_info={}),e.client_info.redirect_uris||(e.client_info.redirect_uris=[globalThis.document?.location.href]);let n=await e.client.post(e.registration_endpoint,{body:e.client_info}),o=n.data;if(!o.client_id)throw m("metro.oidc: Error: dynamic registration of client failed, no client_id returned",n);return e.client_info=Object.assign(e.client_info,o),e.client_info}function te(e){let t;if(typeof localStorage<"u")t={get:r=>JSON.parse(localStorage.getItem("metro/oidc:"+e+":"+r)),set:(r,n)=>localStorage.setItem("metro/oidc:"+e+":"+r,JSON.stringify(n)),has:r=>localStorage.getItem("metro/oidc:"+e+":"+r)!==null};else{let r=new Map;t={get:n=>JSON.parse(r.get("metro/oidc:"+e+":"+n)||null),set:(n,o)=>r.set("metro/oidc:"+e+":"+n,JSON.stringify(o)),has:n=>r.has("metro/oidc:"+e+":"+n)}}return t}var he=new TextEncoder,H=new TextDecoder,Yn=2**32;function Tt(...e){let t=e.reduce((o,{length:i})=>o+i,0),r=new Uint8Array(t),n=0;for(let o of e)r.set(o,n),n+=o.length;return r}function Ae(e){let t=new Uint8Array(e.length);for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);if(n>127)throw new TypeError("non-ASCII string encountered in encode()");t[r]=n}return t}function kt(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e);let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}function j(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(typeof e=="string"?e:H.decode(e),{alphabet:"base64url"});let t=e;t instanceof Uint8Array&&(t=H.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/");try{return kt(t)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}}var $=(e,t="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`),re=(e,t)=>e.name===t;function qr(e){return parseInt(e.name.slice(4),10)}function Be(e,t){if(qr(e.hash)!==t)throw $(`SHA-${t}`,"algorithm.hash")}function Xr(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function Yr(e,t){if(t&&!e.usages.includes(t))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function Kt(e,t,r){switch(t){case"HS256":case"HS384":case"HS512":{if(!re(e.algorithm,"HMAC"))throw $("HMAC");Be(e.algorithm,parseInt(t.slice(2),10));break}case"RS256":case"RS384":case"RS512":{if(!re(e.algorithm,"RSASSA-PKCS1-v1_5"))throw $("RSASSA-PKCS1-v1_5");Be(e.algorithm,parseInt(t.slice(2),10));break}case"PS256":case"PS384":case"PS512":{if(!re(e.algorithm,"RSA-PSS"))throw $("RSA-PSS");Be(e.algorithm,parseInt(t.slice(2),10));break}case"Ed25519":case"EdDSA":{if(!re(e.algorithm,"Ed25519"))throw $("Ed25519");break}case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":{if(!re(e.algorithm,t))throw $(t);break}case"ES256":case"ES384":case"ES512":{if(!re(e.algorithm,"ECDSA"))throw $("ECDSA");let n=Xr(t);if(e.algorithm.namedCurve!==n)throw $(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}Yr(e,r)}function Ot(e,t,...r){if(r=r.filter(Boolean),r.length>2){let n=r.pop();e+=`one of type ${r.join(", ")}, or ${n}.`}else r.length===2?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return t==null?e+=` Received ${t}`:typeof t=="function"&&t.name?e+=` Received function ${t.name}`:typeof t=="object"&&t!=null&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}var Ct=(e,...t)=>Ot("Key must be ",e,...t),Ve=(e,t,...r)=>Ot(`Key for the ${e} algorithm must be `,t,...r);var v=class extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(t,r){super(t,r),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}},O=class extends v{static code="ERR_JWT_CLAIM_VALIDATION_FAILED";code="ERR_JWT_CLAIM_VALIDATION_FAILED";claim;reason;payload;constructor(t,r,n="unspecified",o="unspecified"){super(t,{cause:{claim:n,reason:o,payload:r}}),this.claim=n,this.reason=o,this.payload=r}},ye=class extends v{static code="ERR_JWT_EXPIRED";code="ERR_JWT_EXPIRED";claim;reason;payload;constructor(t,r,n="unspecified",o="unspecified"){super(t,{cause:{claim:n,reason:o,payload:r}}),this.claim=n,this.reason=o,this.payload=r}},xe=class extends v{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"},x=class extends v{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"};var E=class extends v{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"},ne=class extends v{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"};var _e=class extends v{static code="ERR_JWKS_INVALID";code="ERR_JWKS_INVALID"},Pe=class extends v{static code="ERR_JWKS_NO_MATCHING_KEY";code="ERR_JWKS_NO_MATCHING_KEY";constructor(t="no applicable key found in the JSON Web Key Set",r){super(t,r)}},Re=class extends v{[Symbol.asyncIterator];static code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";constructor(t="multiple matching keys found in the JSON Web Key Set",r){super(t,r)}};var Te=class extends v{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(t="signature verification failed",r){super(t,r)}};var Fe=e=>{if(e?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return e instanceof CryptoKey}catch{return!1}},Ge=e=>e?.[Symbol.toStringTag]==="KeyObject",qe=e=>Fe(e)||Ge(e);function Xe(e,t,r){try{return j(e)}catch{throw new r(`Failed to base64url decode the ${t}`)}}var Zr=e=>typeof e=="object"&&e!==null;function W(e){if(!Zr(e)||Object.prototype.toString.call(e)!=="[object Object]")return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function vt(...e){let t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let r;for(let n of t){let o=Object.keys(n);if(!r||r.size===0){r=new Set(o);continue}for(let i of o){if(r.has(i))return!1;r.add(i)}}return!0}var we=e=>W(e)&&typeof e.kty=="string",It=e=>e.kty!=="oct"&&(e.kty==="AKP"&&typeof e.priv=="string"||typeof e.d=="string"),Wt=e=>e.kty!=="oct"&&e.d===void 0&&e.priv===void 0,Jt=e=>e.kty==="oct"&&typeof e.k=="string";function en(e,t){if(e.startsWith("RS")||e.startsWith("PS")){let{modulusLength:r}=t.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}}function tn(e,t){let r=`SHA-${e.slice(-3)}`;switch(e){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:parseInt(e.slice(-3),10)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:t.namedCurve};case"Ed25519":case"EdDSA":return{name:"Ed25519"};case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":return{name:e};default:throw new x(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}async function rn(e,t,r){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(Ct(t,"CryptoKey","KeyObject","JSON Web Key"));return crypto.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}return Kt(t,e,r),t}async function Dt(e,t,r,n){let o=await rn(e,t,"verify");en(e,o);let i=tn(e,o.algorithm);try{return await crypto.subtle.verify(i,o,r,n)}catch{return!1}}var ke='Invalid or unsupported JWK "alg" (Algorithm) Parameter value';function nn(e){let t,r;switch(e.kty){case"AKP":{switch(e.alg){case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":t={name:e.alg},r=e.priv?["sign"]:["verify"];break;default:throw new x(ke)}break}case"RSA":{switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":t={name:"RSA-OAEP",hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},r=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new x(ke)}break}case"EC":{switch(e.alg){case"ES256":case"ES384":case"ES512":t={name:"ECDSA",namedCurve:{ES256:"P-256",ES384:"P-384",ES512:"P-521"}[e.alg]},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:"ECDH",namedCurve:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new x(ke)}break}case"OKP":{switch(e.alg){case"Ed25519":case"EdDSA":t={name:"Ed25519"},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new x(ke)}break}default:throw new x('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:r}}async function oe(e){if(!e.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');let{algorithm:t,keyUsages:r}=nn(e),n={...e};return n.kty!=="AKP"&&delete n.alg,delete n.use,crypto.subtle.importKey("jwk",n,t,e.ext??!(e.d||e.priv),e.key_ops??r)}var ie="given KeyObject instance cannot be used for this algorithm",se,Ut=async(e,t,r,n=!1)=>{se||=new WeakMap;let o=se.get(e);if(o?.[r])return o[r];let i=await oe({...t,alg:r});return n&&Object.freeze(e),o?o[r]=i:se.set(e,{[r]:i}),i},on=(e,t)=>{se||=new WeakMap;let r=se.get(e);if(r?.[t])return r[t];let n=e.type==="public",o=!!n,i;if(e.asymmetricKeyType==="x25519"){switch(t){case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":break;default:throw new TypeError(ie)}i=e.toCryptoKey(e.asymmetricKeyType,o,n?[]:["deriveBits"])}if(e.asymmetricKeyType==="ed25519"){if(t!=="EdDSA"&&t!=="Ed25519")throw new TypeError(ie);i=e.toCryptoKey(e.asymmetricKeyType,o,[n?"verify":"sign"])}switch(e.asymmetricKeyType){case"ml-dsa-44":case"ml-dsa-65":case"ml-dsa-87":{if(t!==e.asymmetricKeyType.toUpperCase())throw new TypeError(ie);i=e.toCryptoKey(e.asymmetricKeyType,o,[n?"verify":"sign"])}}if(e.asymmetricKeyType==="rsa"){let s;switch(t){case"RSA-OAEP":s="SHA-1";break;case"RS256":case"PS256":case"RSA-OAEP-256":s="SHA-256";break;case"RS384":case"PS384":case"RSA-OAEP-384":s="SHA-384";break;case"RS512":case"PS512":case"RSA-OAEP-512":s="SHA-512";break;default:throw new TypeError(ie)}if(t.startsWith("RSA-OAEP"))return e.toCryptoKey({name:"RSA-OAEP",hash:s},o,n?["encrypt"]:["decrypt"]);i=e.toCryptoKey({name:t.startsWith("PS")?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:s},o,[n?"verify":"sign"])}if(e.asymmetricKeyType==="ec"){let a=new Map([["prime256v1","P-256"],["secp384r1","P-384"],["secp521r1","P-521"]]).get(e.asymmetricKeyDetails?.namedCurve);if(!a)throw new TypeError(ie);let d={ES256:"P-256",ES384:"P-384",ES512:"P-521"};d[t]&&a===d[t]&&(i=e.toCryptoKey({name:"ECDSA",namedCurve:a},o,[n?"verify":"sign"])),t.startsWith("ECDH-ES")&&(i=e.toCryptoKey({name:"ECDH",namedCurve:a},o,n?[]:["deriveBits"]))}if(!i)throw new TypeError(ie);return r?r[t]=i:se.set(e,{[t]:i}),i};async function Lt(e,t){if(e instanceof Uint8Array||Fe(e))return e;if(Ge(e)){if(e.type==="secret")return e.export();if("toCryptoKey"in e&&typeof e.toCryptoKey=="function")try{return on(e,t)}catch(n){if(n instanceof TypeError)throw n}let r=e.export({format:"jwk"});return Ut(e,r,t)}if(we(e))return e.k?j(e.k):Ut(e,e,t,!0);throw new Error("unreachable")}async function Ht(e,t,r){if(!W(e))throw new TypeError("JWK must be an object");let n;switch(t??=e.alg,n??=r?.extractable??e.ext,e.kty){case"oct":if(typeof e.k!="string"||!e.k)throw new TypeError('missing "k" (Key Value) Parameter value');return j(e.k);case"RSA":if("oth"in e&&e.oth!==void 0)throw new x('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');return oe({...e,alg:t,ext:n});case"AKP":{if(typeof e.alg!="string"||!e.alg)throw new TypeError('missing "alg" (Algorithm) Parameter value');if(t!==void 0&&t!==e.alg)throw new TypeError("JWK alg and alg option value mismatch");return oe({...e,ext:n})}case"EC":case"OKP":return oe({...e,alg:t,ext:n});default:throw new x('Unsupported "kty" (Key Type) Parameter value')}}function Nt(e,t,r,n,o){if(o.crit!==void 0&&n?.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||n.crit===void 0)return new Set;if(!Array.isArray(n.crit)||n.crit.length===0||n.crit.some(s=>typeof s!="string"||s.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i;r!==void 0?i=new Map([...Object.entries(r),...t.entries()]):i=t;for(let s of n.crit){if(!i.has(s))throw new x(`Extension Header Parameter "${s}" is not recognized`);if(o[s]===void 0)throw new e(`Extension Header Parameter "${s}" is missing`);if(i.get(s)&&n[s]===void 0)throw new e(`Extension Header Parameter "${s}" MUST be integrity protected`)}return new Set(n.crit)}function Mt(e,t){if(t!==void 0&&(!Array.isArray(t)||t.some(r=>typeof r!="string")))throw new TypeError(`"${e}" option must be an array of strings`);if(t)return new Set(t)}var ae=e=>e?.[Symbol.toStringTag],Ye=(e,t,r)=>{if(t.use!==void 0){let n;switch(r){case"sign":case"verify":n="sig";break;case"encrypt":case"decrypt":n="enc";break}if(t.use!==n)throw new TypeError(`Invalid key for this operation, its "use" must be "${n}" when present`)}if(t.alg!==void 0&&t.alg!==e)throw new TypeError(`Invalid key for this operation, its "alg" must be "${e}" when present`);if(Array.isArray(t.key_ops)){let n;switch(!0){case(r==="sign"||r==="verify"):case e==="dir":case e.includes("CBC-HS"):n=r;break;case e.startsWith("PBES2"):n="deriveBits";break;case/^A\d{3}(?:GCM)?(?:KW)?$/.test(e):!e.includes("GCM")&&e.endsWith("KW")?n=r==="encrypt"?"wrapKey":"unwrapKey":n=r;break;case(r==="encrypt"&&e.startsWith("RSA")):n="wrapKey";break;case r==="decrypt":n=e.startsWith("RSA")?"unwrapKey":"deriveBits";break}if(n&&t.key_ops?.includes?.(n)===!1)throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${n}" when present`)}return!0},sn=(e,t,r)=>{if(!(t instanceof Uint8Array)){if(we(t)){if(Jt(t)&&Ye(e,t,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!qe(t))throw new TypeError(Ve(e,t,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"));if(t.type!=="secret")throw new TypeError(`${ae(t)} instances for symmetric algorithms must be of type "secret"`)}},an=(e,t,r)=>{if(we(t))switch(r){case"decrypt":case"sign":if(It(t)&&Ye(e,t,r))return;throw new TypeError("JSON Web Key for this operation must be a private JWK");case"encrypt":case"verify":if(Wt(t)&&Ye(e,t,r))return;throw new TypeError("JSON Web Key for this operation must be a public JWK")}if(!qe(t))throw new TypeError(Ve(e,t,"CryptoKey","KeyObject","JSON Web Key"));if(t.type==="secret")throw new TypeError(`${ae(t)} instances for asymmetric algorithms must not be of type "secret"`);if(t.type==="public")switch(r){case"sign":throw new TypeError(`${ae(t)} instances for asymmetric algorithm signing must be of type "private"`);case"decrypt":throw new TypeError(`${ae(t)} instances for asymmetric algorithm decryption must be of type "private"`)}if(t.type==="private")switch(r){case"verify":throw new TypeError(`${ae(t)} instances for asymmetric algorithm verifying must be of type "public"`);case"encrypt":throw new TypeError(`${ae(t)} instances for asymmetric algorithm encryption must be of type "public"`)}};function jt(e,t,r){switch(e.substring(0,2)){case"A1":case"A2":case"di":case"HS":case"PB":sn(e,t,r);break;default:an(e,t,r)}}async function $t(e,t,r){if(!W(e))throw new E("Flattened JWS must be an object");if(e.protected===void 0&&e.header===void 0)throw new E('Flattened JWS must have either of the "protected" or "header" members');if(e.protected!==void 0&&typeof e.protected!="string")throw new E("JWS Protected Header incorrect type");if(e.payload===void 0)throw new E("JWS Payload missing");if(typeof e.signature!="string")throw new E("JWS Signature missing or incorrect type");if(e.header!==void 0&&!W(e.header))throw new E("JWS Unprotected Header incorrect type");let n={};if(e.protected)try{let y=j(e.protected);n=JSON.parse(H.decode(y))}catch{throw new E("JWS Protected Header is invalid")}if(!vt(n,e.header))throw new E("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let o={...n,...e.header},i=Nt(E,new Map([["b64",!0]]),r?.crit,n,o),s=!0;if(i.has("b64")&&(s=n.b64,typeof s!="boolean"))throw new E('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:a}=o;if(typeof a!="string"||!a)throw new E('JWS "alg" (Algorithm) Header Parameter missing or invalid');let d=r&&Mt("algorithms",r.algorithms);if(d&&!d.has(a))throw new xe('"alg" (Algorithm) Header Parameter value not allowed');if(s){if(typeof e.payload!="string")throw new E("JWS Payload must be a string")}else if(typeof e.payload!="string"&&!(e.payload instanceof Uint8Array))throw new E("JWS Payload must be a string or an Uint8Array instance");let l=!1;typeof t=="function"&&(t=await t(n,e),l=!0),jt(a,t,"verify");let p=Tt(e.protected!==void 0?Ae(e.protected):new Uint8Array,Ae("."),typeof e.payload=="string"?s?Ae(e.payload):he.encode(e.payload):e.payload),g=Xe(e.signature,"signature",E),A=await Lt(t,a);if(!await Dt(a,A,g,p))throw new Te;let c;s?c=Xe(e.payload,"payload",E):typeof e.payload=="string"?c=he.encode(e.payload):c=e.payload;let u={payload:c};return e.protected!==void 0&&(u.protectedHeader=n),e.header!==void 0&&(u.unprotectedHeader=e.header),l?{...u,key:A}:u}async function zt(e,t,r){if(e instanceof Uint8Array&&(e=H.decode(e)),typeof e!="string")throw new E("Compact JWS must be a string or Uint8Array");let{0:n,1:o,2:i,length:s}=e.split(".");if(s!==3)throw new E("Invalid Compact JWS");let a=await $t({payload:o,protected:n,signature:i},t,r),d={payload:a.payload,protectedHeader:a.protectedHeader};return typeof t=="function"?{...d,key:a.key}:d}var cn=e=>Math.floor(e.getTime()/1e3),Ft=60,Gt=Ft*60,Ze=Gt*24,fn=Ze*7,un=Ze*365.25,ln=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function Bt(e){let t=ln.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");let r=parseFloat(t[2]),n=t[3].toLowerCase(),o;switch(n){case"sec":case"secs":case"second":case"seconds":case"s":o=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":o=Math.round(r*Ft);break;case"hour":case"hours":case"hr":case"hrs":case"h":o=Math.round(r*Gt);break;case"day":case"days":case"d":o=Math.round(r*Ze);break;case"week":case"weeks":case"w":o=Math.round(r*fn);break;default:o=Math.round(r*un);break}return t[1]==="-"||t[4]==="ago"?-o:o}var Vt=e=>e.includes("/")?e.toLowerCase():`application/${e.toLowerCase()}`,dn=(e,t)=>typeof e=="string"?t.includes(e):Array.isArray(e)?t.some(Set.prototype.has.bind(new Set(e))):!1;function qt(e,t,r={}){let n;try{n=JSON.parse(H.decode(t))}catch{}if(!W(n))throw new ne("JWT Claims Set must be a top-level JSON object");let{typ:o}=r;if(o&&(typeof e.typ!="string"||Vt(e.typ)!==Vt(o)))throw new O('unexpected "typ" JWT header value',n,"typ","check_failed");let{requiredClaims:i=[],issuer:s,subject:a,audience:d,maxTokenAge:l}=r,p=[...i];l!==void 0&&p.push("iat"),d!==void 0&&p.push("aud"),a!==void 0&&p.push("sub"),s!==void 0&&p.push("iss");for(let c of new Set(p.reverse()))if(!(c in n))throw new O(`missing required "${c}" claim`,n,c,"missing");if(s&&!(Array.isArray(s)?s:[s]).includes(n.iss))throw new O('unexpected "iss" claim value',n,"iss","check_failed");if(a&&n.sub!==a)throw new O('unexpected "sub" claim value',n,"sub","check_failed");if(d&&!dn(n.aud,typeof d=="string"?[d]:d))throw new O('unexpected "aud" claim value',n,"aud","check_failed");let g;switch(typeof r.clockTolerance){case"string":g=Bt(r.clockTolerance);break;case"number":g=r.clockTolerance;break;case"undefined":g=0;break;default:throw new TypeError("Invalid clockTolerance option type")}let{currentDate:A}=r,R=cn(A||new Date);if((n.iat!==void 0||l)&&typeof n.iat!="number")throw new O('"iat" claim must be a number',n,"iat","invalid");if(n.nbf!==void 0){if(typeof n.nbf!="number")throw new O('"nbf" claim must be a number',n,"nbf","invalid");if(n.nbf>R+g)throw new O('"nbf" claim timestamp check failed',n,"nbf","check_failed")}if(n.exp!==void 0){if(typeof n.exp!="number")throw new O('"exp" claim must be a number',n,"exp","invalid");if(n.exp<=R-g)throw new ye('"exp" claim timestamp check failed',n,"exp","check_failed")}if(l){let c=R-n.iat,u=typeof l=="number"?l:Bt(l);if(c-g>u)throw new ye('"iat" claim timestamp check failed (too far in the past)',n,"iat","check_failed");if(c<0-g)throw new O('"iat" claim timestamp check failed (it should be in the past)',n,"iat","check_failed")}return n}async function Qe(e,t,r){let n=await zt(e,t,r);if(n.protectedHeader.crit?.includes("b64")&&n.protectedHeader.b64===!1)throw new ne("JWTs MUST NOT use unencoded payload");let i={payload:qt(n.protectedHeader,n.payload,r),protectedHeader:n.protectedHeader};return typeof t=="function"?{...i,key:n.key}:i}function pn(e){switch(typeof e=="string"&&e.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";case"ML":return"AKP";default:throw new x('Unsupported "alg" value for a JSON Web Key Set')}}function mn(e){return e&&typeof e=="object"&&Array.isArray(e.keys)&&e.keys.every(hn)}function hn(e){return W(e)}var et=class{#e;#t=new WeakMap;constructor(t){if(!mn(t))throw new _e("JSON Web Key Set malformed");this.#e=structuredClone(t)}jwks(){return this.#e}async getKey(t,r){let{alg:n,kid:o}={...t,...r?.header},i=pn(n),s=this.#e.keys.filter(l=>{let p=i===l.kty;if(p&&typeof o=="string"&&(p=o===l.kid),p&&(typeof l.alg=="string"||i==="AKP")&&(p=n===l.alg),p&&typeof l.use=="string"&&(p=l.use==="sig"),p&&Array.isArray(l.key_ops)&&(p=l.key_ops.includes("verify")),p)switch(n){case"ES256":p=l.crv==="P-256";break;case"ES384":p=l.crv==="P-384";break;case"ES512":p=l.crv==="P-521";break;case"Ed25519":case"EdDSA":p=l.crv==="Ed25519";break}return p}),{0:a,length:d}=s;if(d===0)throw new Pe;if(d!==1){let l=new Re,p=this.#t;throw l[Symbol.asyncIterator]=async function*(){for(let g of s)try{yield await Xt(p,g,n)}catch{}},l}return Xt(this.#t,a,n)}};async function Xt(e,t,r){let n=e.get(t)||e.set(t,{}).get(t);if(n[r]===void 0){let o=await Ht({...t,ext:!0},r);if(o instanceof Uint8Array||o.type!=="public")throw new _e("JSON Web Key Set members must be public keys");n[r]=o}return n[r]}function tt(e){let t=new et(e),r=async(n,o)=>t.getKey(n,o);return Object.defineProperties(r,{jwks:{value:()=>structuredClone(t.jwks()),enumerable:!1,configurable:!1,writable:!1}}),r}var rt=new WeakMap;function yn(e){if(!e||!Array.isArray(e.keys))throw m("metro.oidc: Error: jwks must be an object with a keys array");return rt.has(e)||rt.set(e,tt(e)),rt.get(e)}function _n(e={}){let t=e.id_token_signing_alg_values_supported;return Array.isArray(t)&&t.length?t.filter(r=>r!=="none"):["RS256"]}async function nt(e,t={}){if(!e)throw m("metro.oidc: Error: token response did not include an id_token");if(!t.jwks)throw m("metro.oidc: Error: cannot validate id_token without jwks");if(!t.issuer)throw m("metro.oidc: Error: cannot validate id_token without issuer");if(!t.client_id)throw m("metro.oidc: Error: cannot validate id_token without client_id");let{payload:r,protectedHeader:n}=await Qe(e,yn(t.jwks),{issuer:t.issuer,audience:t.client_id,algorithms:t.algorithms||_n(t.openid_configuration),clockTolerance:t.clockTolerance??60,requiredClaims:["iss","sub","aud","exp","iat"]});if(t.nonce!==void 0&&r.nonce!==t.nonce)throw m("metro.oidc: Error: id_token nonce mismatch");return{header:n,claims:r}}function Ke(e={}){let t={client:C(),force_authorization:!1,use_dpop:!0,authorize_callback:async n=>(window.location.href!=n.href&&window.location.replace(n.href),!1)};e=Object.assign({},t,e);let r=e.client_info;if(P(e,{client:_(G(C().constructor)),client_info:_(),issuer:_(h),oauth2:f({}),openid_configuration:f()}),e.store||(e.store=te(e.issuer)),!e.openid_configuration&&e.store.has("openid_configuration")&&(e.openid_configuration=e.store.get("openid_configuration")),!e.client_info?.client_id&&e.store.has("client_info")){let n=e.store.get("client_info");wn(n,r)&&(e.client_info=n)}return async(n,o)=>{let i;if(!e.force_authorization){try{i=await o(n)}catch(A){if(i=A?.cause,!i||i.status!=401&&i.status!=403)throw A}if(i.ok||i.status!=401&&i.status!=403)return i}if(e.openid_configuration||(e.openid_configuration=await Q({issuer:e.issuer,client:e.client.with(e.issuer)}),e.store.set("openid_configuration",e.openid_configuration)),!e.client_info?.client_id){if(!e.openid_configuration.registration_endpoint)throw m("metro.oidcmw: Error: issuer "+e.issuer+" does not support dynamic client registration, but you haven't specified a client_id");e.client_info=await ee({registration_endpoint:e.openid_configuration.registration_endpoint,client:e.client,client_info:e.client_info}),e.store.set("client_info",e.client_info)}let s=e.scope||"openid",a=e.nonce||Le(32);e.store.set("pending_nonce",a);let d=Object.assign({site:e.issuer,client:e.client,force_authorization:!0,authorize_callback:e.authorize_callback,oauth2_configuration:{client_id:e.client_info?.client_id,client_secret:e.client_info?.client_secret,grant_type:"authorization_code",response_type:"code",response_mode:"query",authorization_endpoint:e.openid_configuration.authorization_endpoint,token_endpoint:e.openid_configuration.token_endpoint,scope:s,redirect_uri:e.client_info.redirect_uris[0],nonce:a}}),l=async(A,R)=>{let c=await R(A),u=b(e.openid_configuration.token_endpoint,{hash:""}).href;if(b(A.url,{hash:""}).href!==u||!c.headers.get("content-type")?.startsWith("application/json"))return c;let T=c.data&&typeof c.data=="object"?c.data:null;T||(T=await c.clone().json());let ce=T?.id_token,fe=await p(),ge=await nt(ce,{issuer:e.openid_configuration.issuer,client_id:e.client_info.client_id,jwks:fe,openid_configuration:e.openid_configuration,nonce:e.store.get("pending_nonce")});return e.store.set("id_token",ce),e.store.set("id_token_claims",ge.claims),c},p=async()=>{if(!e.jwks){let R=await e.client.with(L()).with(U()).get(e.openid_configuration.jwks_uri);e.jwks=R.data}return e.jwks},g=e.client.with(e.issuer).with(l);if(e.use_dpop){let A={site:e.issuer,authorization_endpoint:e.openid_configuration.authorization_endpoint,token_endpoint:e.openid_configuration.token_endpoint,dpop_signing_alg_values_supported:e.openid_configuration.dpop_signing_alg_values_supported};g=g.with(ze(A))}return d.client=g,g=g.with(Ue(d)),i=await g.fetch(n),i}}function wn(e,t){if(!e?.client_id)return!1;if(!Array.isArray(t?.redirect_uris))return!0;let r=new Set(e.redirect_uris||[]);return t.redirect_uris.every(n=>r.has(n))}function ot(){return Et()}function it(e){if(!e.store){if(!e.issuer)throw m("Must supply options.issuer or options.store to get the id_token");e.store=te(e.issuer)}return e.store.get("id_token")}function st(e){if(!e.store){if(!e.issuer)throw m("Must supply options.issuer or options.store to get the id_token claims");e.store=te(e.issuer)}return e.store.get("id_token_claims")}var gn={oidcmw:Ke,discover:Q,register:ee,isRedirected:ot,idToken:it,idTokenClaims:st},at=gn;var ct=Object.assign({},D,globalThis.metro||{});ct.oidc||(ct.oidc=at);globalThis.metro=ct;var Wi=at;})();
|
|
1
|
+
(()=>{var wr=Object.defineProperty;var Rt=(e,t)=>{for(var r in t)wr(e,r,{get:t[r],enumerable:!0})};var N={};Rt(N,{Client:()=>me,client:()=>C,deepClone:()=>ye,metroError:()=>l,request:()=>L,response:()=>Ne,url:()=>S});var ee="https://metro.muze.nl/details/";Symbol.metroProxy||(Symbol.metroProxy=Symbol("isProxy"));Symbol.metroSource||(Symbol.metroSource=Symbol("source"));var me=class e{clientOptions={url:S(typeof window<"u"?window.location:"https://localhost"),verbs:["get","post","put","delete","patch","head","options","query"]};static tracers={};constructor(...t){for(let r of t)if(typeof r=="string"||r instanceof String)this.clientOptions.url=S(this.clientOptions.url.href,r);else if(r instanceof e)Object.assign(this.clientOptions,r.clientOptions);else if(r instanceof Function)this.#e([r]);else if(r&&typeof r=="object")for(let n in r)n=="middlewares"?this.#e(r[n]):n=="url"?this.clientOptions.url=S(this.clientOptions.url.href,r[n]):typeof r[n]=="function"?this.clientOptions[n]=r[n](this.clientOptions[n],this.clientOptions):this.clientOptions[n]=r[n];for(let r of this.clientOptions.verbs)this[r]=async function(...n){return this.fetch(L(this.clientOptions,...n,{method:r.toUpperCase()}),xr(...n))}}#e(t){typeof t=="function"&&(t=[t]);let r=t.findIndex(n=>typeof n!="function");if(r>=0)throw l("metro.client: middlewares must be a function or an array of functions "+ee+"client/invalid-middlewares/",t[r]);Array.isArray(this.clientOptions.middlewares)||(this.clientOptions.middlewares=[]),this.clientOptions.middlewares=this.clientOptions.middlewares.concat(t)}fetch(t,r){if(t=L(t,r),!t.url)throw l("metro.client."+t.method.toLowerCase()+": Missing url parameter "+ee+"client/fetch-missing-url/",t);if(r||(r={}),typeof r!="object"||r instanceof String)throw l("metro.client.fetch: Invalid options parameter "+ee+"client/fetch-invalid-options/",r);r=Object.assign({},this.clientOptions,r);let n=Rr(t,r),o=Tr(this,r,n),i=this.clientOptions?.middlewares||[];return br(i,n,o)(t)}with(...t){return new e(ye(this.clientOptions),...t)}get location(){return this.clientOptions.url}};async function gr(e){e[Symbol.metroProxy]&&(e=e[Symbol.metroSource]);let t=await fetch(e);return Ne(t)}function br(e,t,r){let n;for(let o of[gr,...e])n=Sr(o,n,t,r);return n}function Sr(e,t,r,n){let o=r.tracers;return async function(i){he(o,"request",i,e,r);let s;try{s=await e(i,t,n)}catch(a){throw he(o,"error",a,i,e,r),a}return he(o,"response",s,e,r),s}}var Er=0,Ar=["trace","tracer","tracers"];function xr(...e){let t={};for(let r of e)if(Tt(r))for(let n of Ar)n in r&&(t[n]=r[n]);return t}function Rr(e,t={}){let r=Pr(t.trace||t.tracer||t.tracers),n=[];r?n=r.localTracers||[]:n=pe(t.trace).concat(pe(t.tracer)).concat(pe(t.tracers));let o=Object.values(me.tracers||{});return{__metroTraceContext:!0,id:"metro-trace-context-"+ ++Er,parent:r,request:e,options:t,globalTracers:o,localTracers:n,tracers:o.concat(n)}}function Pr(e){return e?e.context?.__metroTraceContext?e.context:e.__metroTraceContext?e:null:null}function pe(e){return!e||e.__metroTraceContext||e.context?.__metroTraceContext?[]:Array.isArray(e)?e.flatMap(pe):kr(e)?[e]:Tt(e)?Object.values(e).flatMap(pe):[]}function kr(e){return e&&typeof e=="object"&&["request","response","error","event","diagnostic","span","link","current"].some(t=>typeof e[t]=="function")}function Tr(e,t,r){let n=Kr(r);return Object.freeze({client:e,options:t,trace:n,fetch(o,i={}){return e.fetch(o,Object.assign({},i,{trace:n}))}})}function Kr(e){let t={__metroTraceContext:!0,context:e,event(r,n={}){he(e.tracers,"event",r,n,e)},diagnostic(r={}){he(e.tracers,"diagnostic",r,e)},current(){for(let r of e.tracers)if(typeof r.current=="function"){let n=r.current(e);if(n)return n}return{traceId:null,spanId:null}},async span(r,n,o={}){let i=e.tracers.find(s=>typeof s.span=="function");return i?Or(i,r,n,o,e):n()},link(r){let n=null;for(let o of e.tracers)typeof o.link=="function"&&(n=o.link(r,void 0,e)||n);return n},options(r={}){return Object.assign({},r,{trace:t})}};return t}function he(e,t,...r){for(let n of e)n&&typeof n[t]=="function"&&vr(n,t,r)}async function Or(e,t,r,n,o){let i=null,s=()=>(i||(i=(async()=>r())()),i);try{await e.span(t,s,n,o)}catch(a){He.error("metro: tracer.span() failed",a)}return s()}function vr(e,t,r){let n=o=>{He.error("metro: tracer."+t+"() failed",o)};try{let o=e[t].call(e,...r);typeof o?.then=="function"&&o.then(void 0,n)}catch(o){n(o)}}function Tt(e){return e&&typeof e=="object"&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null)}function C(...e){return new me(...ye(e))}function Cr(e,t){let r=t||{};!r.url&&t.url&&(r.url=t.url);for(let n of["method","headers","body","mode","credentials","cache","redirect","referrer","referrerPolicy","integrity","keepalive","signal","priority","url"]){let o=e[n];if(!(typeof o>"u"||o==null))if(o?.[Symbol.metroProxy]&&(o=o[Symbol.metroSource]),typeof o=="function")r[n]=o(r[n],r);else if(n=="url")r.url=S(r.url,o);else if(n=="headers"){r.headers=new Headers(t.headers),o instanceof Headers||(o=new Headers(e.headers));for(let[i,s]of o.entries())r.headers.set(i,s)}else r[n]=o}return e instanceof Request&&e.data&&(r.body=e.data),r}function L(...e){let t={url:S(typeof window<"u"?window.location:"https://localhost/"),duplex:"half"};for(let o of e)typeof o=="string"||o instanceof URL||o instanceof URLSearchParams?t.url=S(t.url,o):o&&(o instanceof FormData||o instanceof ReadableStream||o instanceof Blob||o instanceof ArrayBuffer||o instanceof DataView)?t.body=o:o&&typeof o=="object"&&Object.assign(t,Cr(o,t));let r=new Request(t.url,t),n=t.body;return n&&typeof n=="object"&&!(n instanceof String)&&!(n instanceof ReadableStream)&&!(n instanceof Blob)&&!(n instanceof ArrayBuffer)&&!(n instanceof DataView)&&!(n instanceof FormData)&&!(n instanceof URLSearchParams)&&globalThis.ArrayBuffer&&ArrayBuffer.isView(n)&&typeof n.toString=="function"&&(t.body=n.toString({headers:r.headers}),r=new Request(t.url,t)),Object.freeze(r),new Proxy(r,{get(o,i){let s;switch(i){case Symbol.metroSource:s=o;break;case Symbol.metroProxy:s=!0;break;case"with":s=function(...a){return typeof n<"u"&&a.unshift({body:n}),L(o,...a)};break;case"data":s=n;break;default:o[i]instanceof Function?i==="clone"?s=function(){let a=o.clone();return typeof n<"u"&&!(typeof ReadableStream<"u"&&n instanceof ReadableStream)?L(a,{body:n}):L(a)}:s=o[i].bind(o):s=o[i];break}return s}})}function Pt(e,t){let r=t||{};!r.url&&t.url&&(r.url=t.url);for(let n of["status","statusText","headers","body","url","type","redirected"]){let o=e[n];typeof o>"u"||o==null||(o?.[Symbol.metroProxy]&&(o=o[Symbol.metroSource]),typeof o=="function"?r[n]=o(r[n],r):n=="url"?r.url=new URL(o,r.url||"https://localhost/"):r[n]=o)}return e instanceof Response&&e.data&&(r.body=e.data),r}function Ne(...e){let t={};for(let o of e)typeof o=="string"?t.body=o:o instanceof Response?Object.assign(t,Pt(o,t)):o&&typeof o=="object"&&(o instanceof FormData||o instanceof Blob||o instanceof ArrayBuffer||o instanceof DataView||o instanceof ReadableStream||o instanceof URLSearchParams||o instanceof String||typeof globalThis.TypedArray<"u"&&o instanceof globalThis.TypedArray?t.body=o:Object.assign(t,Pt(o,t)));let r;t.body&&(r=t.body),[101,204,205,304].includes(t.status)&&(t.body=null);let n=new Response(t.body,t);return Object.freeze(n),new Proxy(n,{get(o,i){let s;switch(i){case Symbol.metroProxy:s=!0;break;case Symbol.metroSource:s=o;break;case"with":s=function(...a){return Ne(o,...a)};break;case"data":s=r;break;case"ok":s=o.status>=200&&o.status<300;break;default:typeof o[i]=="function"?s=o[i].bind(o):s=o[i];break}return s}})}function kt(e,t){typeof t=="function"?t(e.searchParams,e):(t=new URLSearchParams(t),t.forEach((r,n)=>{e.searchParams.append(n,r)}))}function Ir(e,t){let r=e[Symbol.metroSource]||e;t instanceof URLSearchParams||(t=new URLSearchParams(t));let n=r.hash||"#";return n+="?"+t,S(r,{hash:n})}function S(...e){let t=["hash","fragment","host","hostname","href","password","pathname","port","protocol","username","search","searchParams","hashParams"],r=new URL("https://localhost/"),n=null;for(let o of e)if(typeof o=="string"||o instanceof String)r=new URL(o,r);else if(o instanceof URL||typeof Location<"u"&&o instanceof Location)r=new URL(o);else if(o instanceof URLSearchParams)kt(r,o);else if(o&&typeof o=="object")for(let i in o)switch(i){case"search":typeof o.search=="function"?o.search(r.search,r):r.search=new URLSearchParams(o.search);break;case"searchParams":kt(r,o.searchParams);break;default:if(!t.includes(i))throw l("metro.url: unknown url parameter "+ee+"url/unknown-param-name/",i);if(i=="fragment"){let s=o.fragment;s&&typeof s=="string"&&s[0]!="#"&&(s="#"+s),o.hash=s,i="hash"}else i=="hashParams"&&(n=o.hashParams);if(typeof o[i]=="function")o[i](r[i],r);else if(typeof o[i]=="string"||o[i]instanceof String||typeof o[i]=="number"||o[i]instanceof Number||typeof o[i]=="boolean"||o[i]instanceof Boolean)r[i]=""+o[i];else if(typeof o[i]=="object"&&o[i].toString)r[i]=o[i].toString();else throw l("metro.url: unsupported value for "+i+" "+ee+"url/unsupported-param-value/",e[i]);break}else throw l("metro.url: unsupported option value "+ee+"url/unsupported-option-value/",o);return n&&(r.hash||(r.hash="#"),typeof n=="string"?r.hash+=n:r=Ir(r,n)),Object.freeze(r),new Proxy(r,{get(o,i){let s;switch(i){case Symbol.metroProxy:s=!0;break;case Symbol.metroSource:s=o;break;case"with":s=function(...a){return S(o,...a)};break;case"filename":s=o.pathname.split("/").pop();break;case"folderpath":s=o.pathname.substring(0,o.pathname.lastIndexOf("/")+1);break;case"authority":s=o.username??"",s+=o.password?":"+o.password:"",s+=s?"@":"",s+=o.hostname,s+=o.port?":"+o.port:"",s+="/",s=o.protocol+"//"+s;break;case"fragment":s=o.hash.substring(1);break;case"scheme":o.protocol?s=o.protocol.substring(0,o.protocol.length-1):s="";break;default:o[i]instanceof Function?s=o[i].bind(o):s=o[i];break}return s}})}var He={error:(e,...t)=>{console.error("\u24C2\uFE0F ",e,...t)},info:(e,...t)=>{console.info("\u24C2\uFE0F ",e,...t)},group:e=>{console.group("\u24C2\uFE0F "+e)},groupEnd:e=>{console.groupEnd("\u24C2\uFE0F "+e)}};function l(e,...t){return He.error(e,...t),new Error(e,...t)}function ye(e){if(Array.isArray(e))return e.slice().map(ye);if(e&&typeof e=="object")if(e.__proto__?.constructor==Object||!e.__proto__){let t=Object.assign({},e);return Object.keys(t).forEach(r=>{t[r]=ye(e[r])}),t}else return e;return e}var Ve={};Rt(Ve,{Optional:()=>u,Recommended:()=>re,Required:()=>b,allOf:()=>Be,anyOf:()=>Y,assert:()=>k,disable:()=>Dr,enable:()=>Wr,error:()=>g,fails:()=>O,formatIssue:()=>vt,formatIssues:()=>Ct,instanceOf:()=>q,issues:()=>Mr,not:()=>ne,oneOf:()=>T,validEmail:()=>Fe,validURL:()=>w,warn:()=>It});var je=!1;function Wr(){je=!0}function Dr(){je=!1}function G(e="",t){return(typeof e>"u"||e==null)&&(e=""),typeof t=="number"?`${e}[${t}]`:`${e}.${t}`}function Kt(e=""){if(Array.isArray(e))return e;if(!e)return[];let t=[],r=/(?:^|\.)([^.\[\]]+)|\[(\d+)\]/g,n;for(;n=r.exec(e);)typeof n[1]<"u"?t.push(n[1]):typeof n[2]<"u"&&t.push(Number(n[2]));return t}function ze(e=[]){return typeof e=="string"?e.startsWith(".")?e.slice(1):e:e.map((t,r)=>typeof t=="number"?`[${t}]`:`${r?".":""}${t}`).join("")}function Me(e){return e===String?"string":e===Number?"number":e===Boolean?"boolean":e.name||"function"}function Ot(e,t=60){return e.length<=t?e:e.slice(0,t-1)+"\u2026"}function Jr(e){return`'${Ot(String(e).replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\n/g,"\\n"))}'`}function Ur(e){try{let r=JSON.stringify(e);if(typeof r=="string")return Ot(r)}catch{}let t=e?.constructor?.name;return t&&t!="Object"?t:Object.prototype.toString.call(e)}function te(e){return typeof e=="string"?Jr(e):typeof e>"u"?"undefined":e===null?"null":typeof e=="function"?Me(e):e instanceof RegExp?e.toString():typeof e=="number"||typeof e=="boolean"||typeof e=="bigint"?String(e):typeof e=="symbol"?e.toString():Ur(e)}function X(e){return e===String||e===Number||e===Boolean||typeof e=="function"?Me(e):e instanceof RegExp?e.toString():Array.isArray(e)?"["+e.map(X).join(", ")+"]":te(e)}function Lr(e){return e.map(X).join(", ")}function Nr(e,t,r){return e=="data and pattern are not equal"?`expected ${te(r)}, found ${te(t)}`:e=="data does not match pattern"||/^data\[\d+\] does not match pattern$/.test(e)?`expected ${X(r)}, found ${te(t)}`:e=="data is undefined, should match pattern"?`missing; expected ${X(r)}`:e=="data is required"?"required":e=="data is an empty string, which is not allowed"?"empty string is not allowed":e=="data is not an object, pattern is"?"data is not an object":e=="data is not an instanceof pattern"?`expected instance of ${X(r)}, found ${te(t)}`:e=="data does not match oneOf patterns"||e=="data does not match anyOf patterns"?`expected one of ${Lr(r)}, found ${te(t)}`:e=="data matches pattern, when required not to"?`must not match ${X(r)}`:e}function vt(e,t={}){if(!e||typeof e!="object")return String(e);let r=e.pathString||ze(e.path||[])||"value";return`${t.indent??""}${r}: ${e.message}`}function Ct(e,t={}){if(!e)return!1;let r=t.indent??" - ";return(Array.isArray(e)?e:[e]).map(n=>vt(n,{...t,indent:r}))}function Hr(e){if(!e||typeof e!="object")return{path:[],pathString:"",message:String(e),expected:void 0,actual:void 0};let t=Kt(e.path),r=ze(t),n=e.actual??e.found,o=X(e.expected),i=Nr(e.message,n,e.expected);return{path:t,pathString:r,message:i,expected:o,actual:n}}function $e(e){if(!e)return[];let t=[];for(let r of Array.isArray(e)?e:[e])if(r){if(r&&typeof r=="object"&&r.problems){let n=$e(r.problems);if(n.length){t=t.concat(n);continue}}t.push(Hr(r))}return t}function k(e,t){if(je){let r=O(e,t);if(r){let n=$e(r),i=`Assertions failed:
|
|
2
|
+
`+Ct(n).join(`
|
|
3
|
+
`);throw console.error("\u{1F170}\uFE0F "+i),new Error(i,{cause:{problems:r,issues:n,source:e}})}}}function u(e){return function(r,n,o){if(typeof r<"u"&&r!=null&&typeof e<"u")return O(r,e,n,o)}}function b(e){return function(r,n,o){return r==null||typeof r>"u"?g("data is required",r,e||"any value",o):typeof e<"u"?O(r,e,n,o):!1}}function re(e){return function(r,n,o){return r==null||typeof r>"u"?(It("data does not contain recommended value",r,e,o),!1):O(r,e,n,o)}}function T(...e){return function(r,n,o){for(let i of e)if(!O(r,i,n,o))return!1;return g("data does not match oneOf patterns",r,e,o)}}function Y(...e){return function(r,n,o){if(!Array.isArray(r))return g("data is not an array",r,"anyOf",o);for(let[i,s]of r.entries()){let a=G(o,i);if(T(...e)(s,n,a))return g("data does not match anyOf patterns",s,e,a)}return!1}}function Be(...e){return function(r,n,o){let i=[];for(let s of e)i=i.concat(O(r,s,n,o));if(i=i.filter(Boolean),i.length)return g("data does not match all given patterns",r,e,o,i)}}function w(e,t,r){try{e instanceof URL&&(e=e.href);let n=new URL(e);if(n.href!=e&&!(n.href+"/"==e||n.href==e+"/"))return g("data is not a valid url",e,"validURL",r)}catch{return g("data is not a valid url",e,"validURL",r)}}function Fe(e,t,r){if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e))return g("data is not a valid email",e,"validEmail",r)}function q(e){return function(r,n,o){if(!(r instanceof e))return g("data is not an instanceof pattern",r,e,o)}}function ne(e){return function(r,n,o){if(!O(r,e,n,o))return g("data matches pattern, when required not to",r,e,o)}}function Mr(e,t,r){let n=O(e,t,r);return n?$e(n):!1}function O(e,t,r,n=""){typeof r>"u"&&(r=e);let o=[];if(t===Boolean)typeof e!="boolean"&&!(e instanceof Boolean)&&o.push(g("data is not a boolean",e,t,n));else if(t===Number)typeof e!="number"&&!(e instanceof Number)&&o.push(g("data is not a number",e,t,n));else if(t===String)typeof e!="string"&&!(e instanceof String)&&o.push(g("data is not a string",e,t,n)),e==""&&o.push(g("data is an empty string, which is not allowed",e,t,n));else if(t instanceof RegExp)if(Array.isArray(e)){let i=e.findIndex((s,a)=>O(s,t,r,G(n,a)));i>-1&&o.push(g("data["+i+"] does not match pattern",e[i],t,G(n,i)))}else typeof e>"u"?o.push(g("data is undefined, should match pattern",e,t,n)):t.test(e)||o.push(g("data does not match pattern",e,t,n));else if(t instanceof Function){let i=t(e,r,n);i&&(Array.isArray(i)?o=o.concat(i):o.push(i))}else if(Array.isArray(t))if(!Array.isArray(e))o.push(g("data is not an array",e,[],n));else for(let i of t)for(let s of e.keys()){let a=O(e[s],i,r,G(n,s));Array.isArray(a)?o=o.concat(a):a&&o.push(a)}else if(t&&typeof t=="object")if(Array.isArray(e)){let i=e.findIndex((s,a)=>O(s,t,r,G(n,a)));i>-1&&o.push(g("data["+i+"] does not match pattern",e[i],t,G(n,i)))}else if(!e||typeof e!="object")o.push(g("data is not an object, pattern is",e,t,n));else if(e instanceof URLSearchParams&&(e=Object.fromEntries(e)),t instanceof Function){let i=O(e,t,r,n);i&&(o=o.concat(i))}else for(let[i,s]of Object.entries(t)){let a=O(e[i],s,r,G(n,i));a&&(o=o.concat(a))}else t!=e&&o.push(g("data and pattern are not equal",e,t,n));return o.length?o:!1}function g(e,t,r,n="",o){let i=Kt(n),s={path:n,pathString:ze(i),pathParts:i,message:e,found:t,expected:r};return o&&(s.problems=o),s}function It(e,t,r,n){console.warn("\u{1F170}\uFE0F Assert: "+n,e,r,t)}globalThis.assert={...Ve};function Wt(e){let t,r;if(typeof localStorage<"u")t={get:()=>localStorage.getItem("metro/state:"+e),set:n=>localStorage.setItem("metro/state:"+e,n),has:()=>localStorage.getItem("metro/state:"+e)!==null,delete:()=>localStorage.removeItem("metro/state:"+e)},r={get:n=>JSON.parse(localStorage.getItem(e+":"+n)),set:(n,o)=>localStorage.setItem(e+":"+n,JSON.stringify(o)),has:n=>localStorage.getItem(e+":"+n)!==null,delete:n=>localStorage.removeItem(e+":"+n)};else{let n=new Map;t={get:()=>n.get("metro/state:"+e),set:o=>n.set("metro/state:"+e,o),has:()=>n.has("metro/state:"+e),delete:()=>n.delete("metro/state:"+e)},r=new Map}return{state:t,tokens:r}}var xe=new Map,jr=new Map([["bearer","Bearer"],["dpop","DPoP"]]),zr=new Set(["none","client_secret_post","client_secret_basic"]);function Xe(e){let t={client:C(),force_authorization:!1,site:"default",oauth2_configuration:{authorization_endpoint:"/authorize",token_endpoint:"/token",redirect_uri:globalThis.document?.location.href,grant_type:"authorization_code",code_verifier:Ye(64)},authorize_callback:async c=>(window.location.href!=c.href&&window.location.replace(c.href),!1)};k(e,{});let r=Object.assign({},t.oauth2_configuration,e?.oauth2_configuration);e=Object.assign({},t,e),e.oauth2_configuration=r;let n=e.tokens??"site:"+e.site,o=Wt(e.site);e.tokens||(e.tokens=o.tokens),e.state||(e.state=o.state),k(e,{oauth2_configuration:{client_id:b(/.+/),grant_type:"authorization_code",authorization_endpoint:b(w),token_endpoint:b(w),redirect_uri:b(w)}});for(let c in r)switch(c){case"access_token":case"authorization_code":case"refresh_token":e.tokens.set(c,$r(c,r[c]));break}return async function(c,f){if(e.force_authorization)return i(c,f);let m=await f(c);return m.ok||!Dt(m)?m:i(c,f)};async function i(c,f,m={}){a();let _=e.tokens.get("access_token"),P=e.tokens.get("refresh_token"),Ee=Yr(_);if(!_||Ee&&!P){if(!await s(p))throw Ge(c);return i(c,f)}else if(Ee&&P){if(!await s(d))throw Ge(c);return i(c,f)}else{let Ae=L(c,{headers:{Authorization:_.type+" "+_.value}}),Q=await f(Ae);if(!Dt(Q)||m.handledRejectedToken)return Q;if(e.tokens.get("access_token")?.value!==_.value)return i(c,f,{handledRejectedToken:!0});e.tokens.delete("access_token");let J=p;if(P&&(J=d),!await s(J))throw Ge(c);return i(c,f,{handledRejectedToken:!0})}}function s(c){if(!xe.has(n)){let f=c().finally(()=>{xe.delete(n)});xe.set(n,f)}return xe.get(n)}function a(){if(typeof window<"u"&&window?.location){let c=S(window.location),f,m,_;if(c.searchParams.has("code")||c.searchParams.has("error"))_=c.searchParams,c=c.with({search:""}),history.pushState({},"",c.href);else if(c.hash){let P=c.hash.substr(1);_=new URLSearchParams("?"+P),c=c.with({hash:""}),history.pushState({},"",c.href)}if(_){if(R(_.get("iss")),_.has("error"))throw l("oauth2mw: authorization failed: "+_.get("error")+(_.get("error_description")?" ("+_.get("error_description")+")":""));f=_.get("code"),m=_.get("state"),W(m),f&&e.tokens.set("authorization_code",f)}}}async function p(){if(r.grant_type==="authorization_code"&&!e.tokens.has("authorization_code")){let _=await y();if(!e.authorize_callback||typeof e.authorize_callback!="function")throw l("oauth2mw: oauth2 with grant_type:authorization_code requires a callback function in client options.authorize_callback");let P=await e.authorize_callback(_);if(P)K(P);else return!1}let c=h(),f=await e.client.post(c);if(!f.ok){let _=await f.text();throw l("OAuth2mw: fetch access_token: "+f.status+": "+f.statusText+" ("+_+")",{cause:c})}let m=await f.json();return V(m),e.tokens.delete("authorization_code"),m}async function d(){let c=h("refresh_token"),f=await e.client.post(c);if(!f.ok){let _=await f.text();throw l("OAuth2mw: refresh access_token: "+f.status+": "+f.statusText+" ("+_+")",{cause:c})}let m=await f.json();return V(m),m}async function y(){if(!r.authorization_endpoint)throw l("oauth2mw: Missing options.oauth2_configuration.authorization_endpoint");let c=S(r.authorization_endpoint,{hash:""});k(r,{client_id:/.+/,redirect_uri:/.+/,scope:/.*/});let f={response_type:"code",client_id:r.client_id,redirect_uri:r.redirect_uri,state:r.state||Qr(40)};return r.response_type&&(f.response_type=r.response_type),r.response_mode&&(f.response_mode=r.response_mode),e.state.set(f.state),r.code_verifier&&(e.tokens.set("code_verifier",r.code_verifier),f.code_challenge=await Zr(r.code_verifier),f.code_challenge_method="S256"),r.scope&&(f.scope=r.scope),r.prompt&&(f.prompt=r.prompt),r.login_hint&&(f.login_hint=r.login_hint),r.nonce&&(f.nonce=r.nonce),S(c,{search:f})}function h(c=null){if(k(r,{client_id:/.+/,redirect_uri:/.+/}),!r.token_endpoint)throw l("oauth2mw: Missing options.endpoints.token url");let f=S(r.token_endpoint,{hash:""}),m={grant_type:c||r.grant_type},_={};switch(A(m,_),r.scope&&(m.scope=r.scope),m.grant_type){case"authorization_code":m.redirect_uri=r.redirect_uri,m.code=e.tokens.get("authorization_code");let P=e.tokens.get("code_verifier");P&&(m.code_verifier=P);break;case"client_credentials":break;case"refresh_token":m.refresh_token=Xr(e.tokens.get("refresh_token"));break;default:throw new Error("Unknown grant_type: "+m.grant_type)}return L(f,{method:"POST",headers:_,body:new URLSearchParams(m)})}function A(c,f){let m=Fr(r);if(m==="none"){c.client_id=r.client_id;return}if(!r.client_secret)throw l("oauth2mw: token_endpoint_auth_method "+m+" requires oauth2_configuration.client_secret");if(m==="client_secret_post"){c.client_id=r.client_id,c.client_secret=r.client_secret;return}if(m==="client_secret_basic"){f.Authorization=Vr(r.client_id,r.client_secret);return}}function K(c){let f=c;if(c&&typeof c=="object"){if(R(c.iss),c.error)throw l("oauth2mw: authorization failed: "+c.error);W(c.state),f=c.authorization_code||c.code}if(!f)throw l("oauth2mw: authorization callback did not return an authorization code");e.tokens.set("authorization_code",f)}function R(c){if(r.issuer){if(!c){if(r.authorization_response_iss_parameter_supported)throw l("oauth2mw: authorization response is missing iss, expected "+r.issuer);return}if(c!==r.issuer)throw l("oauth2mw: authorization response is from issuer "+c+", expected "+r.issuer)}}function W(c){let f=e.state.get();if(!c||c!==f)throw l("oauth2mw: authorization state mismatch")}function V(c){let f=Br(c,r.token_type);e.tokens.set("access_token",f),c.refresh_token&&e.tokens.set("refresh_token",{value:c.refresh_token})}}function Dt(e){if(!e)return!1;let t=Ze(e.headers?.get("WWW-Authenticate"));return e.status===400?t?.error==="invalid_token":t?.error==="insufficient_scope"?!1:e.status===401}function $r(e,t){return e==="access_token"&&t&&typeof t=="object"?t:e==="access_token"?{value:t,type:"Bearer",expires:null}:t}function Br(e,t){if(!e||typeof e!="object")throw l("OAuth2mw: token endpoint did not return a JSON object");if(!e.access_token)throw l("OAuth2mw: token response did not include access_token");if(!e.token_type)throw l("OAuth2mw: token response did not include token_type");let r=Jt(e.token_type);if(t&&r!==Jt(t))throw l("OAuth2mw: token endpoint returned a "+r+" token, but "+t+" is required");return{value:e.access_token,expires:e.expires_in===void 0?null:qr(e.expires_in),type:r,scope:e.scope}}function Jt(e){let t=jr.get(String(e).toLowerCase());if(!t)throw l("OAuth2mw: unsupported token_type "+e);return t}function Fr(e){let t=e.token_endpoint_auth_method||(e.client_secret?"client_secret_post":"none");if(!zr.has(t))throw l("oauth2mw: unsupported token_endpoint_auth_method "+t);return t}function Vr(e,t){let r=Ut(e)+":"+Ut(t);return"Basic "+Gr(r)}function Ut(e){return encodeURIComponent(e).replace(/%20/g,"+")}function Gr(e){return typeof btoa=="function"?btoa(e):Buffer.from(e,"binary").toString("base64")}function Xr(e){return e&&typeof e=="object"?e.value:e}function Yr(e){if(!e)return!0;if(!e.expires)return!1;let t=new Date(e.expires);return new Date().getTime()>t.getTime()}function qr(e){if(e instanceof Date)return new Date(e.getTime());if(typeof e=="number"){let t=new Date;return t.setSeconds(t.getSeconds()+e),t}throw new TypeError("Unknown expires type "+e)}function Ye(e=64){let t=new Uint8Array(e);return globalThis.crypto.getRandomValues(t),qe(t)}async function Zr(e){let r=new TextEncoder().encode(e),n=await globalThis.crypto.subtle.digest("SHA-256",r);return qe(n)}function qe(e){let t=Array.from(new Uint8Array(e),r=>String.fromCharCode(r)).join("");return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Qr(e){let t=new Uint8Array(Math.ceil(e*3/4)+1);if(globalThis.crypto?.getRandomValues)return globalThis.crypto.getRandomValues(t),qe(t).slice(0,e);let r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n="",o=0;for(;o<e;)n+=r.charAt(Math.floor(Math.random()*r.length)),o++;return n}function Ge(e){let t=new Error("oauth2mw: authorization was not completed for "+e.url+"; no access token was obtained");return t.code="authorization_not_completed",t.request=e,t}function Lt(){let e=new URL(document.location.href);if(!e.searchParams.has("code")){if(e.hash){let t=e.hash.substr(1);if(new URLSearchParams("?"+t).has("code"))return!0}return!1}return!0}function Ze(e){if(!e||typeof e!="string")return null;let t=e.trim(),r=t.search(/\s/),n=r<0?t:t.slice(0,r),o=r<0?"":t.slice(r+1);if(!["bearer","dpop"].includes(n.toLowerCase()))return null;let i={scheme:n},s=/([A-Za-z][A-Za-z0-9_-]*)=("(?:[^"\\]|\\.)*"|[^,\s]*)/g,a;for(;a=s.exec(o);){let p=a[2];p.startsWith('"')&&p.endsWith('"')&&(p=p.slice(1,-1).replace(/\\"/g,'"')),i[a[1]]=p}return i}var tn=new TextEncoder,rn=new TextDecoder;function Re(e){return typeof e=="string"?tn.encode(e):rn.decode(e)}function Nt(e){if(typeof e.modulusLength!="number"||e.modulusLength<2048)throw new et(`${e.name} modulusLength must be at least 2048 bits`)}function nn(e){switch(e.algorithm.name){case"ECDSA":return{name:e.algorithm.name,hash:"SHA-256"};case"RSA-PSS":return Nt(e.algorithm),{name:e.algorithm.name,saltLength:32};case"RSASSA-PKCS1-v1_5":return Nt(e.algorithm),{name:e.algorithm.name};case"Ed25519":return{name:e.algorithm.name}}throw new z}async function on(e,t,r){if(r.usages.includes("sign")===!1)throw new TypeError('private CryptoKey instances used for signing assertions must include "sign" in their "usages"');let n=`${Pe(Re(JSON.stringify(e)))}.${Pe(Re(JSON.stringify(t)))}`,o=Pe(await crypto.subtle.sign(nn(r),r,Re(n)));return`${n}.${o}`}var Qe;Uint8Array.prototype.toBase64?Qe=e=>(e instanceof ArrayBuffer&&(e=new Uint8Array(e)),e.toBase64({alphabet:"base64url",omitPadding:!0})):Qe=t=>{t instanceof ArrayBuffer&&(t=new Uint8Array(t));let r=[];for(let n=0;n<t.byteLength;n+=32768)r.push(String.fromCharCode.apply(null,t.subarray(n,n+32768)));return btoa(r.join("")).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")};function Pe(e){return Qe(e)}var z=class extends Error{constructor(t){var r;super(t??"operation not supported"),this.name=this.constructor.name,(r=Error.captureStackTrace)===null||r===void 0||r.call(Error,this,this.constructor)}},et=class extends Error{constructor(t){var r;super(t),this.name=this.constructor.name,(r=Error.captureStackTrace)===null||r===void 0||r.call(Error,this,this.constructor)}};function sn(e){if(e.algorithm.hash.name==="SHA-256")return"PS256";throw new z("unsupported RsaHashedKeyAlgorithm hash name")}function an(e){if(e.algorithm.hash.name==="SHA-256")return"RS256";throw new z("unsupported RsaHashedKeyAlgorithm hash name")}function cn(e){if(e.algorithm.namedCurve==="P-256")return"ES256";throw new z("unsupported EcKeyAlgorithm namedCurve")}function un(e){switch(e.algorithm.name){case"RSA-PSS":return sn(e);case"RSASSA-PKCS1-v1_5":return an(e);case"ECDSA":return cn(e);case"Ed25519":return"Ed25519";default:throw new z("unsupported CryptoKey algorithm name")}}function Ht(e){return e instanceof CryptoKey}function fn(e){return Ht(e)&&e.type==="private"}function ln(e){return Ht(e)&&e.type==="public"}function dn(){return Math.floor(Date.now()/1e3)}async function tt(e,t,r,n,o,i){let s=e?.privateKey,a=e?.publicKey;if(!fn(s))throw new TypeError('"keypair.privateKey" must be a private CryptoKey');if(!ln(a))throw new TypeError('"keypair.publicKey" must be a public CryptoKey');if(a.extractable!==!0)throw new TypeError('"keypair.publicKey.extractable" must be true');if(typeof t!="string")throw new TypeError('"htu" must be a string');if(typeof r!="string")throw new TypeError('"htm" must be a string');if(n!==void 0&&typeof n!="string")throw new TypeError('"nonce" must be a string or undefined');if(o!==void 0&&typeof o!="string")throw new TypeError('"accessToken" must be a string or undefined');if(i!==void 0&&(typeof i!="object"||i===null||Array.isArray(i)))throw new TypeError('"additional" must be an object');return on({alg:un(s),typ:"dpop+jwt",jwk:await pn(a)},Object.assign(Object.assign({},i),{iat:dn(),jti:crypto.randomUUID(),htm:r,nonce:n,htu:t,ath:o?Pe(await crypto.subtle.digest("SHA-256",Re(o))):void 0}),s)}async function pn(e){let{kty:t,e:r,n,x:o,y:i,crv:s}=await crypto.subtle.exportKey("jwk",e);return{kty:t,crv:s,e:r,n,x:o,y:i}}async function Mt(e,t){var r;let n;if(typeof e!="string"||e.length===0)throw new TypeError('"alg" must be a non-empty string');switch(e){case"PS256":n={name:"RSA-PSS",hash:"SHA-256",modulusLength:2048,publicExponent:new Uint8Array([1,0,1])};break;case"RS256":n={name:"RSASSA-PKCS1-v1_5",hash:"SHA-256",modulusLength:2048,publicExponent:new Uint8Array([1,0,1])};break;case"ES256":n={name:"ECDSA",namedCurve:"P-256"};break;case"Ed25519":n={name:"Ed25519"};break;default:throw new z}return crypto.subtle.generateKey(n,(r=t?.extractable)!==null&&r!==void 0?r:!1,["sign","verify"])}function rt(){return new Promise((e,t)=>{let r=globalThis.indexedDB.open("metro",1);r.onupgradeneeded=()=>r.result.createObjectStore("keyPairs",{keyPath:"domain"}),r.onerror=n=>{t(n)},r.onsuccess=n=>{let o=n.target.result;e({set:function(i,s){return new Promise((a,p)=>{let d=o.transaction("keyPairs","readwrite",{durability:"strict"}),y=d.objectStore("keyPairs");d.oncomplete=()=>{a()},d.onerror=p,y.put(i,s)})},get:function(i){return new Promise((s,a)=>{let p=o.transaction("keyPairs","readonly"),y=p.objectStore("keyPairs").get(i);y.onsuccess=()=>{s(y.result)},y.onerror=a,p.onerror=a})},clear:function(){return new Promise((i,s)=>{let a=o.transaction("keyPairs","readwrite"),d=a.objectStore("keyPairs").clear();d.onsuccess=()=>{i()},d.onerror=s,a.onerror=s})}})}})}var zt=new Map;function nt(e){return k(e,{site:b(w),token_endpoint:b(w),dpop_signing_alg_values_supported:u([])}),async(n,o)=>{let i=await mn(e.site),s=S(n.url).origin,a=await o(await r(n,i));return jt(s,a),t(n)&&await _n(a)&&(a=await o(await r(n,i)),jt(s,a)),a};function t(n){return n.url.startsWith(e.token_endpoint)||wn(n.headers.get("Authorization"))}async function r(n,o){if(!t(n))return n;let i=zt.get(S(n.url).origin),s=yn(n.url);if(n.url.startsWith(e.token_endpoint)){let d=await tt(o,s,n.method,i);return n.with({headers:{DPoP:d}})}let a=n.headers.get("Authorization").split(" ")[1],p=await tt(o,s,n.method,i,a);return n.with({headers:{Authorization:"DPoP "+a,DPoP:p}})}}async function mn(e){let t=await rt(),r=await t.get(e);if(!r){let n=await Mt("ES256");r={domain:e,keyPair:n},await t.set(r)}return r.keyPair}function yn(e){let t=new URL(e);return t.search="",t.hash="",t.href}function jt(e,t){let r=t.headers.get("DPoP-Nonce");r&&zt.set(e,r)}async function _n(e){return e.headers.get("DPoP-Nonce")?e.status==401?Ze(e.headers.get("WWW-Authenticate"))?.error=="use_dpop_nonce":e.status==400?(await e.clone().json().catch(()=>null))?.error=="use_dpop_nonce":!1:!1}function wn(e){return/^DPoP\s/i.test(e||"")}function H(e){return e=Object.assign({contentType:"application/json",reviver:null,replacer:null,space:""},e),async function(r,n){if(r.headers.get("Accept")||(r=r.with({headers:{Accept:e.accept??e.contentType}})),r.method!=="GET"&&r.method!=="HEAD"&&r.data&&typeof r.data=="object"&&!(r.data instanceof ReadableStream)){let i=r.headers.get("Content-Type");(!i||Sn(i))&&(r=r.with({headers:{"Content-Type":e.contentType}})),$t(r.headers.get("Content-Type"))&&(r=r.with({body:JSON.stringify(r.data,e.replacer,e.space)}))}let o=await n(r);if(o&&$t(o.headers?.get("Content-Type"))){let s=await o.clone().text();if(s==="")return o;try{let a=JSON.parse(s,e.reviver);return o.with({body:a})}catch(a){if(!o.ok)return o;throw gn(r,o,a)}}return o}}function gn(e,t,r){let n="jsonmw: could not parse "+t.headers.get("Content-Type")+" response from "+e.url,o=new Error(n,{cause:r});return o.request=e,o.response=t,o}var bn=/^application\/([a-zA-Z0-9\-_]+\+)?json\b/;function $t(e){return bn.exec(e)}function Sn(e){return/^text\/plain\b/.exec(e)}function M(e){return async function(r,n){let o=await n(r);if(!o.ok)if(e&&typeof e[o.status]=="function")o=e[o.status].apply(o,r);else throw new Error(o.status+": "+o.statusText,{cause:o});return o}}var _e=(...e)=>(t,r)=>e.filter(n=>r.hasOwnKey(n)).length>0?!1:g("root data must have all of",r,e),$=(...e)=>t=>Array.isArray(t)&&e.filter(r=>!t.includes(r)).length==0?!1:g("data must be an array which includes",t,e);var D=["HS256","HS384","HS512","RS256","RS384","RS512","ES256","ES384","ES512"],ke=["none","client_secret_post","client_secret_basic","client_secret_jwt","private_key_jwt"];async function oe(e={}){k(e,{client:u(q(C().constructor)),issuer:b(w)});let t={client:C().with(M()).with(H()),requireDynamicRegistration:!1};e=Object.assign({},t,e),e.client=e.client.with(M()).with(H()),Te("issuer",e.issuer);function r(a){return Ft(a)?!1:g("url must use https",a)}let n={issuer:b(Be(e.issuer,r)),authorization_endpoint:b(w),token_endpoint:b(w),userinfo_endpoint:re(w),jwks_uri:b(w),registration_endpoint:e.requireDynamicRegistration?b(w):re(w),scopes_supported:re($("openid")),response_types_supported:e.requireDynamicRegistration?b($("code","id_token","id_token token")):b([]),response_modes_supported:u([]),grant_types_supported:e.requireDynamicRegistration?u($("authorization_code")):u([]),acr_values_supported:u([]),subject_types_supported:b([]),id_token_signing_alg_values_supported:b($("RS256")),id_token_encryption_alg_values_supported:u([]),id_token_encryption_enc_values_supported:u([]),userinfo_signing_alg_values_supported:u([]),userinfo_encryption_alg_values_supported:u([]),userinfo_encryption_enc_values_supported:u([]),request_object_signing_alg_values_supported:u($("RS256")),request_object_encryption_alg_values_supported:u([]),request_object_encryption_enc_values_supported:u([]),token_endpoint_auth_methods_supported:u(Y(...ke)),token_endpoint_auth_signing_alg_values_supported:u($("RS256"),ne($("none"))),display_values_supported:u(Y("page","popup","touch","wap")),claim_types_supported:u(Y("normal","aggregated","distributed")),claims_supported:re([]),service_documentation:u(w),claims_locales_supported:u([]),ui_locales_supported:u([]),claims_parameter_supported:u(Boolean),request_parameter_supported:u(Boolean),request_uri_parameter_supported:u(Boolean),op_policy_uri:u(w),op_tos_uri:u(w)},o=S(e.issuer,".well-known/openid-configuration"),s=(await e.client.get(o)).data;return k(s,n),An(s,e.issuer),s}var En=["authorization_endpoint","token_endpoint","jwks_uri"];function An(e,t){if(!e||typeof e!="object")throw l("metro.oidc.discovery: openid-configuration for "+t+" is not a JSON object");if(!xn(e.issuer,t))throw l("metro.oidc.discovery: openid-configuration is for issuer "+e.issuer+", expected "+t);Te("issuer",e.issuer);for(let r of En){if(!e[r])throw l("metro.oidc.discovery: openid-configuration for "+t+" has no "+r);Te(r,e[r])}e.registration_endpoint&&Te("registration_endpoint",e.registration_endpoint)}function xn(e,t){return typeof e!="string"?!1:Bt(e)===Bt(String(t))}function Bt(e){return e.replace(/\/$/,"")}function Te(e,t){if(!Ft(t))throw l("metro.oidc.discovery: "+e+" must use https: "+t)}function Ft(e){let t;try{t=new URL(String(e))}catch{return!1}return t.protocol=="https:"?!0:t.protocol=="http:"&&Rn(t.hostname)}function Rn(e){return e=="localhost"||e.endsWith(".localhost")||e=="127.0.0.1"||e=="[::1]"}async function ie(e){let t={redirect_uris:b([w]),response_types:u([]),grant_types:u(Y("authorization_code","refresh_token")),application_type:u(T("native","web")),contacts:u([Fe]),client_name:u(String),logo_uri:u(w),client_uri:u(w),policy_uri:u(w),tos_uri:u(w),jwks_uri:u(w,ne(_e("jwks"))),jwks:u(w,ne(_e("jwks_uri"))),sector_identifier_uri:u(w),subject_type:u(String),id_token_signed_response_alg:u(T(...D)),id_token_encrypted_response_alg:u(T(...D)),id_token_encrypted_response_enc:u(T(...D),_e("id_token_encrypted_response_alg")),userinfo_signed_response_alg:u(T(...D)),userinfo_encrypted_response_alg:u(T(...D)),userinfo_encrypted_response_enc:u(T(...D),_e("userinfo_encrypted_response_alg")),request_object_signing_alg:u(T(...D)),request_object_encryption_alg:u(T(...D)),request_object_encryption_enc:u(T(...D)),token_endpoint_auth_method:u(T(...ke)),token_endpoint_auth_signing_alg:u(T(...D)),default_max_age:u(Number),require_auth_time:u(Boolean),default_acr_values:u([String]),initiate_login_uri:u([w]),request_uris:u([w])};k(e,{client:u(q(C().constructor)),registration_endpoint:w,client_info:t});let r={client:C().with(M()).with(H()),client_info:{redirect_uris:[globalThis.document?.location.href]}};e=Object.assign({},r,e),e.client=e.client.with(M()).with(H()),e.client_info||(e.client_info={}),e.client_info.redirect_uris||(e.client_info.redirect_uris=[globalThis.document?.location.href]);let n=await e.client.post(e.registration_endpoint,{body:e.client_info}),o=n.data;if(!o.client_id)throw l("metro.oidc: Error: dynamic registration of client failed, no client_id returned",n);return e.client_info=Object.assign(e.client_info,o),e.client_info}function Z(e){let t;if(typeof localStorage<"u")t={get:r=>JSON.parse(localStorage.getItem("metro/oidc:"+e+":"+r)),set:(r,n)=>localStorage.setItem("metro/oidc:"+e+":"+r,JSON.stringify(n)),has:r=>localStorage.getItem("metro/oidc:"+e+":"+r)!==null};else{let r=new Map;t={get:n=>JSON.parse(r.get("metro/oidc:"+e+":"+n)||null),set:(n,o)=>r.set("metro/oidc:"+e+":"+n,JSON.stringify(o)),has:n=>r.has("metro/oidc:"+e+":"+n)}}return t}var we=new TextEncoder,j=new TextDecoder,Uo=2**32;function Vt(...e){let t=e.reduce((o,{length:i})=>o+i,0),r=new Uint8Array(t),n=0;for(let o of e)r.set(o,n),n+=o.length;return r}function Ke(e){let t=new Uint8Array(e.length);for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);if(n>127)throw new TypeError("non-ASCII string encountered in encode()");t[r]=n}return t}function Gt(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e);let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}function B(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(typeof e=="string"?e:j.decode(e),{alphabet:"base64url"});let t=e;t instanceof Uint8Array&&(t=j.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/");try{return Gt(t)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}}var F=(e,t="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`),se=(e,t)=>e.name===t;function Pn(e){return parseInt(e.name.slice(4),10)}function ot(e,t){if(Pn(e.hash)!==t)throw F(`SHA-${t}`,"algorithm.hash")}function kn(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function Tn(e,t){if(t&&!e.usages.includes(t))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function Xt(e,t,r){switch(t){case"HS256":case"HS384":case"HS512":{if(!se(e.algorithm,"HMAC"))throw F("HMAC");ot(e.algorithm,parseInt(t.slice(2),10));break}case"RS256":case"RS384":case"RS512":{if(!se(e.algorithm,"RSASSA-PKCS1-v1_5"))throw F("RSASSA-PKCS1-v1_5");ot(e.algorithm,parseInt(t.slice(2),10));break}case"PS256":case"PS384":case"PS512":{if(!se(e.algorithm,"RSA-PSS"))throw F("RSA-PSS");ot(e.algorithm,parseInt(t.slice(2),10));break}case"Ed25519":case"EdDSA":{if(!se(e.algorithm,"Ed25519"))throw F("Ed25519");break}case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":{if(!se(e.algorithm,t))throw F(t);break}case"ES256":case"ES384":case"ES512":{if(!se(e.algorithm,"ECDSA"))throw F("ECDSA");let n=kn(t);if(e.algorithm.namedCurve!==n)throw F(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}Tn(e,r)}function Yt(e,t,...r){if(r=r.filter(Boolean),r.length>2){let n=r.pop();e+=`one of type ${r.join(", ")}, or ${n}.`}else r.length===2?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return t==null?e+=` Received ${t}`:typeof t=="function"&&t.name?e+=` Received function ${t.name}`:typeof t=="object"&&t!=null&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}var qt=(e,...t)=>Yt("Key must be ",e,...t),it=(e,t,...r)=>Yt(`Key for the ${e} algorithm must be `,t,...r);var I=class extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(t,r){super(t,r),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}},v=class extends I{static code="ERR_JWT_CLAIM_VALIDATION_FAILED";code="ERR_JWT_CLAIM_VALIDATION_FAILED";claim;reason;payload;constructor(t,r,n="unspecified",o="unspecified"){super(t,{cause:{claim:n,reason:o,payload:r}}),this.claim=n,this.reason=o,this.payload=r}},ge=class extends I{static code="ERR_JWT_EXPIRED";code="ERR_JWT_EXPIRED";claim;reason;payload;constructor(t,r,n="unspecified",o="unspecified"){super(t,{cause:{claim:n,reason:o,payload:r}}),this.claim=n,this.reason=o,this.payload=r}},Oe=class extends I{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"},x=class extends I{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"};var E=class extends I{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"},ae=class extends I{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"};var be=class extends I{static code="ERR_JWKS_INVALID";code="ERR_JWKS_INVALID"},ve=class extends I{static code="ERR_JWKS_NO_MATCHING_KEY";code="ERR_JWKS_NO_MATCHING_KEY";constructor(t="no applicable key found in the JSON Web Key Set",r){super(t,r)}},Ce=class extends I{[Symbol.asyncIterator];static code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";constructor(t="multiple matching keys found in the JSON Web Key Set",r){super(t,r)}};var Ie=class extends I{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(t="signature verification failed",r){super(t,r)}};var st=e=>{if(e?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return e instanceof CryptoKey}catch{return!1}},at=e=>e?.[Symbol.toStringTag]==="KeyObject",ct=e=>st(e)||at(e);function ut(e,t,r){try{return B(e)}catch{throw new r(`Failed to base64url decode the ${t}`)}}var Kn=e=>typeof e=="object"&&e!==null;function U(e){if(!Kn(e)||Object.prototype.toString.call(e)!=="[object Object]")return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function Zt(...e){let t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let r;for(let n of t){let o=Object.keys(n);if(!r||r.size===0){r=new Set(o);continue}for(let i of o){if(r.has(i))return!1;r.add(i)}}return!0}var Se=e=>U(e)&&typeof e.kty=="string",Qt=e=>e.kty!=="oct"&&(e.kty==="AKP"&&typeof e.priv=="string"||typeof e.d=="string"),er=e=>e.kty!=="oct"&&e.d===void 0&&e.priv===void 0,tr=e=>e.kty==="oct"&&typeof e.k=="string";function vn(e,t){if(e.startsWith("RS")||e.startsWith("PS")){let{modulusLength:r}=t.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}}function Cn(e,t){let r=`SHA-${e.slice(-3)}`;switch(e){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:parseInt(e.slice(-3),10)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:t.namedCurve};case"Ed25519":case"EdDSA":return{name:"Ed25519"};case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":return{name:e};default:throw new x(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}async function In(e,t,r){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(qt(t,"CryptoKey","KeyObject","JSON Web Key"));return crypto.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}return Xt(t,e,r),t}async function rr(e,t,r,n){let o=await In(e,t,"verify");vn(e,o);let i=Cn(e,o.algorithm);try{return await crypto.subtle.verify(i,o,r,n)}catch{return!1}}var We='Invalid or unsupported JWK "alg" (Algorithm) Parameter value';function Wn(e){let t,r;switch(e.kty){case"AKP":{switch(e.alg){case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":t={name:e.alg},r=e.priv?["sign"]:["verify"];break;default:throw new x(We)}break}case"RSA":{switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":t={name:"RSA-OAEP",hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},r=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new x(We)}break}case"EC":{switch(e.alg){case"ES256":case"ES384":case"ES512":t={name:"ECDSA",namedCurve:{ES256:"P-256",ES384:"P-384",ES512:"P-521"}[e.alg]},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:"ECDH",namedCurve:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new x(We)}break}case"OKP":{switch(e.alg){case"Ed25519":case"EdDSA":t={name:"Ed25519"},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new x(We)}break}default:throw new x('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:r}}async function ce(e){if(!e.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');let{algorithm:t,keyUsages:r}=Wn(e),n={...e};return n.kty!=="AKP"&&delete n.alg,delete n.use,crypto.subtle.importKey("jwk",n,t,e.ext??!(e.d||e.priv),e.key_ops??r)}var ue="given KeyObject instance cannot be used for this algorithm",fe,nr=async(e,t,r,n=!1)=>{fe||=new WeakMap;let o=fe.get(e);if(o?.[r])return o[r];let i=await ce({...t,alg:r});return n&&Object.freeze(e),o?o[r]=i:fe.set(e,{[r]:i}),i},Dn=(e,t)=>{fe||=new WeakMap;let r=fe.get(e);if(r?.[t])return r[t];let n=e.type==="public",o=!!n,i;if(e.asymmetricKeyType==="x25519"){switch(t){case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":break;default:throw new TypeError(ue)}i=e.toCryptoKey(e.asymmetricKeyType,o,n?[]:["deriveBits"])}if(e.asymmetricKeyType==="ed25519"){if(t!=="EdDSA"&&t!=="Ed25519")throw new TypeError(ue);i=e.toCryptoKey(e.asymmetricKeyType,o,[n?"verify":"sign"])}switch(e.asymmetricKeyType){case"ml-dsa-44":case"ml-dsa-65":case"ml-dsa-87":{if(t!==e.asymmetricKeyType.toUpperCase())throw new TypeError(ue);i=e.toCryptoKey(e.asymmetricKeyType,o,[n?"verify":"sign"])}}if(e.asymmetricKeyType==="rsa"){let s;switch(t){case"RSA-OAEP":s="SHA-1";break;case"RS256":case"PS256":case"RSA-OAEP-256":s="SHA-256";break;case"RS384":case"PS384":case"RSA-OAEP-384":s="SHA-384";break;case"RS512":case"PS512":case"RSA-OAEP-512":s="SHA-512";break;default:throw new TypeError(ue)}if(t.startsWith("RSA-OAEP"))return e.toCryptoKey({name:"RSA-OAEP",hash:s},o,n?["encrypt"]:["decrypt"]);i=e.toCryptoKey({name:t.startsWith("PS")?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:s},o,[n?"verify":"sign"])}if(e.asymmetricKeyType==="ec"){let a=new Map([["prime256v1","P-256"],["secp384r1","P-384"],["secp521r1","P-521"]]).get(e.asymmetricKeyDetails?.namedCurve);if(!a)throw new TypeError(ue);let p={ES256:"P-256",ES384:"P-384",ES512:"P-521"};p[t]&&a===p[t]&&(i=e.toCryptoKey({name:"ECDSA",namedCurve:a},o,[n?"verify":"sign"])),t.startsWith("ECDH-ES")&&(i=e.toCryptoKey({name:"ECDH",namedCurve:a},o,n?[]:["deriveBits"]))}if(!i)throw new TypeError(ue);return r?r[t]=i:fe.set(e,{[t]:i}),i};async function or(e,t){if(e instanceof Uint8Array||st(e))return e;if(at(e)){if(e.type==="secret")return e.export();if("toCryptoKey"in e&&typeof e.toCryptoKey=="function")try{return Dn(e,t)}catch(n){if(n instanceof TypeError)throw n}let r=e.export({format:"jwk"});return nr(e,r,t)}if(Se(e))return e.k?B(e.k):nr(e,e,t,!0);throw new Error("unreachable")}async function ir(e,t,r){if(!U(e))throw new TypeError("JWK must be an object");let n;switch(t??=e.alg,n??=r?.extractable??e.ext,e.kty){case"oct":if(typeof e.k!="string"||!e.k)throw new TypeError('missing "k" (Key Value) Parameter value');return B(e.k);case"RSA":if("oth"in e&&e.oth!==void 0)throw new x('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');return ce({...e,alg:t,ext:n});case"AKP":{if(typeof e.alg!="string"||!e.alg)throw new TypeError('missing "alg" (Algorithm) Parameter value');if(t!==void 0&&t!==e.alg)throw new TypeError("JWK alg and alg option value mismatch");return ce({...e,ext:n})}case"EC":case"OKP":return ce({...e,alg:t,ext:n});default:throw new x('Unsupported "kty" (Key Type) Parameter value')}}function sr(e,t,r,n,o){if(o.crit!==void 0&&n?.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||n.crit===void 0)return new Set;if(!Array.isArray(n.crit)||n.crit.length===0||n.crit.some(s=>typeof s!="string"||s.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i;r!==void 0?i=new Map([...Object.entries(r),...t.entries()]):i=t;for(let s of n.crit){if(!i.has(s))throw new x(`Extension Header Parameter "${s}" is not recognized`);if(o[s]===void 0)throw new e(`Extension Header Parameter "${s}" is missing`);if(i.get(s)&&n[s]===void 0)throw new e(`Extension Header Parameter "${s}" MUST be integrity protected`)}return new Set(n.crit)}function ar(e,t){if(t!==void 0&&(!Array.isArray(t)||t.some(r=>typeof r!="string")))throw new TypeError(`"${e}" option must be an array of strings`);if(t)return new Set(t)}var le=e=>e?.[Symbol.toStringTag],ft=(e,t,r)=>{if(t.use!==void 0){let n;switch(r){case"sign":case"verify":n="sig";break;case"encrypt":case"decrypt":n="enc";break}if(t.use!==n)throw new TypeError(`Invalid key for this operation, its "use" must be "${n}" when present`)}if(t.alg!==void 0&&t.alg!==e)throw new TypeError(`Invalid key for this operation, its "alg" must be "${e}" when present`);if(Array.isArray(t.key_ops)){let n;switch(!0){case(r==="sign"||r==="verify"):case e==="dir":case e.includes("CBC-HS"):n=r;break;case e.startsWith("PBES2"):n="deriveBits";break;case/^A\d{3}(?:GCM)?(?:KW)?$/.test(e):!e.includes("GCM")&&e.endsWith("KW")?n=r==="encrypt"?"wrapKey":"unwrapKey":n=r;break;case(r==="encrypt"&&e.startsWith("RSA")):n="wrapKey";break;case r==="decrypt":n=e.startsWith("RSA")?"unwrapKey":"deriveBits";break}if(n&&t.key_ops?.includes?.(n)===!1)throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${n}" when present`)}return!0},Jn=(e,t,r)=>{if(!(t instanceof Uint8Array)){if(Se(t)){if(tr(t)&&ft(e,t,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!ct(t))throw new TypeError(it(e,t,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"));if(t.type!=="secret")throw new TypeError(`${le(t)} instances for symmetric algorithms must be of type "secret"`)}},Un=(e,t,r)=>{if(Se(t))switch(r){case"decrypt":case"sign":if(Qt(t)&&ft(e,t,r))return;throw new TypeError("JSON Web Key for this operation must be a private JWK");case"encrypt":case"verify":if(er(t)&&ft(e,t,r))return;throw new TypeError("JSON Web Key for this operation must be a public JWK")}if(!ct(t))throw new TypeError(it(e,t,"CryptoKey","KeyObject","JSON Web Key"));if(t.type==="secret")throw new TypeError(`${le(t)} instances for asymmetric algorithms must not be of type "secret"`);if(t.type==="public")switch(r){case"sign":throw new TypeError(`${le(t)} instances for asymmetric algorithm signing must be of type "private"`);case"decrypt":throw new TypeError(`${le(t)} instances for asymmetric algorithm decryption must be of type "private"`)}if(t.type==="private")switch(r){case"verify":throw new TypeError(`${le(t)} instances for asymmetric algorithm verifying must be of type "public"`);case"encrypt":throw new TypeError(`${le(t)} instances for asymmetric algorithm encryption must be of type "public"`)}};function cr(e,t,r){switch(e.substring(0,2)){case"A1":case"A2":case"di":case"HS":case"PB":Jn(e,t,r);break;default:Un(e,t,r)}}async function ur(e,t,r){if(!U(e))throw new E("Flattened JWS must be an object");if(e.protected===void 0&&e.header===void 0)throw new E('Flattened JWS must have either of the "protected" or "header" members');if(e.protected!==void 0&&typeof e.protected!="string")throw new E("JWS Protected Header incorrect type");if(e.payload===void 0)throw new E("JWS Payload missing");if(typeof e.signature!="string")throw new E("JWS Signature missing or incorrect type");if(e.header!==void 0&&!U(e.header))throw new E("JWS Unprotected Header incorrect type");let n={};if(e.protected)try{let V=B(e.protected);n=JSON.parse(j.decode(V))}catch{throw new E("JWS Protected Header is invalid")}if(!Zt(n,e.header))throw new E("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let o={...n,...e.header},i=sr(E,new Map([["b64",!0]]),r?.crit,n,o),s=!0;if(i.has("b64")&&(s=n.b64,typeof s!="boolean"))throw new E('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:a}=o;if(typeof a!="string"||!a)throw new E('JWS "alg" (Algorithm) Header Parameter missing or invalid');let p=r&&ar("algorithms",r.algorithms);if(p&&!p.has(a))throw new Oe('"alg" (Algorithm) Header Parameter value not allowed');if(s){if(typeof e.payload!="string")throw new E("JWS Payload must be a string")}else if(typeof e.payload!="string"&&!(e.payload instanceof Uint8Array))throw new E("JWS Payload must be a string or an Uint8Array instance");let d=!1;typeof t=="function"&&(t=await t(n,e),d=!0),cr(a,t,"verify");let y=Vt(e.protected!==void 0?Ke(e.protected):new Uint8Array,Ke("."),typeof e.payload=="string"?s?Ke(e.payload):we.encode(e.payload):e.payload),h=ut(e.signature,"signature",E),A=await or(t,a);if(!await rr(a,A,h,y))throw new Ie;let R;s?R=ut(e.payload,"payload",E):typeof e.payload=="string"?R=we.encode(e.payload):R=e.payload;let W={payload:R};return e.protected!==void 0&&(W.protectedHeader=n),e.header!==void 0&&(W.unprotectedHeader=e.header),d?{...W,key:A}:W}async function fr(e,t,r){if(e instanceof Uint8Array&&(e=j.decode(e)),typeof e!="string")throw new E("Compact JWS must be a string or Uint8Array");let{0:n,1:o,2:i,length:s}=e.split(".");if(s!==3)throw new E("Invalid Compact JWS");let a=await ur({payload:o,protected:n,signature:i},t,r),p={payload:a.payload,protectedHeader:a.protectedHeader};return typeof t=="function"?{...p,key:a.key}:p}var Ln=e=>Math.floor(e.getTime()/1e3),pr=60,hr=pr*60,lt=hr*24,Nn=lt*7,Hn=lt*365.25,Mn=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function lr(e){let t=Mn.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");let r=parseFloat(t[2]),n=t[3].toLowerCase(),o;switch(n){case"sec":case"secs":case"second":case"seconds":case"s":o=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":o=Math.round(r*pr);break;case"hour":case"hours":case"hr":case"hrs":case"h":o=Math.round(r*hr);break;case"day":case"days":case"d":o=Math.round(r*lt);break;case"week":case"weeks":case"w":o=Math.round(r*Nn);break;default:o=Math.round(r*Hn);break}return t[1]==="-"||t[4]==="ago"?-o:o}var dr=e=>e.includes("/")?e.toLowerCase():`application/${e.toLowerCase()}`,jn=(e,t)=>typeof e=="string"?t.includes(e):Array.isArray(e)?t.some(Set.prototype.has.bind(new Set(e))):!1;function mr(e,t,r={}){let n;try{n=JSON.parse(j.decode(t))}catch{}if(!U(n))throw new ae("JWT Claims Set must be a top-level JSON object");let{typ:o}=r;if(o&&(typeof e.typ!="string"||dr(e.typ)!==dr(o)))throw new v('unexpected "typ" JWT header value',n,"typ","check_failed");let{requiredClaims:i=[],issuer:s,subject:a,audience:p,maxTokenAge:d}=r,y=[...i];d!==void 0&&y.push("iat"),p!==void 0&&y.push("aud"),a!==void 0&&y.push("sub"),s!==void 0&&y.push("iss");for(let R of new Set(y.reverse()))if(!(R in n))throw new v(`missing required "${R}" claim`,n,R,"missing");if(s&&!(Array.isArray(s)?s:[s]).includes(n.iss))throw new v('unexpected "iss" claim value',n,"iss","check_failed");if(a&&n.sub!==a)throw new v('unexpected "sub" claim value',n,"sub","check_failed");if(p&&!jn(n.aud,typeof p=="string"?[p]:p))throw new v('unexpected "aud" claim value',n,"aud","check_failed");let h;switch(typeof r.clockTolerance){case"string":h=lr(r.clockTolerance);break;case"number":h=r.clockTolerance;break;case"undefined":h=0;break;default:throw new TypeError("Invalid clockTolerance option type")}let{currentDate:A}=r,K=Ln(A||new Date);if((n.iat!==void 0||d)&&typeof n.iat!="number")throw new v('"iat" claim must be a number',n,"iat","invalid");if(n.nbf!==void 0){if(typeof n.nbf!="number")throw new v('"nbf" claim must be a number',n,"nbf","invalid");if(n.nbf>K+h)throw new v('"nbf" claim timestamp check failed',n,"nbf","check_failed")}if(n.exp!==void 0){if(typeof n.exp!="number")throw new v('"exp" claim must be a number',n,"exp","invalid");if(n.exp<=K-h)throw new ge('"exp" claim timestamp check failed',n,"exp","check_failed")}if(d){let R=K-n.iat,W=typeof d=="number"?d:lr(d);if(R-h>W)throw new ge('"iat" claim timestamp check failed (too far in the past)',n,"iat","check_failed");if(R<0-h)throw new v('"iat" claim timestamp check failed (it should be in the past)',n,"iat","check_failed")}return n}async function dt(e,t,r){let n=await fr(e,t,r);if(n.protectedHeader.crit?.includes("b64")&&n.protectedHeader.b64===!1)throw new ae("JWTs MUST NOT use unencoded payload");let i={payload:mr(n.protectedHeader,n.payload,r),protectedHeader:n.protectedHeader};return typeof t=="function"?{...i,key:n.key}:i}function zn(e){switch(typeof e=="string"&&e.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";case"ML":return"AKP";default:throw new x('Unsupported "alg" value for a JSON Web Key Set')}}function $n(e){return e&&typeof e=="object"&&Array.isArray(e.keys)&&e.keys.every(Bn)}function Bn(e){return U(e)}var pt=class{#e;#t=new WeakMap;constructor(t){if(!$n(t))throw new be("JSON Web Key Set malformed");this.#e=structuredClone(t)}jwks(){return this.#e}async getKey(t,r){let{alg:n,kid:o}={...t,...r?.header},i=zn(n),s=this.#e.keys.filter(d=>{let y=i===d.kty;if(y&&typeof o=="string"&&(y=o===d.kid),y&&(typeof d.alg=="string"||i==="AKP")&&(y=n===d.alg),y&&typeof d.use=="string"&&(y=d.use==="sig"),y&&Array.isArray(d.key_ops)&&(y=d.key_ops.includes("verify")),y)switch(n){case"ES256":y=d.crv==="P-256";break;case"ES384":y=d.crv==="P-384";break;case"ES512":y=d.crv==="P-521";break;case"Ed25519":case"EdDSA":y=d.crv==="Ed25519";break}return y}),{0:a,length:p}=s;if(p===0)throw new ve;if(p!==1){let d=new Ce,y=this.#t;throw d[Symbol.asyncIterator]=async function*(){for(let h of s)try{yield await yr(y,h,n)}catch{}},d}return yr(this.#t,a,n)}};async function yr(e,t,r){let n=e.get(t)||e.set(t,{}).get(t);if(n[r]===void 0){let o=await ir({...t,ext:!0},r);if(o instanceof Uint8Array||o.type!=="public")throw new be("JSON Web Key Set members must be public keys");n[r]=o}return n[r]}function ht(e){let t=new pt(e),r=async(n,o)=>t.getKey(n,o);return Object.defineProperties(r,{jwks:{value:()=>structuredClone(t.jwks()),enumerable:!1,configurable:!1,writable:!1}}),r}var mt=new WeakMap;function Fn(e){if(!e||!Array.isArray(e.keys))throw l("metro.oidc: Error: jwks must be an object with a keys array");return mt.has(e)||mt.set(e,ht(e)),mt.get(e)}function Vn(e={}){let t=e.id_token_signing_alg_values_supported;return Array.isArray(t)&&t.length?t.filter(r=>r!=="none"):["RS256"]}async function yt(e,t={}){if(!e)throw l("metro.oidc: Error: token response did not include an id_token");if(!t.jwks)throw l("metro.oidc: Error: cannot validate id_token without jwks");if(!t.issuer)throw l("metro.oidc: Error: cannot validate id_token without issuer");if(!t.client_id)throw l("metro.oidc: Error: cannot validate id_token without client_id");let{payload:r,protectedHeader:n}=await dt(e,Fn(t.jwks),{issuer:t.issuer,audience:t.client_id,algorithms:t.algorithms||Vn(t.openid_configuration),clockTolerance:t.clockTolerance??60,requiredClaims:["iss","sub","aud","exp","iat"]});if(t.nonce!==void 0&&r.nonce!==t.nonce)throw l("metro.oidc: Error: id_token nonce mismatch");return{header:n,claims:r}}var De=new Map,Gn={token_endpoint_auth_method:"none",grant_types:["authorization_code","refresh_token"],response_types:["code"]};function Xn(e,t){if(!De.has(e)){let r=t().finally(()=>{De.delete(e)});De.set(e,r)}return De.get(e)}function Je(e={}){let t={client:C(),force_authorization:!1,use_dpop:!0,authorize_callback:async h=>(window.location.href!=h.href&&window.location.replace(h.href),!1)};e=Object.assign({},t,e);let r=e.client_info;k(e,{client:b(q(C().constructor)),client_info:b(),issuer:b(w),oauth2:u({}),openid_configuration:u()});let n=_t(e),o=qn(e),i=wt(e.issuer,n),s=e.issuer+" "+JSON.stringify(r?.redirect_uris??null),a=e.store;if(e.store||(e.store=Z(e.issuer),a=Z(i)),!e.openid_configuration&&e.store.has("openid_configuration")&&(e.openid_configuration=e.store.get("openid_configuration")),!e.client_info?.client_id&&e.store.has("client_info")){let h=e.store.get("client_info");Yn(h,r)&&(e.client_info=h)}async function p(){if(e.openid_configuration&&e.client_info?.client_id)return;let h=await Xn(s,d);e.openid_configuration=h.openid_configuration,e.client_info=h.client_info,e.store.set("openid_configuration",e.openid_configuration),e.store.set("client_info",e.client_info)}async function d(){let h=e.openid_configuration;h||(h=await oe({issuer:e.issuer,client:e.client.with(e.issuer)}));let A=e.client_info;if(!A?.client_id){if(!h.registration_endpoint)throw l("metro.oidcmw: Error: issuer "+e.issuer+" does not support dynamic client registration, but you haven't specified a client_id");A=await ie({registration_endpoint:h.registration_endpoint,client:e.client,client_info:Object.assign({},Gn,A)}),A.token_endpoint_auth_method=="none"&&delete A.client_secret}return{openid_configuration:h,client_info:A}}function y(h){return typeof h!="function"?h:async A=>(a.set("pending_nonce",A.searchParams.get("nonce")),h(A))}return async(h,A)=>{let K;if(!e.force_authorization&&(K=await A(h),K.ok||K.status!=401&&K.status!=403))return K;await p();let R=e.scope||Zn(e),W=e.nonce||Ye(32),V=Object.assign({site:i,client:e.client,force_authorization:!0,authorize_callback:y(e.authorize_callback),oauth2_configuration:{client_id:e.client_info?.client_id,client_secret:e.client_info?.client_secret,token_endpoint_auth_method:e.client_info?.token_endpoint_auth_method,grant_type:"authorization_code",response_type:"code",response_mode:"query",authorization_endpoint:e.openid_configuration.authorization_endpoint,token_endpoint:e.openid_configuration.token_endpoint,scope:R,redirect_uri:e.client_info.redirect_uris[0],login_hint:e.login_hint??e.webid,issuer:e.openid_configuration.issuer,authorization_response_iss_parameter_supported:e.openid_configuration.authorization_response_iss_parameter_supported,token_type:e.use_dpop?"DPoP":void 0,nonce:W}}),c=async(_,P)=>{let Ee=S(e.openid_configuration.token_endpoint,{hash:""}).href;if(S(_.url,{hash:""}).href!==Ee)return P(_);let Q=await eo(_)=="refresh_token",J=await P(_),xt=J.headers.get("content-type");if(!J.ok||!xt?.startsWith("application/json"))return J;let de=J.data;(!de||typeof de!="object"||de instanceof ReadableStream)&&(de=await J.clone().json());let Ue=de?.id_token;if(Q&&!Ue)return J;let _r=await f(),Le=await yt(Ue,{issuer:e.openid_configuration.issuer,client_id:e.client_info.client_id,jwks:_r,openid_configuration:e.openid_configuration,nonce:Q?void 0:a.get("pending_nonce")});return Q&&to(Le.claims,a.get("id_token_claims")),Qn(Le.claims,o),a.set("id_token",Ue),a.set("id_token_claims",Le.claims),J},f=async()=>{if(!e.jwks){let P=await e.client.with(M()).with(H()).get(e.openid_configuration.jwks_uri);e.jwks=P.data}return e.jwks},m=e.client.with(e.issuer).with(c);if(e.use_dpop){let _={site:e.issuer,token_endpoint:e.openid_configuration.token_endpoint,dpop_signing_alg_values_supported:e.openid_configuration.dpop_signing_alg_values_supported};m=m.with(nt(_))}return V.client=m,m=m.with(Xe(V)),K=await m.fetch(h),K}}function Yn(e,t){if(!e?.client_id)return!1;if(!Array.isArray(t?.redirect_uris))return!0;let r=new Set(e.redirect_uris||[]);return t.redirect_uris.every(n=>r.has(n))}function _t(e){return e.webid??e.login_hint}function qn(e){return e.webid?Object.assign({webid:e.webid},e.expected_claims):e.expected_claims||{}}function Zn(e){let t=e.openid_configuration?.scopes_supported,r=Array.isArray(t)&&t.includes("webid");return e.webid||r?"openid webid":"openid"}function wt(e,t){return t?e+"|"+t:e}function Qn(e,t){for(let[r,n]of Object.entries(t)){let o=ro(e,r);if(o!==n)throw l("metro.oidcmw: id_token is for a different user: expected "+r+" "+n+", got "+o)}}async function eo(e){let t=await e.clone().text();return new URLSearchParams(t).get("grant_type")}function to(e,t){if(t&&e.sub!==t.sub)throw l("metro.oidcmw: refreshed id_token is for a different user: expected sub "+t.sub+", got "+e.sub)}function ro(e,t){return t=="webid"&&e.webid===void 0?e.sub:e[t]}function gt(){return Lt()}function bt(e){if(!e.store){if(!e.issuer)throw l("Must supply options.issuer or options.store to get the id_token");e.store=Z(wt(e.issuer,_t(e)))}return e.store.get("id_token")}function St(e){if(!e.store){if(!e.issuer)throw l("Must supply options.issuer or options.store to get the id_token claims");e.store=Z(wt(e.issuer,_t(e)))}return e.store.get("id_token_claims")}var no={oidcmw:Je,discover:oe,register:ie,isRedirected:gt,idToken:bt,idTokenClaims:St},Et=no;var At=Object.assign({},N,globalThis.metro||{});At.oidc||(At.oidc=Et);globalThis.metro=At;var gs=Et;})();
|
|
4
4
|
//# sourceMappingURL=browser.min.js.map
|