"use strict";var q=Object.defineProperty;var N=Object.getOwnPropertyDescriptor;var C=Object.getOwnPropertyNames;var D=Object.prototype.hasOwnProperty;var z=(e,t)=>{for(var n in t)q(e,n,{get:t[n],enumerable:!0})},J=(e,t,n,l)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of C(t))!D.call(e,s)&&s!==n&&q(e,s,{get:()=>t[s],enumerable:!(l=N(t,s))||l.enumerable});return e};var G=e=>J(q({},"__esModule",{value:!0}),e);var ee={};z(ee,{authenticatedFetch:()=>v,default:()=>F,errorResponse:()=>y});module.exports=G(ee);var M=(e,t)=>["authorization",`Basic ${btoa(`${e}:${t}`)}`],L=M;var W=new TextEncoder,U=e=>btoa(String.fromCharCode.apply(null,Array.from(e))).split("+").join("-").split("/").join("_").replace(/={1,2}$/,""),A=e=>{let t=new Uint8Array(e);return globalThis.crypto.getRandomValues(t),U(t)},$=()=>A(6),H=async()=>{let e=A(33),t=U(new Uint8Array(await globalThis.crypto.subtle.digest({name:"SHA-256"},W.encode(e))));return[e,t]};var X=(e,t,n,l,s,_,h,f)=>{let m=new URL(s).origin;return async(g,c,R,w,b,E,x)=>{let k=$(),[S,i]=await H();return Promise.resolve().then(async()=>{let p=new URLSearchParams([...c&&Array.from(c).sort().map(a=>["audience",a])||[],["client_id",e],["code_challenge",i],["code_challenge_method","S256"],["redirect_uri",l],["response_type","code"],...g&&[["scope",Array.from(g).sort().join(" ")]]||[],["state",k]]),o=await h(`${s}/oauth2/auth?${p}`,{redirect:"manual"});if(o.status<300||o.status>399||!o.headers.has("location"))throw new Error("Redirect expected while initiating login request");let r=o.headers.getSetCookie().map(a=>a.split(";")[0]).join("; "),d=new URL(String(o.headers.get("location"))).searchParams.get("login_challenge");if(!d)throw new Error("Invalid login challenge");return[d,r]}).then(async([p,o])=>{var u;let r=await f(`${_}/admin/oauth2/auth/requests/login/accept?login_challenge=${encodeURIComponent(p)}`,{method:"PUT",body:JSON.stringify({...E&&{acr:E},...Array.isArray(x)&&!!x.length&&{amr:x},subject:R}),redirect:"error"});if(r.status!==200||!((u=r.headers.get("content-type"))!=null&&u.toLowerCase().startsWith("application/json")))throw new Error("Unexpected response code or content type while accepting login request");let d=await r.json(),a=new URL(d.redirect_to);return[a.pathname+a.search,o]}).then(async([p,o])=>{let r=await h(`${m}${p}`,{headers:o?[["cookie",o]]:[],redirect:"manual"});if(r.status<300||r.status>399||!r.headers.has("location"))throw new Error("Redirect expected while accepting consent request");let d=r.headers.getSetCookie().map(u=>u.split(";")[0]).join("; "),a=new URL(String(r.headers.get("location"))).searchParams.get("consent_challenge");if(!a)throw new Error("Invalid consent challenge");return[a,d]}).then(async([p,o])=>{var u;let r=await f(`${_}/admin/oauth2/auth/requests/consent/accept?consent_challenge=${encodeURIComponent(p)}`,{method:"PUT",body:JSON.stringify({grant_access_token_audience:c,grant_scope:g,...(w||b)&&{session:{...w&&{access_token:w},...b&&{id_token:b}}}}),redirect:"error"});if(r.status!==200||!((u=r.headers.get("content-type"))!=null&&u.toLowerCase().startsWith("application/json")))throw new Error("Unexpected response code or content type while accepting consent request");let d=await r.json(),a=new URL(d.redirect_to);return[a.pathname+a.search,o]}).then(async([p,o])=>{let r=await h(`${m}${p}`,{headers:o?[["cookie",o]]:[],redirect:"manual"});if(r.status<300||r.status>399||!r.headers.has("location"))throw new Error("Redirect expected while accepting consent");let d=new URL(String(r.headers.get("location"))).searchParams,a=d.get("state"),u=d.get("code");if(a!==k)throw new Error("Invalid state");if(!u)throw new Error("Invalid code");return[u]}).then(async([p])=>{var r;let o=await h(`${s}/oauth2/token`,{method:"POST",body:new URLSearchParams([...n==="client_secret_basic"?[]:n==="client_secret_post"?[["client_id",e],["client_secret",String(t)]]:[["client_id",e]],["code",p],["code_verifier",S],["grant_type","authorization_code"],["redirect_uri",l]]).toString(),redirect:"error",headers:[...n==="client_secret_basic"?[L(e,String(t))]:[],["content-type","application/x-www-form-urlencoded"]]});if(o.status!==200||!((r=o.headers.get("content-type"))!=null&&r.toLowerCase().startsWith("application/json")))throw new Error("Unexpected response code or content type while fetching token");return o.json()})}},O=X;var Y=(e,t)=>new Response(JSON.stringify({error:e,error_description:t}),{status:400,headers:[["content-type","application/json"]]}),y=Y;var T=Symbol(),P=Symbol(),V=e=>{var h;let t=(h=e.fetchFn)!=null?h:fetch;if(e.clientAuthMethod==="none")return t;let n=e;async function*l(){let f=Object.create(null),m=async()=>{let g=await fetch(new Request(n.tokenEndpointUri,{duplex:"half",body:new Blob([new URLSearchParams({grant_type:"client_credentials",...n.clientAuthMethod==="client_secret_basic"?{}:n.clientAuthMethod==="client_secret_post"?{client_id:n.clientId,client_secret:n.clientSecret}:{client_id:n.clientId},...n.scope?{scope:n.scope}:{},...n.audience?{audience:n.audience}:{}}).toString()]).stream(),redirect:"error",method:"POST",headers:[...n.clientAuthMethod==="client_secret_basic"?[L(n.clientId,n.clientSecret)]:[],["content-type","application/x-www-form-urlencoded"]]}));if(!g.ok)throw new Error("Unable to refresh token");let c=await g.json(),R=Reflect.get(c,"access_token"),w=Reflect.get(c,"token_type");if(typeof R!="string"||typeof w!="string"||w.toLowerCase()!=="bearer")throw new Error("Invalid token response");return typeof Reflect.get(c,"expires_in")=="number"&&c.expires_in>0&&Object.assign(f,{[T]:R,[P]:process.hrtime.bigint()+BigInt(c.expires_in)*BigInt(9802e5)}),R};for(;;){if(f[P]>=process.hrtime.bigint())return f[P]-process.hrtime.bigint(){let m=f[0],g=f[1],c=new Request(m,g);return c.headers.set("authorization","Bearer "+(await s.next()).value),t(c)}},v=V;var K=async e=>{var s,_;if(e.headers.has("content-type")&&e.headers.get("content-type")!=="application/x-www-form-urlencoded")throw 415;if(!e.body||(s=e.headers.get("content-length"))!=null&&s.match(/^$|[^0-9]/))throw 400;let t=Number((_=e.headers.get("content-length"))!=null?_:Number.NaN);if(t>131072)throw 413;let n=[],l=0;for await(let h of e.body){if(l+=h.byteLength,l>t||l>131072)throw n.length=0,await e.body.cancel(),413;n.push(h)}return new URLSearchParams(await new Blob(n).text())},B=K;var Q=e=>{if(!e)return null;try{return new URL(e).origin}catch(t){return null}},I=Q;var Z=(e,t,n,l,s,_,h,f,m,g,c,R,w)=>{if(!s||!I(s))throw new Error("Invalid Hydra public URI: "+s);if(!_||!I(_))throw new Error("Invalid Hydra admin URI: "+_);if(!["client_secret_basic","client_secret_post","none"].includes(n))throw new Error("Invalid Hydra token endpoint auth method: "+n);if(!e)throw new Error("Invalid Hydra client ID");if(n==="none"&&t)throw new Error("Invalid Hydra secret (must be empty for public clients)");if(n!=="none"&&!t)throw new Error("Invalid Hydra secret (must not be empty for confidential clients)");if(!l||!I(l))throw new Error("Invalid Hydra client redirect URI: "+l);if(!Array.isArray(c)||!c.reduce((k,S)=>k&&typeof S=="string",!0))throw new Error("Invalid Hydra audience: "+c);R||(R=["urn:ietf:params:oauth:token-type:access_token"]),w||(w=[]);let b=O(e,t,n,l,s,_,v(h),v(f)),E=R,x=w;return async k=>{var S;try{let i=await B(k);if(!i.has("subject_token"))return y("invalid_request","missing subject_token");if(!i.has("subject_token_type")||!E.includes(String(i.get("subject_token_type")).toLowerCase()))return y("invalid_request","invalid subject_token_type");if(String(i.get("grant_type")).toLowerCase()!=="urn:ietf:params:oauth:grant-type:token-exchange")return y("unsupported_grant_type");if(i.has("requested_token_type")&&String(i.get("requested_token_type")).toLowerCase()!=="urn:ietf:params:oauth:token-type:access_token")return y("invalid_request","invalid requested_token_type");let p=String((S=i.get("scope"))!=null?S:"").split(" ").filter(u=>u.length);if(!p.reduce((u,j)=>u&&!!(g!=null&&g.includes(j)),!0))return y("invalid_scope");let o=i.getAll("audience");if(!o.reduce((u,j)=>u&&c.includes(j),!0))return y("invalid_request","invalid audience");let r=i.get("resource");if(r&&I(r)===null)return y("invalid_request","invalid resource");if(i.has("actor_token")!==i.has("actor_token_type"))return y("invalid_request","missing actor_token or actor_token_type");if(i.has("actor_token_type")&&!x.includes(String(i.get("actor_token_type")).toLowerCase()))return y("invalid_request","invalid subject_token_type");let d=await m(i),a=await b(p,o,d.subject,d.access_token,d.id_token,d.acr,d.amr);return new Response(JSON.stringify({access_token:a.access_token,issued_token_type:"urn:ietf:params:oauth:token-type:access_token",token_type:a.token_type,expires_in:a.expires_in,scope:a.scope}),{status:200,headers:[["content-type","application/json"]]})}catch(i){if(typeof i=="number")return new Response(null,{status:i})}return new Response(null,{status:500})}},F=Z;0&&(module.exports={authenticatedFetch,errorResponse});