@gydr-ai/mcp-oauth 0.1.1 → 0.1.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/index.js CHANGED
@@ -1,9 +1,9 @@
1
- var Ir=Object.defineProperty;var s=(e,t)=>Ir(e,"name",{value:t,configurable:!0});var w=class extends Error{static{s(this,"McpAuthConfigError")}constructor(t){super(t),this.name="McpAuthConfigError"}};function W(e,t,r){if(e===void 0)return;let n;try{n=JSON.stringify(e)}catch{throw new TypeError(`${r} returned data that is not JSON-serializable`)}if(typeof n!="string")throw new TypeError(`${r} returned data that is not JSON-serializable`);if(Buffer.byteLength(n,"utf8")>t)throw new TypeError(`${r} returned more than ${t} bytes`);return JSON.parse(n)}s(W,"jsonCopy");var yt={accessToken:1800,refreshToken:1209600,grant:7776e3,authorizationCode:60,pendingAuthorization:900,clientMetadataCache:1800,clientMetadataFailure:60},Je={accessToken:{min:1,max:86400},refreshToken:{min:1,max:3456e4},grant:{min:1,max:3456e4},authorizationCode:{min:1,max:600},pendingAuthorization:{min:1,max:3600},clientMetadataCache:{min:0,max:86400},clientMetadataFailure:{min:0,max:3600}},wt={clientNameLength:128,redirectUris:8,redirectUriLength:2048,stateLength:2048,scopeLength:1024,registrationBytes:16*1024,formBytes:32*1024,clientMetadataBytes:5*1024,clientMetadataTimeoutMs:4e3,clientMetadataFailures:1e4,grantContextBytes:4096,consentDetailsBytes:8192,grantDataBytes:4096},_t=["mcp"],kt=10,Ye=300,Rt="__Host-mcp-auth-",bt=1e5,Ct=2419200,Xe=6e4,Ze=1e4,Te=86400,Ae=2048,Tt=600,At=10,Qe=60;var Et="/.well-known/oauth-protected-resource",xt="/.well-known/oauth-authorization-server",de=new Set(["127.0.0.1","[::1]","localhost"]),K={id:"interaction",csrf:"form_token",decision:"choice"},St="approve",Ee="application/x-www-form-urlencoded",Pt="application/json";var xe={"Cache-Control":"no-store",Pragma:"no-cache"},vt={"Access-Control-Allow-Origin":"*","Access-Control-Expose-Headers":"WWW-Authenticate"};function re(e,t,r={}){let n=new Headers({"Content-Type":Pt,...r.cacheable?{"Cache-Control":`public, max-age=${Tt}`}:xe,...r.cors?vt:{},...r.headers});return new Response(JSON.stringify(t),{status:e,headers:n})}s(re,"json");function $(e,t,r,n){return re(e,r===void 0?{error:t}:{error:t,error_description:r},{cors:!0,...n!==void 0?{headers:{"WWW-Authenticate":n}}:{}})}s($,"oauthError");function It(e){return new Response(null,{status:204,headers:{...vt,"Access-Control-Allow-Methods":e,"Access-Control-Allow-Headers":"Authorization, Content-Type, MCP-Protocol-Version","Access-Control-Max-Age":"600"}})}s(It,"preflight");function Mt(e){return new Response(null,{status:405,headers:{Allow:e,...xe}})}s(Mt,"methodNotAllowed");function Mr(e=[],t=[]){let r=["'self'",...e].join(" ");return{"Content-Type":"text/html; charset=utf-8","Content-Security-Policy":`default-src 'none';${t.length===0?"":` script-src ${t.map(o=>`'${o}'`).join(" ")};`} style-src 'unsafe-inline'; img-src data:; form-action ${r}; frame-ancestors 'none'; base-uri 'none'`,"X-Frame-Options":"DENY","X-Content-Type-Options":"nosniff","Referrer-Policy":"no-referrer",...xe}}s(Mr,"pageHeaders");function Se(e,t,r={}){let n=new Headers(Mr(r.formActionOrigins,r.scriptHashes));for(let o of r.setCookies??[])n.append("Set-Cookie",o);return new Response(t,{status:e,headers:n})}s(Se,"html");function ne(e,t=[],r=302){let n=new Headers({Location:e,"Referrer-Policy":"no-referrer",...xe});for(let o of t)n.append("Set-Cookie",o);return new Response(null,{status:r,headers:n})}s(ne,"redirect");import{createHash as jt,randomBytes as jr,timingSafeEqual as Or}from"node:crypto";var Ur=32,Ot=43;function N(){return jr(Ur).toString("base64url")}s(N,"randomToken");function A(e){return jt("sha256").update(e,"utf8").digest("hex")}s(A,"sha256Hex");function et(e){return jt("sha256").update(e,"ascii").digest("base64url")}s(et,"pkceChallenge");function ue(e,t){let r=Buffer.from(e,"utf8"),n=Buffer.from(t,"utf8");return r.length===n.length&&Or(r,n)}s(ue,"constantTimeEqual");var Lr="-_",Nr="-._~";function Ut(e){return t=>{for(let r=0;r<t.length;r+=1){let n=t.charCodeAt(r);if(!(n>=48&&n<=57||n>=65&&n<=90||n>=97&&n<=122)&&!e.includes(t.charAt(r)))return!1}return!0}}s(Ut,"charsetCheck");var Lt=Ut(Lr),Dr=Ut(Nr);function Hr(e){return e.length>=43&&e.length<=128&&Dr(e)}s(Hr,"isWellFormedVerifier");function Nt(e){return e.length===Ot&&Lt(e)}s(Nt,"isWellFormedChallenge");function J(e){return e.length===Ot&&Lt(e)}s(J,"isOpaqueToken");function Dt(e,t){return Hr(e)&&ue(et(e),t)}s(Dt,"pkceMatches");function tt(e){if(typeof e=="object"&&e!==null&&!Object.isFrozen(e)){Object.freeze(e);for(let t of Reflect.ownKeys(e))tt(Reflect.get(e,t))}return e}s(tt,"deepFreeze");function M(e){return tt(structuredClone(e))}s(M,"frozenCopy");function Ht(e){return tt(e)}s(Ht,"freezeDeep");async function $t(e,t){let r=e.options.getGrantContext;if(r===void 0)return;let n=await r(M({grantId:t.grantId,clientId:t.clientId,subject:t.subject,scopes:[...t.scopes],resource:t.resource,createdAt:t.createdAt,...t.data!==void 0?{data:t.data}:{}}));return W(n,e.options.limits.grantContextBytes,"getGrantContext")}s($t,"grantContextFor");function O(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(O,"isRecord");function z(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")}s(z,"isStringArray");function le(e){return M({grantId:e.grantId,clientId:e.clientId,subject:e.subject,scopes:e.scopes,resource:e.resource,createdAt:e.createdAt,expiresAt:e.expiresAt,...e.clientName!==void 0?{clientName:e.clientName}:{},...e.displayName!==void 0?{displayName:e.displayName}:{},...e.allowRefresh!==void 0?{allowRefresh:e.allowRefresh}:{},...e.data!==void 0?{data:e.data}:{}})}s(le,"grantSummary");function S(e,t){return!(Number.isFinite(e)&&Number.isFinite(t)&&e>t)}s(S,"hasExpired");function Pe(e){return()=>{let t=e();if(typeof t!="number"||!Number.isFinite(t))throw new TypeError("The configured clock returned a non-finite time");return t}}s(Pe,"checkedClock");async function ve(e,t,r,n=r){let{options:o}=e,i=o.now(),a=N(),c=Math.min(i+o.accessTokenTtlMs,t.expiresAt);await o.store.putAccessToken({tokenHash:A(a),grantId:t.grantId,clientId:t.clientId,scopes:r,resource:t.resource,expiresAt:c});let d={access_token:a,token_type:"Bearer",expires_in:Math.max(0,Math.floor((c-i)/1e3)),scope:r.join(" ")};if(t.allowRefresh===!1)return d;let l=N();return await o.store.putRefreshToken({tokenHash:A(l),grantId:t.grantId,clientId:t.clientId,scopes:n,resource:t.resource,expiresAt:Math.min(i+o.refreshTokenTtlMs,t.expiresAt)}),{...d,refresh_token:l}}s(ve,"issueTokenPair");async function oe(e,t,r){let n=await e.options.store.getGrant(t);if(!(n===void 0||n.clientId!==r||S(n.expiresAt,e.options.now())))return n}s(oe,"liveGrant");async function rt(e,t){let r=e.options.identityProvider;if(r.revoke!==void 0)try{await r.revoke(t)}catch{}}s(rt,"revokeUpstreamToken");async function nt(e,t,r){if(t===void 0||e.options.identityProvider.revoke===void 0)return;let n;try{n=await e.options.sealer.open(t,r)}catch{return}await rt(e,n)}s(nt,"revokeSealedUpstreamToken");async function zt(e,t,r,n){let{options:o}=e,i=await o.store.getGrant(t);i!==void 0&&await e.emit({type:"grant_revoked",grantId:t,reason:r,grant:le(i)}),n(t);let a=await o.store.getGrant(t),c=await o.store.deleteGrant(t),d=O(c)&&c.grantId===t?c.sealedUpstreamRefreshToken:(a??i)?.sealedUpstreamRefreshToken;d!==void 0&&typeof d!="string"||await nt(e,d,t)}s(zt,"revokeGrantById");function Ie(e){return`"${e.replace(/[\\"]/g,"\\$&").replace(/[\r\n]/g," ")}"`}s(Ie,"quoted");function $r(e){switch(e){case"insufficient_scope":return 403;case"invalid_request":return 400;case"invalid_token":case void 0:return 401}}s($r,"challengeStatus");function Me(e,t={}){let{options:r}=e,n=[`resource_metadata=${Ie(r.resourceMetadataUrl)}`],o=t.scope??r.defaultScopes;t.error!==void 0&&n.push(`error=${Ie(t.error)}`),t.description!==void 0&&n.push(`error_description=${Ie(t.description)}`),n.push(`scope=${Ie(o.join(" "))}`);let i=$r(t.error);return new Response(JSON.stringify({error:t.error??"unauthorized",...t.description!==void 0?{error_description:t.description}:{}}),{status:i,headers:{"Content-Type":"application/json","Cache-Control":"no-store","WWW-Authenticate":`Bearer ${n.join(", ")}`,"Access-Control-Allow-Origin":"*","Access-Control-Expose-Headers":"WWW-Authenticate"}})}s(Me,"bearerChallenge");function zr(){return new Response(JSON.stringify({error:"server_error"}),{status:500,headers:{"Content-Type":"application/json","Cache-Control":"no-store"}})}s(zr,"serverFailure");function Gr(e){let t=e.headers.get("authorization");if(t===null)return null;let r=t.trim(),n=r.indexOf(" ");if((n===-1?r:r.slice(0,n)).toLowerCase()!=="bearer")return null;let i=n===-1?"":r.slice(n+1).trim();return i===""?void 0:i}s(Gr,"bearerToken");async function Gt(e,t,r){let{options:n}=e,o=Gr(t);if(o===null)return{ok:!1,response:Me(e)};let i=s(l=>({ok:!1,response:Me(e,{error:"invalid_token",description:l})}),"invalid");if(o===void 0||!J(o))return i("The bearer value is not in this server's token format");let a=await n.store.getAccessToken(A(o));if(a===void 0||S(a.expiresAt,n.now()))return i("The token is unknown here or past its expiry");if(a.resource!==n.resource)return i("The token's audience is a different resource");let c=await oe(e,a.grantId,a.clientId);if(c===void 0)return i("Access behind this token has been withdrawn");let d;try{d=await $t(e,c)}catch{return await e.emit({type:"grant_context_failed",grantId:c.grantId}),{ok:!1,response:zr()}}return{ok:!0,subject:c.subject,grantId:c.grantId,clientId:c.clientId,scopes:a.scopes,context:d,getUpstreamAccessToken:s(l=>r(c.grantId,l?.forceRefresh===!0),"getUpstreamAccessToken")}}s(Gt,"authenticateRequest");var Ft={rate_limited:{status:429,title:"Slow down",message:"An unusual number of requests came from your network just now. Please wait a little, then start again from your application."},repeated_parameter:{status:400,title:"Malformed link",message:"The link that opened this page names the same setting more than once, so it cannot be trusted."},client_unknown:{status:400,title:"Application not recognised",message:"The application that opened this page is not known to this server. Try connecting again from the application."},redirect_uri_not_registered:{status:400,title:"Unexpected return address",message:"The application asked for the result to go somewhere other than the return addresses it registered, so nothing was sent."},invalid_request:{status:400,title:"Incomplete request",message:"The application sent a request this server cannot accept. Please try connecting again from the application."},unsupported_response_type:{status:400,title:"Unsupported request",message:"The application asked for a kind of sign-in this server does not offer."},invalid_target:{status:400,title:"Wrong service",message:"The application asked for access to a service this server does not protect."},invalid_scope:{status:400,title:"Unavailable permissions",message:"The application asked for permissions that are not available to it."},consent_required:{status:400,title:"Approval needed",message:"This server always asks you before granting access, but the application asked to skip that step."},access_denied:{status:403,title:"Not permitted",message:"This application may not connect to this service."},flow_ended:{status:400,title:"This sign-in has ended",message:"The sign-in you returned from is no longer open, either because it took too long or because it was already completed. Please connect again from your application."},malformed_response:{status:400,title:"Malformed response",message:"The identity provider's response could not be used to finish signing in."},browser_mismatch:{status:400,title:"Different browser",message:"This sign-in has to finish in the browser where it began. Open your application on this device and connect again."},sign_in_not_confirmed:{status:400,title:"Sign-in not confirmed",message:"Your identity provider did not confirm who you are. Please connect again from your application."},subject_not_permitted:{status:403,title:"Access not permitted",message:"The account you signed in with may not connect this application."},consent_unavailable:{status:400,title:"Nothing to approve",message:"There is no open request to approve here. It may have been answered already, taken too long, or been opened in another browser. Please connect again from your application."},unsupported_submission:{status:415,title:"Unexpected submission",message:"Your answer must be sent with the form on the previous page."},server_error:{status:500,title:"Unexpected problem",message:"Something on this server stopped the request from finishing. Please start again from your application."}};function Bt(e,t){let r=e.getClientIp?.(t);if(r!==void 0&&r!=="")return r;if(!e.trustProxy)return"unknown";let o=(t.headers.get("x-forwarded-for")??"").split(",").map(i=>i.trim()).filter(i=>i!=="");return o[o.length-1]??"unknown"}s(Bt,"clientIp");var Fr=/^[A-Za-z]{1,8}(?:-[A-Za-z0-9]{1,8})*$/;function je(e){if(e===null)return[];let t=[];for(let[r,n]of e.split(",").entries()){let[o="",...i]=n.trim().split(";"),a=o.trim(),c=i.map(l=>l.trim()).find(l=>l.startsWith("q=")),d=c===void 0?1:Number(c.slice(2));Fr.test(a)&&Number.isFinite(d)&&d>0&&d<=1&&t.push({tag:a,q:d,order:r})}return t.sort((r,n)=>n.q-r.q||r.order-n.order),[...new Set(t.map(r=>r.tag))].slice(0,10)}s(je,"parseLocales");var Br=/^[A-Za-z0-9_.:-]{1,64}$/;async function se(e){let t;try{t=await e()}catch{return{allowed:!1}}return ot(t)}s(se,"decide");function ot(e){if(e===!0)return{allowed:!0};if(!O(e))return{allowed:!1};if(e.allow===!0)return{allowed:!0};let t=e.reason;return typeof t=="string"&&Br.test(t)?{allowed:!1,reason:t}:{allowed:!1}}s(ot,"judge");async function pe(e){return(await se(e)).allowed}s(pe,"permits");function qt(e){let t=s(async r=>{if(e.onEvent)try{await e.onEvent(r)}catch{}},"emit");return{options:e,cimd:{failures:new Map,inflight:new Map},emit:t,async allowed(r,n){if(!e.rateLimit)return!0;let o=e.rateLimit,i=await pe(()=>o(Bt(e,r),n));return i||await t({type:"request_throttled",scope:n}),i},errorPage(r,n,o={}){let i=Ft[n],a=e.renderErrorPage(M({status:i.status,reason:n,title:i.title,message:i.message,locales:je(r.headers.get("accept-language")),...o.detail!==void 0?{detail:o.detail}:{},...o.policyReason!==void 0?{policyReason:o.policyReason}:{}}));return Se(i.status,a,{setCookies:o.setCookies??[]})}}}s(qt,"createContext");var qr=/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}\p{Co}\p{Cs}\p{Cn}]/u;function ie(e){return qr.test(e)}s(ie,"hasHiddenCharacters");var Kr={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};function P(e){return e.replace(/[&<>"']/g,t=>Kr[t]??t)}s(P,"escapeHtml");function Oe(e){if(e.length===0)return!1;for(let t=0;t<e.length;t+=1){let r=e.charCodeAt(t);if(r!==33&&!(r>=35&&r<=91)&&!(r>=93&&r<=126))return!1}return!0}s(Oe,"isScopeToken");function ae(e,t){let r=e.length;for(;r>0&&e[r-1]===t;)r-=1;return e.slice(0,r)}s(ae,"trimTrailing");function st(e,t){return`<!doctype html>
1
+ var Gr=Object.defineProperty;var i=(e,t)=>Gr(e,"name",{value:t,configurable:!0});var _=class extends Error{static{i(this,"McpAuthConfigError")}constructor(t){super(t),this.name="McpAuthConfigError"}};function J(e,t,r){if(e===void 0)return;let n;try{n=JSON.stringify(e)}catch{throw new TypeError(`${r} returned data that is not JSON-serializable`)}if(typeof n!="string")throw new TypeError(`${r} returned data that is not JSON-serializable`);if(Buffer.byteLength(n,"utf8")>t)throw new TypeError(`${r} returned more than ${t} bytes`);return JSON.parse(n)}i(J,"jsonCopy");var Ct={accessToken:1800,refreshToken:1209600,grant:7776e3,grantIdle:0,authorizationCode:60,pendingAuthorization:900,clientMetadataCache:1800,clientMetadataFailure:60},et={accessToken:{min:1,max:86400},refreshToken:{min:1,max:3456e4},grant:{min:1,max:3456e4},grantIdle:{min:0,max:3456e4},authorizationCode:{min:1,max:600},pendingAuthorization:{min:1,max:3600},clientMetadataCache:{min:0,max:86400},clientMetadataFailure:{min:0,max:3600}},Tt={clientNameLength:128,redirectUris:8,redirectUriLength:2048,stateLength:2048,scopeLength:1024,registrationBytes:16*1024,formBytes:32*1024,clientMetadataBytes:5*1024,clientMetadataTimeoutMs:4e3,clientMetadataFailures:1e4,grantContextBytes:4096,consentDetailsBytes:8192,grantDataBytes:4096},At=["mcp"],Et=10,tt=300,xt="__Host-mcp-auth-",Pt=1e5,St=2419200,rt=6e4,nt=1e4,Pe=86400,Se=2048,vt=600,It=10,ot=60;var Mt="/.well-known/oauth-protected-resource",jt="/.well-known/oauth-authorization-server",pe=new Set(["127.0.0.1","[::1]","localhost"]),K={id:"interaction",csrf:"form_token",decision:"choice"},Ot="approve",ve="application/x-www-form-urlencoded",Ut="application/json";var Ie={"Cache-Control":"no-store",Pragma:"no-cache"},Lt={"Access-Control-Allow-Origin":"*","Access-Control-Expose-Headers":"WWW-Authenticate"};function oe(e,t,r={}){let n=new Headers({"Content-Type":Ut,...r.cacheable?{"Cache-Control":`public, max-age=${vt}`}:Ie,...r.cors?Lt:{},...r.headers});return new Response(JSON.stringify(t),{status:e,headers:n})}i(oe,"json");function $(e,t,r,n){return oe(e,r===void 0?{error:t}:{error:t,error_description:r},{cors:!0,...n!==void 0?{headers:{"WWW-Authenticate":n}}:{}})}i($,"oauthError");function Nt(e){return new Response(null,{status:204,headers:{...Lt,"Access-Control-Allow-Methods":e,"Access-Control-Allow-Headers":"Authorization, Content-Type, MCP-Protocol-Version","Access-Control-Max-Age":"600"}})}i(Nt,"preflight");function Dt(e){return new Response(null,{status:405,headers:{Allow:e,...Ie}})}i(Dt,"methodNotAllowed");function $r(e=[],t=[]){let r=["'self'",...e].join(" ");return{"Content-Type":"text/html; charset=utf-8","Content-Security-Policy":`default-src 'none';${t.length===0?"":` script-src ${t.map(o=>`'${o}'`).join(" ")};`} style-src 'unsafe-inline'; img-src data:; form-action ${r}; frame-ancestors 'none'; base-uri 'none'`,"X-Frame-Options":"DENY","X-Content-Type-Options":"nosniff","Referrer-Policy":"no-referrer",...Ie}}i($r,"pageHeaders");function Me(e,t,r={}){let n=new Headers($r(r.formActionOrigins,r.scriptHashes));for(let o of r.setCookies??[])n.append("Set-Cookie",o);return new Response(t,{status:e,headers:n})}i(Me,"html");function ie(e,t=[],r=302){let n=new Headers({Location:e,"Referrer-Policy":"no-referrer",...Ie});for(let o of t)n.append("Set-Cookie",o);return new Response(null,{status:r,headers:n})}i(ie,"redirect");import{createHash as Ht,randomBytes as zr,timingSafeEqual as Fr}from"node:crypto";var Br=32,Gt=43;function D(){return zr(Br).toString("base64url")}i(D,"randomToken");function x(e){return Ht("sha256").update(e,"utf8").digest("hex")}i(x,"sha256Hex");function it(e){return Ht("sha256").update(e,"ascii").digest("base64url")}i(it,"pkceChallenge");function fe(e,t){let r=Buffer.from(e,"utf8"),n=Buffer.from(t,"utf8");return r.length===n.length&&Fr(r,n)}i(fe,"constantTimeEqual");var qr="-_",Kr="-._~";function $t(e){return t=>{for(let r=0;r<t.length;r+=1){let n=t.charCodeAt(r);if(!(n>=48&&n<=57||n>=65&&n<=90||n>=97&&n<=122)&&!e.includes(t.charAt(r)))return!1}return!0}}i($t,"charsetCheck");var zt=$t(qr),Vr=$t(Kr);function Wr(e){return e.length>=43&&e.length<=128&&Vr(e)}i(Wr,"isWellFormedVerifier");function Ft(e){return e.length===Gt&&zt(e)}i(Ft,"isWellFormedChallenge");function Y(e){return e.length===Gt&&zt(e)}i(Y,"isOpaqueToken");function Bt(e,t){return Wr(e)&&fe(it(e),t)}i(Bt,"pkceMatches");function st(e){if(typeof e=="object"&&e!==null&&!Object.isFrozen(e)){Object.freeze(e);for(let t of Reflect.ownKeys(e))st(Reflect.get(e,t))}return e}i(st,"deepFreeze");function j(e){return st(structuredClone(e))}i(j,"frozenCopy");function qt(e){return st(e)}i(qt,"freezeDeep");async function Kt(e,t){let r=e.options.getGrantContext;if(r===void 0)return;let n=await r(j({grantId:t.grantId,clientId:t.clientId,subject:t.subject,scopes:[...t.scopes],resource:t.resource,createdAt:t.createdAt,...t.data!==void 0?{data:t.data}:{}}));return J(n,e.options.limits.grantContextBytes,"getGrantContext")}i(Kt,"grantContextFor");function L(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(L,"isRecord");function z(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")}i(z,"isStringArray");function me(e){return j({grantId:e.grantId,clientId:e.clientId,subject:e.subject,scopes:e.scopes,resource:e.resource,createdAt:e.createdAt,expiresAt:e.expiresAt,...e.clientName!==void 0?{clientName:e.clientName}:{},...e.displayName!==void 0?{displayName:e.displayName}:{},...e.allowRefresh!==void 0?{allowRefresh:e.allowRefresh}:{},...e.data!==void 0?{data:e.data}:{},...e.redirectUri!==void 0?{redirectUri:e.redirectUri}:{}})}i(me,"grantSummary");function P(e,t){return!(Number.isFinite(e)&&Number.isFinite(t)&&e>t)}i(P,"hasExpired");function je(e){return()=>{let t=e();if(typeof t!="number"||!Number.isFinite(t))throw new TypeError("The configured clock returned a non-finite time");return t}}i(je,"checkedClock");async function Oe(e,t,r,n=r){let{options:o}=e,s=o.now(),a=D(),c=Math.min(s+o.accessTokenTtlMs,t.expiresAt);await o.store.putAccessToken({tokenHash:x(a),grantId:t.grantId,clientId:t.clientId,scopes:r,resource:t.resource,expiresAt:c});let d={access_token:a,token_type:"Bearer",expires_in:Math.max(0,Math.floor((c-s)/1e3)),scope:r.join(" ")};if(t.allowRefresh===!1)return d;let l=D();return await o.store.putRefreshToken({tokenHash:x(l),grantId:t.grantId,clientId:t.clientId,scopes:n,resource:t.resource,expiresAt:Math.min(s+o.refreshTokenTtlMs,t.expiresAt)}),{...d,refresh_token:l}}i(Oe,"issueTokenPair");async function se(e,t,r){let n=await e.options.store.getGrant(t);if(!(n===void 0||n.clientId!==r||P(n.expiresAt,e.options.now())))return n}i(se,"liveGrant");async function at(e,t){let r=e.options.identityProvider;if(r.revoke!==void 0)try{await r.revoke(t)}catch{}}i(at,"revokeUpstreamToken");async function ct(e,t,r){if(t===void 0||e.options.identityProvider.revoke===void 0)return;let n;try{n=await e.options.sealer.open(t,r)}catch{return}await at(e,n)}i(ct,"revokeSealedUpstreamToken");async function Vt(e,t,r,n){let{options:o}=e,s=await o.store.getGrant(t);s!==void 0&&await e.emit({type:"grant_revoked",grantId:t,reason:r,grant:me(s)}),n(t);let a=await o.store.getGrant(t),c=await o.store.deleteGrant(t),d=L(c)&&c.grantId===t?c.sealedUpstreamRefreshToken:(a??s)?.sealedUpstreamRefreshToken;d!==void 0&&typeof d!="string"||await ct(e,d,t)}i(Vt,"revokeGrantById");function Ue(e){return`"${e.replace(/[\\"]/g,"\\$&").replace(/[\r\n]/g," ")}"`}i(Ue,"quoted");function Jr(e){switch(e){case"insufficient_scope":return 403;case"invalid_request":return 400;case"invalid_token":case void 0:return 401}}i(Jr,"challengeStatus");function Le(e,t={}){let{options:r}=e,n=[`resource_metadata=${Ue(r.resourceMetadataUrl)}`],o=t.scope??r.defaultScopes;t.error!==void 0&&n.push(`error=${Ue(t.error)}`),t.description!==void 0&&n.push(`error_description=${Ue(t.description)}`),n.push(`scope=${Ue(o.join(" "))}`);let s=Jr(t.error);return new Response(JSON.stringify({error:t.error??"unauthorized",...t.description!==void 0?{error_description:t.description}:{}}),{status:s,headers:{"Content-Type":"application/json","Cache-Control":"no-store","WWW-Authenticate":`Bearer ${n.join(", ")}`,"Access-Control-Allow-Origin":"*","Access-Control-Expose-Headers":"WWW-Authenticate"}})}i(Le,"bearerChallenge");function Yr(){return new Response(JSON.stringify({error:"server_error"}),{status:500,headers:{"Content-Type":"application/json","Cache-Control":"no-store"}})}i(Yr,"serverFailure");function Xr(e){let t=e.headers.get("authorization");if(t===null)return null;let r=t.trim(),n=r.indexOf(" ");if((n===-1?r:r.slice(0,n)).toLowerCase()!=="bearer")return null;let s=n===-1?"":r.slice(n+1).trim();return s===""?void 0:s}i(Xr,"bearerToken");async function Wt(e,t,r){let{options:n}=e,o=Xr(t);if(o===null)return{ok:!1,response:Le(e)};let s=i(l=>({ok:!1,response:Le(e,{error:"invalid_token",description:l})}),"invalid");if(o===void 0||!Y(o))return s("The bearer value is not in this server's token format");let a=await n.store.getAccessToken(x(o));if(a===void 0||P(a.expiresAt,n.now()))return s("The token is unknown here or past its expiry");if(a.resource!==n.resource)return s("The token's audience is a different resource");let c=await se(e,a.grantId,a.clientId);if(c===void 0)return s("Access behind this token has been withdrawn");let d;try{d=await Kt(e,c)}catch{return await e.emit({type:"grant_context_failed",grantId:c.grantId}),{ok:!1,response:Yr()}}return{ok:!0,subject:c.subject,grantId:c.grantId,clientId:c.clientId,scopes:a.scopes,context:d,getUpstreamAccessToken:i(l=>r(c.grantId,l?.forceRefresh===!0),"getUpstreamAccessToken")}}i(Wt,"authenticateRequest");var Jt={rate_limited:{status:429,title:"Slow down",message:"An unusual number of requests came from your network just now. Please wait a little, then start again from your application."},repeated_parameter:{status:400,title:"Malformed link",message:"The link that opened this page names the same setting more than once, so it cannot be trusted."},client_unknown:{status:400,title:"Application not recognised",message:"The application that opened this page is not known to this server. Try connecting again from the application."},redirect_uri_not_registered:{status:400,title:"Unexpected return address",message:"The application asked for the result to go somewhere other than the return addresses it registered, so nothing was sent."},invalid_request:{status:400,title:"Incomplete request",message:"The application sent a request this server cannot accept. Please try connecting again from the application."},unsupported_response_type:{status:400,title:"Unsupported request",message:"The application asked for a kind of sign-in this server does not offer."},invalid_target:{status:400,title:"Wrong service",message:"The application asked for access to a service this server does not protect."},invalid_scope:{status:400,title:"Unavailable permissions",message:"The application asked for permissions that are not available to it."},consent_required:{status:400,title:"Approval needed",message:"This server always asks you before granting access, but the application asked to skip that step."},access_denied:{status:403,title:"Not permitted",message:"This application may not connect to this service."},flow_ended:{status:400,title:"This sign-in has ended",message:"The sign-in you returned from is no longer open, either because it took too long or because it was already completed. Please connect again from your application."},malformed_response:{status:400,title:"Malformed response",message:"The identity provider's response could not be used to finish signing in."},browser_mismatch:{status:400,title:"Different browser",message:"This sign-in has to finish in the browser where it began. Open your application on this device and connect again."},sign_in_not_confirmed:{status:400,title:"Sign-in not confirmed",message:"Your identity provider did not confirm who you are. Please connect again from your application."},subject_not_permitted:{status:403,title:"Access not permitted",message:"The account you signed in with may not connect this application."},consent_unavailable:{status:400,title:"Nothing to approve",message:"There is no open request to approve here. It may have been answered already, taken too long, or been opened in another browser. Please connect again from your application."},unsupported_submission:{status:415,title:"Unexpected submission",message:"Your answer must be sent with the form on the previous page."},server_error:{status:500,title:"Unexpected problem",message:"Something on this server stopped the request from finishing. Please start again from your application."}};function Yt(e,t){let r=e.getClientIp?.(t);if(r!==void 0&&r!=="")return r;if(!e.trustProxy)return"unknown";let o=(t.headers.get("x-forwarded-for")??"").split(",").map(s=>s.trim()).filter(s=>s!=="");return o[o.length-1]??"unknown"}i(Yt,"clientIp");var Zr=/^[A-Za-z]{1,8}(?:-[A-Za-z0-9]{1,8})*$/;function Ne(e){if(e===null)return[];let t=[];for(let[r,n]of e.split(",").entries()){let[o="",...s]=n.trim().split(";"),a=o.trim(),c=s.map(l=>l.trim()).find(l=>l.startsWith("q=")),d=c===void 0?1:Number(c.slice(2));Zr.test(a)&&Number.isFinite(d)&&d>0&&d<=1&&t.push({tag:a,q:d,order:r})}return t.sort((r,n)=>n.q-r.q||r.order-n.order),[...new Set(t.map(r=>r.tag))].slice(0,10)}i(Ne,"parseLocales");var Qr=/^[A-Za-z0-9_.:-]{1,64}$/;async function ae(e){let t;try{t=await e()}catch{return{allowed:!1}}return dt(t)}i(ae,"decide");function dt(e){if(e===!0)return{allowed:!0};if(!L(e))return{allowed:!1};if(e.allow===!0)return{allowed:!0};let t=e.reason;return typeof t=="string"&&Qr.test(t)?{allowed:!1,reason:t}:{allowed:!1}}i(dt,"judge");async function he(e){return(await ae(e)).allowed}i(he,"permits");function Xt(e){let t=i(async r=>{if(e.onEvent)try{await e.onEvent(r)}catch{}},"emit");return{options:e,cimd:{failures:new Map,inflight:new Map},emit:t,async allowed(r,n){if(!e.rateLimit)return!0;let o=e.rateLimit,s=await he(()=>o(Yt(e,r),n));return s||await t({type:"request_throttled",scope:n}),s},errorPage(r,n,o={}){let s=Jt[n],a=e.renderErrorPage(j({status:s.status,reason:n,title:s.title,message:s.message,locales:Ne(r.headers.get("accept-language")),...o.detail!==void 0?{detail:o.detail}:{},...o.policyReason!==void 0?{policyReason:o.policyReason}:{}}));return Me(s.status,a,{setCookies:o.setCookies??[]})}}}i(Xt,"createContext");var en=/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}\p{Co}\p{Cs}\p{Cn}]/u;function ce(e){return en.test(e)}i(ce,"hasHiddenCharacters");var tn={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};function v(e){return e.replace(/[&<>"']/g,t=>tn[t]??t)}i(v,"escapeHtml");function De(e){if(e.length===0)return!1;for(let t=0;t<e.length;t+=1){let r=e.charCodeAt(t);if(r!==33&&!(r>=35&&r<=91)&&!(r>=93&&r<=126))return!1}return!0}i(De,"isScopeToken");function de(e,t){let r=e.length;for(;r>0&&e[r-1]===t;)r-=1;return e.slice(0,r)}i(de,"trimTrailing");function ut(e,t){return`<!doctype html>
2
2
  <html lang="en">
3
3
  <head>
4
4
  <meta charset="utf-8">
5
5
  <meta name="viewport" content="width=device-width">
6
- <title>${P(e)}</title>
6
+ <title>${v(e)}</title>
7
7
  <style>
8
8
  html{font:16px/1.55 ui-sans-serif,system-ui,sans-serif;background:Canvas;color:CanvasText}
9
9
  body{margin:0 auto;max-width:34rem;padding:2rem 1rem}
@@ -20,28 +20,28 @@ button.go{background:#0f766e;border-color:#0f766e;color:#fff}
20
20
  <body>
21
21
  ${t}
22
22
  </body>
23
- </html>`}s(st,"document");function Vr(e){let t='<p class="note"><strong>Self-registered application.</strong> Nobody has checked the name above. Go on only if you just asked this application to connect.</p>';switch(e.clientKind){case"static":return"<p>The operator of this service added this application.</p>";case"metadata_document":return e.clientHost===void 0||e.clientHost===""?t:`<p>The description of this application is published at <strong>${P(e.clientHost)}</strong>. The name above is the application's own claim.</p>`;case"dynamic":return t}}s(Vr,"provenance");function Wr(e){let t=e.fieldErrors??{},r=e.submitted??{},n=[...new Set([...Object.keys(t),...Object.keys(r)])];return n.length===0?"":`<section class="facts" role="alert">${n.map((i,a)=>{let c=`field-${a}`,d=Object.hasOwn(t,i)?t[i]:void 0,l=Object.hasOwn(r,i)?r[i]:void 0,g=d===void 0?"":`<span class="note" id="${c}-error">${P(d)}</span>`,h=d===void 0?"":` aria-invalid="true" aria-describedby="${c}-error"`;return`<p><label for="${c}">${P(i)}</label>
24
- <input type="text" id="${c}" name="${P(i)}" value="${P(l??"")}"${h}>
25
- ${g}</p>`}).join(`
26
- `)}</section>`}s(Wr,"correctionFields");function Kt(e){let t=e.clientName??"An application without a name",r=e.redirectIsLoopback?`a program running on this device (${P(e.redirectHost)})`:P(e.redirectHost),n=e.subjectDisplayName===void 0?"":`<p>You are signed in as <strong>${P(e.subjectDisplayName)}</strong>.</p>`,o=e.scopes.map(d=>{let l=Object.hasOwn(e.scopeDescriptions,d)?e.scopeDescriptions[d]:void 0,g=l===void 0?"":` \u2014 ${P(l)}`;return`<li><code>${P(d)}</code>${g}</li>`}).join(""),i=Object.entries(e.hiddenFields).map(([d,l])=>`<input type="hidden" name="${P(d)}" value="${P(l)}">`).join(`
27
- `),a=P(e.decisionField),c=Wr(e);return st("Connect application",`<h1>Connect <strong>${P(t)}</strong>?</h1>
23
+ </html>`}i(ut,"document");function rn(e){let t='<p class="note"><strong>Self-registered application.</strong> Nobody has checked the name above. Go on only if you just asked this application to connect.</p>';switch(e.clientKind){case"static":return"<p>The operator of this service added this application.</p>";case"metadata_document":return e.clientHost===void 0||e.clientHost===""?t:`<p>The description of this application is published at <strong>${v(e.clientHost)}</strong>. The name above is the application's own claim.</p>`;case"dynamic":return t}}i(rn,"provenance");function nn(e){let t=e.fieldErrors??{},r=e.submitted??{},n=[...new Set([...Object.keys(t),...Object.keys(r)])];return n.length===0?"":`<section class="facts" role="alert">${n.map((s,a)=>{let c=`field-${a}`,d=Object.hasOwn(t,s)?t[s]:void 0,l=Object.hasOwn(r,s)?r[s]:void 0,h=d===void 0?"":`<span class="note" id="${c}-error">${v(d)}</span>`,m=d===void 0?"":` aria-invalid="true" aria-describedby="${c}-error"`;return`<p><label for="${c}">${v(s)}</label>
24
+ <input type="text" id="${c}" name="${v(s)}" value="${v(l??"")}"${m}>
25
+ ${h}</p>`}).join(`
26
+ `)}</section>`}i(nn,"correctionFields");function Zt(e){let t=e.clientName??"An application without a name",r=e.redirectIsLoopback?`a program running on this device (${v(e.redirectHost)})`:v(e.redirectHost),n=e.subjectDisplayName===void 0?"":`<p>You are signed in as <strong>${v(e.subjectDisplayName)}</strong>.</p>`,o=e.scopes.map(d=>{let l=Object.hasOwn(e.scopeDescriptions,d)?e.scopeDescriptions[d]:void 0,h=l===void 0?"":` \u2014 ${v(l)}`;return`<li><code>${v(d)}</code>${h}</li>`}).join(""),s=Object.entries(e.hiddenFields).map(([d,l])=>`<input type="hidden" name="${v(d)}" value="${v(l)}">`).join(`
27
+ `),a=v(e.decisionField),c=nn(e);return ut("Connect application",`<h1>Connect <strong>${v(t)}</strong>?</h1>
28
28
  ${n}
29
- ${Vr(e)}
29
+ ${rn(e)}
30
30
  <section class="facts">
31
31
  <p><span>Permissions</span></p><ul>${o}</ul>
32
- <p><span>Service</span> ${P(e.resource)}</p>
32
+ <p><span>Service</span> ${v(e.resource)}</p>
33
33
  <p><span>Result goes to</span> ${r}</p>
34
- <p><span>Application id</span> <code>${P(e.clientId)}</code></p>
34
+ <p><span>Application id</span> <code>${v(e.clientId)}</code></p>
35
35
  </section>
36
36
  <p>Connect only applications you recognise. The connection can be removed again at any time.</p>
37
- <form method="post" action="${P(e.formAction)}">
38
- ${i}
37
+ <form method="post" action="${v(e.formAction)}">
38
+ ${s}
39
39
  ${c}
40
40
  <p class="choices">
41
41
  <button type="submit" name="${a}" value="approve" class="go">Connect</button>
42
42
  <button type="submit" name="${a}" value="deny">Cancel</button>
43
43
  </p>
44
- </form>`)}s(Kt,"defaultConsentPage");function Vt(e){return st(e.title,`<h1>${P(e.title)}</h1>
45
- <p>${P(e.message)}</p>${e.detail===void 0?"":`
46
- <p class="note">${P(e.detail)}</p>`}`)}s(Vt,"defaultErrorPage");function fe(e){if(e.length>Ae||!e.startsWith("https://")||e.includes("#"))return!1;let t;try{t=new URL(e)}catch{return!1}return t.hostname!==""&&t.username===""&&t.password===""&&t.pathname.length>1&&t.href===e}s(fe,"isMetadataDocumentClientId");function Y(e,t){if(typeof e!="string")return;let r=e.trim();if(!(r.length===0||r.length>t))return ie(r)?void 0:r}s(Y,"cleanClientName");function Jr(e){return e==="authorization_code"||e==="refresh_token"}s(Jr,"isSupportedGrantType");function me(e,t){if(e===void 0)return["authorization_code"];if(!z(e)||!e.includes("authorization_code"))return;let r=e.filter(Jr);if(!(t&&r.length!==e.length))return[...new Set(r)]}s(me,"parseGrantTypes");function Ue(e,t,r,n){if(e===void 0)return null;if(typeof e!="string"||e.length>n)return;let o=[...new Set(e.split(" ").filter(a=>a.length>0))],i=o.filter(a=>t.includes(a));if(i.length!==0&&!(r&&i.length<o.length))return i}s(Ue,"parseClientScopes");var Yr=2048,Xr=["code","state","iss","error","error_description","error_uri"];function he(e){try{return new URL(e)}catch{return}}s(he,"tryParse");function be(e){return e.protocol==="http:"&&de.has(e.hostname)}s(be,"isLoopbackHttp");function Jt(e){let t=he(e);return t!==void 0&&be(t)}s(Jt,"isLoopbackRedirectUri");function Ce(e,t={redirectUriLength:Yr}){if(e.length>t.redirectUriLength)return"over_length";let r=he(e);return r===void 0?"unparseable":e.includes("#")?"has_fragment":r.username.length>0||r.password.length>0?"has_credentials":!(r.protocol==="https:"&&r.hostname.length>0)&&!be(r)?"disallowed_scheme":Xr.some(o=>r.searchParams.has(o))?"reserved_query_parameter":void 0}s(Ce,"redirectUriProblem");function it(e,t){return Ce(e,t)===void 0}s(it,"isAcceptableRedirectUri");function Zr(e){return e>=48&&e<=57}s(Zr,"isDigit");function Wt(e,t){let r=`${t.protocol}//${t.hostname}`;if(e.slice(0,r.length).toLowerCase()!==r.toLowerCase())return e;let n=e.slice(r.length);if(n.startsWith(":")){let o=1;for(;o<n.length&&Zr(n.charCodeAt(o));)o+=1;n=n.slice(o)}return r.toLowerCase()+n}s(Wt,"portless");function Qr(e,t,r){if(!it(t,r))return!1;if(t===e)return!0;let n=he(e),o=he(t);return n===void 0||o===void 0||!be(n)||!be(o)?!1:Wt(e,n)===Wt(t,o)}s(Qr,"redirectUriMatches");function Yt(e,t,r){return e.some(n=>Qr(n,t,r))}s(Yt,"matchesAnyRedirectUri");function Le(e){let t=he(e);return t===void 0?"":be(t)?t.hostname:t.host}s(Le,"redirectHostOf");function Xt(e){return he(e)?.origin}s(Xt,"originOf");function Ne(e,t){let r=new URL(e);for(let[n,o]of Object.entries(t))o!==void 0&&r.searchParams.append(n,o);return r.toString()}s(Ne,"buildRedirect");function Zt(e,t={}){for(let[n,o]of Object.entries(t)){if(!e.includes(n))throw new w(`scopeDescriptions names ${n}, which is not in scopes`);if(o.trim()===""||o.length>200||ie(o))throw new w(`scopeDescriptions.${n} must be 1 to 200 visible characters`)}let r=Object.fromEntries(Object.entries(t));return Object.setPrototypeOf(r,null),Object.freeze(r)}s(Zt,"resolveScopeDescriptions");function Qt(e=[],t,r,n){let o=new Map;for(let i of e){let a=i.clientId,c=`clients[${JSON.stringify(a)}]`;if(a.trim()===""||a.length>255||ie(a))throw new w(`${c}: clientId must be 1 to 255 visible characters`);if(fe(a)||/^https:/i.test(a))throw new w(`${c}: clientId must not be an https URL`);if(o.has(a))throw new w(`${c}: listed twice`);if(i.redirectUris.length===0||i.redirectUris.length>r.redirectUris)throw new w(`${c}: list 1 to ${r.redirectUris} redirectUris`);for(let g of i.redirectUris){let h=Ce(g,r);if(h!==void 0)throw new w(`${c}: redirect URI refused (${h})`)}let d=i.clientName===void 0?void 0:Y(i.clientName,r.clientNameLength);if(i.clientName!==void 0&&d===void 0)throw new w(`${c}: clientName is not a valid display name`);let l=me(i.grantTypes??["authorization_code","refresh_token"],!0);if(l===void 0)throw new w(`${c}: grantTypes must include authorization_code`);if(i.scopes?.some(g=>!t.includes(g))===!0)throw new w(`${c}: scopes must be a subset of scopes`);if(i.scopes?.length===0)throw new w(`${c}: scopes must not be empty`);o.set(a,Ht({clientId:a,redirectUris:[...new Set(i.redirectUris)],kind:"static",createdAt:n(),grantTypes:l,...i.scopes!==void 0?{scopes:[...i.scopes]}:{},...d!==void 0?{clientName:d}:{}}))}return o}s(Qt,"resolveStaticClients");function at(e,t,r){let n;try{n=new URL(t)}catch{throw new w(`${e} must be an absolute URL`)}if(t.includes("#")||n.search!==""||t.includes("?"))throw new w(`${e} must have no query or fragment`);if(n.username!==""||n.password!=="")throw new w(`${e} must have no userinfo`);let o=n.protocol==="http:"&&de.has(n.hostname);if(n.protocol!=="https:"&&!(o&&r))throw new w(`${e} must use https (http is allowed only for localhost with allowInsecureLocalhost)`);return n}s(at,"parseServerUrl");function ct(e){return ae(e,"/")}s(ct,"trimPath");function er(e,t,r,n,o){let i=t??r;if(!Number.isInteger(i)||i<n||i>o)throw new w(`lifetimes.${e} must be an integer from ${n} to ${o}`);return i*1e3}s(er,"seconds");function en(e,t,r){let n=t??r;if(!Number.isInteger(n)||n<1)throw new w(`limits.${e} must be a positive integer`);return n}s(en,"positive");function tr(e={}){let t=s(r=>en(r,e[r],wt[r]),"pick");return{clientNameLength:t("clientNameLength"),redirectUris:t("redirectUris"),redirectUriLength:t("redirectUriLength"),stateLength:t("stateLength"),scopeLength:t("scopeLength"),registrationBytes:t("registrationBytes"),formBytes:t("formBytes"),clientMetadataBytes:t("clientMetadataBytes"),clientMetadataTimeoutMs:t("clientMetadataTimeoutMs"),clientMetadataFailures:t("clientMetadataFailures"),grantContextBytes:t("grantContextBytes"),consentDetailsBytes:t("consentDetailsBytes"),grantDataBytes:t("grantDataBytes")}}s(tr,"resolveLimits");function tn(e,t){let r=t.split("/").slice(1);if(!t.startsWith("/")||t.includes("//")||/[\\?#\s]/.test(t)||r.some(n=>n==="."||n===".."))throw new w(`paths.${e} must be one absolute path without //, \\, ?, #, dot segments or whitespace`);return t}s(tn,"checkPath");function rr(e,t={}){let r=s(i=>tn(i,t[i]??`${e}/${i}`),"pick"),n={authorize:r("authorize"),callback:r("callback"),consent:r("consent"),token:r("token"),register:r("register"),revoke:r("revoke")},o=Object.values(n);if(new Set(o).size!==o.length)throw new w("paths must be distinct");return n}s(rr,"resolvePaths");var rn=/^sha256-[A-Za-z0-9+/]{43}=$/,nn=/^__Host-[A-Za-z0-9_.-]{0,40}$/;function nr(e,t){let r=e.allowInsecureLocalhost===!0,n=at("issuer",e.issuer,r),o=ct(n.pathname),i=`${n.origin}${o}`;if(e.issuer!==i&&!(o===""&&e.issuer===`${i}/`))throw new w(`issuer must be in normalized form, for example ${i}`);let a=at("resource",e.resource,r),c=ct(a.pathname),d=e.scopes??_t;if(d.length===0||!d.every(Oe))throw new w("scopes must be non-empty scope tokens");let l=e.defaultScopes??d;if(l.length===0||!l.every(C=>d.includes(C)))throw new w("defaultScopes must be a subset of scopes");let g=e.refreshReuseGraceSeconds??kt;if(!Number.isInteger(g)||g<0||g>Ye)throw new w(`refreshReuseGraceSeconds must be an integer from 0 to ${Ye}`);let h=e.lifetimes??{},u=s(C=>er(C,h[C],yt[C],Je[C].min,Je[C].max),"lifetime"),p=rr(o,e.paths),f=e.cookiePrefix??Rt;if(!nn.test(f))throw new w("cookiePrefix must start with __Host- and use only letters, digits, '.', '_' and '-'");let m=tr(e.limits),y=Pe(e.now??Date.now),k=[...e.scriptHashes??[]];for(let C of k)if(!rn.test(C))throw new w("scriptHashes entries must look like sha256-<base64 of 32 bytes>");let R=e.consentReplaySeconds??At;if(!Number.isInteger(R)||R<0||R>Qe)throw new w(`consentReplaySeconds must be an integer from 0 to ${Qe}`);let x=Et,v=xt,L=c===""?[x]:[`${x}${c}`,x],q=o===""?[v]:[`${v}${o}`,v],D=new Set([...L,...q,a.pathname,c===""?"/":c]);for(let[C,G]of Object.entries(p))if(D.has(G))throw new w(`paths.${C} collides with a metadata path or the resource path`);return{issuer:i,issuerOrigin:n.origin,resource:e.resource,resourceMetadataUrl:`${a.origin}${x}${c}`,resourceMetadataPaths:L,authorizationServerMetadataPaths:q,scopes:[...d],defaultScopes:[...l],identityProvider:e.identityProvider,store:e.store,sealer:e.sealer,renderConsentPage:e.renderConsentPage??t.consent,renderErrorPage:e.renderErrorPage??t.error,accessTokenTtlMs:u("accessToken"),refreshTokenTtlMs:u("refreshToken"),grantTtlMs:u("grant"),codeTtlMs:u("authorizationCode"),pendingTtlMs:u("pendingAuthorization"),clientMetadataCacheMs:u("clientMetadataCache"),clientMetadataFailureMs:u("clientMetadataFailure"),limits:m,cookiePrefix:f,scriptHashes:k,consentReplayMs:R*1e3,refreshReuseGraceMs:g*1e3,clientIdMetadataDocuments:e.clientIdMetadataDocuments??!0,dynamicClientRegistration:e.dynamicClientRegistration??!0,paths:p,callbackUrl:`${n.origin}${p.callback}`,trustProxy:e.trustProxy??!1,now:y,scopeDescriptions:Zt(d,e.scopeDescriptions),staticClients:Qt(e.clients,d,m,y),...e.resourceName!==void 0?{resourceName:e.resourceName}:{},...e.rateLimit?{rateLimit:e.rateLimit}:{},...e.getClientIp?{getClientIp:e.getClientIp}:{},...e.onEvent?{onEvent:e.onEvent}:{},...e.fetchClientMetadata?{fetchClientMetadata:e.fetchClientMetadata}:{},...e.authorizeClient?{authorizeClient:e.authorizeClient}:{},...e.allowRegistration?{allowRegistration:e.allowRegistration}:{},...e.mapSubject?{mapSubject:e.mapSubject}:{},...e.allowSubject?{allowSubject:e.allowSubject}:{},...e.allowClientMetadataUrl?{allowClientMetadataUrl:e.allowClientMetadataUrl}:{},...e.getGrantContext?{getGrantContext:e.getGrantContext}:{},...e.getConsentDetails?{getConsentDetails:e.getConsentDetails}:{},...e.readConsentFields?{readConsentFields:e.readConsentFields}:{},...e.beforeGrant?{beforeGrant:e.beforeGrant}:{},...e.afterGrant?{afterGrant:e.afterGrant}:{},...e.beforeTokenIssue?{beforeTokenIssue:e.beforeTokenIssue}:{}}}s(nr,"resolveOptions");import{safeFetch as on}from"@gydr-ai/safe-fetch";var I=class extends Error{static{s(this,"ClientMetadataError")}reason;constructor(t){super(`Client ID Metadata Document not accepted (${t})`),this.name="ClientMetadataError",this.reason=t}};function sn(e,t,r,n){if(!O(t))throw new I("not_an_object");if(t.client_id!==e)throw new I("client_id_differs_from_url");let o=t.token_endpoint_auth_methods_supported;if(t.token_endpoint_auth_method!==void 0&&t.token_endpoint_auth_method!=="none"||o!==void 0&&(!z(o)||!o.includes("none"))||t.client_secret!==void 0)throw new I("confidential_client");let i=me(t.grant_types,!1);if(i===void 0)throw new I("grant_types_unusable");if(t.response_types!==void 0&&(!z(t.response_types)||!t.response_types.includes("code")))throw new I("response_types_unusable");let a=Ue(t.scope,n.scopes,!1,n.limits.scopeLength);if(a===void 0)throw new I("scope_unusable");if(!z(t.redirect_uris))throw new I("redirect_uris_absent");let c=t.redirect_uris.filter(l=>it(l,n.limits)).slice(0,n.limits.redirectUris);if(c.length===0)throw new I("redirect_uris_unusable");let d=Y(t.client_name,n.limits.clientNameLength);return{clientId:e,redirectUris:c,kind:"metadata_document",createdAt:r,grantTypes:i,...a!==null?{scopes:a}:{},...d!==void 0?{clientName:d}:{}}}s(sn,"validateClientMetadata");function an(e){return(t,r)=>on(t,{method:"GET",headers:{Accept:"application/json"},redirect:"error",signal:r.signal},{timeoutMs:e.limits.clientMetadataTimeoutMs,maxResponseBytes:e.limits.clientMetadataBytes,label:"client metadata"})}s(an,"bundledFetcher");function or(e,t){return t.aborted?Promise.reject(new I("timeout")):new Promise((r,n)=>{let o=s(()=>{n(new I("timeout"))},"onAbort");t.addEventListener("abort",o,{once:!0}),e.then(i=>{t.removeEventListener("abort",o),r(i)},i=>{t.removeEventListener("abort",o),n(i instanceof Error?i:new I(De(i)))})})}s(or,"beforeAbort");async function cn(e,t,r){let n=Number(e.headers.get("content-length"));if(Number.isFinite(n)&&n>t)throw await e.body?.cancel().catch(()=>{}),new I("too_large");if(e.body===null)return"";let o=e.body.getReader(),i=[],a=0;try{for(;;){let c=await or(o.read(),r);if(c.done)break;let d=c.value;if(!(d instanceof Uint8Array))throw new I("not_bytes");if(a+=d.byteLength,a>t)throw new I("too_large");i.push(d)}}catch(c){throw await o.cancel().catch(()=>{}),c}return Buffer.concat(i).toString("utf8")}s(cn,"readLimited");function De(e){return e instanceof I?e.reason:O(e)?typeof e.code=="string"?e.code:typeof e.reason=="string"?e.reason:"unreachable":"unreachable"}s(De,"failureReason");function dn(e){if(e===null)return;let t;for(let r of e.split(",")){let[n="",o=""]=r.split("=",2);switch(n.trim().toLowerCase()){case"no-store":case"no-cache":return 0;case"max-age":{let a=o.trim().replace(/^"(.*)"$/,"$1");t=/^\d{1,10}$/.test(a)?Number(a):0;break}default:break}}return t}s(dn,"cacheControlSeconds");async function sr(e,t,r){let n=r.fetchClientMetadata??an(r),o=AbortSignal.timeout(r.limits.clientMetadataTimeoutMs),i,a;try{let d=await or(n(e,{signal:o}),o);if(d.status!==200)throw await d.body?.cancel().catch(()=>{}),new I(`status_${d.status}`);a=dn(d.headers.get("cache-control")),i=await cn(d,r.limits.clientMetadataBytes,o)}catch(d){throw d instanceof I?d:new I(De(d))}let c;try{c=JSON.parse(i)}catch{throw new I("invalid_json")}return{client:sn(e,c,t,r),maxAgeSeconds:a}}s(sr,"fetchClientMetadata");function dt(e){try{return new URL(e).host}catch{return""}}s(dt,"hostOf");function ir(e){let t;try{t=new URL(e)}catch{return}let r=ae(t.hostname,"."),n=ae(t.pathname,"/");return`${t.protocol}//${r}:${t.port}${n}`}s(ir,"serverIdentity");function un(e,t){let r=ir(e);return r!==void 0&&r===ir(t)}s(un,"isIssuerUrl");async function He(e,t){let{options:r}=e;if(t.length>Ae)return;if(!fe(t)){let g=r.staticClients.get(t);if(g!==void 0)return g;let h=await r.store.getClient(t);return h?.kind==="metadata_document"?void 0:h}if(!r.clientIdMetadataDocuments)return;if(un(t,r.issuer)){await e.emit({type:"client_metadata_refused",host:dt(t),reason:"client_id_is_issuer"});return}let n=r.allowClientMetadataUrl;if(n!==void 0&&!await pe(()=>n(t))){await e.emit({type:"client_metadata_refused",host:dt(t),reason:"not_allowed_by_policy"});return}let o=await r.store.getCachedClientMetadata(t);if(o?.clientId===t)return o;let{failures:i,inflight:a}=e.cimd,c=i.get(t);if(c!==void 0){if(c>r.now())return;i.delete(t)}let d=a.get(t);if(d!==void 0)return d;let l=ln(e,t).finally(()=>{a.delete(t)});return a.set(t,l),l}s(He,"resolveClient");async function ln(e,t){let{options:r}=e,n=r.now(),o;try{o=await sr(t,n,r)}catch(c){pn(e,t),await e.emit({type:"client_metadata_refused",host:dt(t),reason:De(c)});return}let i=o.maxAgeSeconds,a=i===void 0?r.clientMetadataCacheMs:Math.min(i*1e3,r.clientMetadataCacheMs);return a>0&&await r.store.putCachedClientMetadata(t,o.client,n+a),o.client}s(ln,"downloadAndRemember");function pn(e,t){let{options:r}=e,{failures:n}=e.cimd;if(r.clientMetadataFailureMs!==0){for(n.delete(t);n.size>=r.limits.clientMetadataFailures;){let o=n.keys().next();if(o.done===!0)break;n.delete(o.value)}n.set(t,r.now()+r.clientMetadataFailureMs)}}s(pn,"rememberFailure");function $e(e,t){let r=e.headers.get("cookie");if(r!==null)for(let n of r.split(";")){let o=n.indexOf("=");if(o!==-1&&n.slice(0,o).trim()===t)return n.slice(o+1).trim()}}s($e,"readCookie");function ze(e,t,r){return`${e}=${t}; Path=/; Max-Age=${r}; HttpOnly; Secure; SameSite=Lax`}s(ze,"hostCookie");function Ge(e){return`${e}=; Path=/; Max-Age=0; HttpOnly; Secure; SameSite=Lax`}s(Ge,"clearHostCookie");function X(e,t){return e+A(`binding:${t}`).slice(0,20)}s(X,"bindingCookieName");function Z(e){let t=new Map;for(let[r,n]of e){let o=t.get(r);o?o.push(n):t.set(r,[n])}return t}s(Z,"groupParams");function _(e,t){let r=e.get(t)?.[0];return r===void 0||r===""?void 0:r}s(_,"single");function Q(e,t){return t.filter(r=>(e.get(r)?.length??0)>1)}s(Q,"repeatedDefined");function ar(e){let t=e.indexOf("://");if(t===-1)return;let r=e.indexOf("/",t+3),n=r===-1?e.length:r;return{authority:e.slice(0,n).toLowerCase(),rest:e.slice(n)}}s(ar,"splitAuthority");function ge(e,t){if(t===e)return!0;let r=ar(e),n=ar(t);return r!==void 0&&n!==void 0&&r.authority===n.authority&&r.rest===n.rest}s(ge,"sameResource");function cr(e,t,r,n){if(e===void 0)return r;if(e.length>n)return;let o=[...new Set(e.split(" ").filter(a=>a.length>0))];return o.length===0?void 0:o.every(a=>Oe(a)&&t.includes(a))?o:void 0}s(cr,"resolveScopes");var fn=["client_id","redirect_uri","response_type","code_challenge","code_challenge_method","resource","scope","state","prompt"];async function dr(e,t){let{options:r}=e,{limits:n}=r;if(!await e.allowed(t,"authorize"))return e.errorPage(t,"rate_limited");let o=Z(new URL(t.url).searchParams),i=s(async(C,G,j={})=>(await e.emit({type:"authorization_refused",reason:C,...G!==void 0?{clientId:G}:{}}),e.errorPage(t,C,j)),"refuse");if(Q(o,fn).length>0)return i("repeated_parameter");let a=_(o,"client_id"),c=a===void 0?void 0:await He(e,a);if(a===void 0||c===void 0)return i("client_unknown");let d=_(o,"redirect_uri"),[l]=c.redirectUris.length===1?c.redirectUris:[],g=d??l;if(g===void 0||!Yt(c.redirectUris,g,n))return i("redirect_uri_not_registered",a);let h=_(o,"state");if(h!==void 0&&h.length>n.stateLength)return i("invalid_request",a,{detail:`The state value exceeds ${n.stateLength} characters`});if(_(o,"response_type")!=="code")return i("unsupported_response_type",a,{detail:"Only the authorization code flow is offered"});let u=_(o,"code_challenge");if(u===void 0||!Nt(u))return i("invalid_request",a,{detail:"A 43-character S256 code_challenge must accompany the request"});if(_(o,"code_challenge_method")!=="S256")return i("invalid_request",a,{detail:"The only accepted code_challenge_method is S256"});let p=_(o,"resource");if(p===void 0||!ge(r.resource,p))return i("invalid_target",a,{detail:`Tokens from this server are only for ${r.resource}`});let f=c.scopes??r.scopes,m=r.defaultScopes.filter(C=>f.includes(C)),y=cr(o.get("scope")?.[0],f,m.length>0?m:f,n.scopeLength);if(y===void 0)return i("invalid_scope",a);if(_(o,"prompt")?.split(" ").includes("none"))return i("consent_required",a);let k=r.authorizeClient;if(k!==void 0){let C=await se(()=>k({client:M(c),redirectUri:g,scopes:M(y),request:t}));if(!C.allowed)return i("access_denied",a,C.reason===void 0?{}:{policyReason:C.reason})}let R=N(),x=N(),v=N(),L=N(),q={id:R,clientId:c.clientId,clientKind:c.kind,redirectUri:g,codeChallenge:u,resource:r.resource,scopes:y,upstreamCodeVerifier:v,upstreamNonce:L,bindingHash:A(x),allowRefresh:c.grantTypes?.includes("refresh_token")??!0,expiresAt:r.now()+r.pendingTtlMs,...c.clientName!==void 0?{clientName:c.clientName}:{},...h!==void 0?{state:h}:{}};await r.store.putPendingAuthorization(q);let D=await r.identityProvider.authorizationUrl({state:R,codeChallenge:et(v),redirectUri:r.callbackUrl,nonce:L});return await e.emit({type:"authorization_started",clientId:c.clientId,scopes:y}),ne(D,[ze(X(r.cookiePrefix,R),x,Math.ceil(r.pendingTtlMs/1e3))])}s(dr,"handleAuthorize");import{randomUUID as wn}from"node:crypto";function mn(e){try{return new URL(e).host}catch{return""}}s(mn,"documentHost");function Fe(e,t,r,n,o={}){let{options:i}=e,a=i.renderConsentPage(M({clientId:r.clientId,clientKind:r.clientKind,redirectUri:r.redirectUri,redirectHost:Le(r.redirectUri),redirectIsLoopback:Jt(r.redirectUri),scopes:r.scopes,scopeDescriptions:{...i.scopeDescriptions},resource:r.resource,formAction:i.paths.consent,hiddenFields:{[K.id]:r.id,[K.csrf]:n},decisionField:K.decision,locales:je(t.headers.get("accept-language")),...r.clientName!==void 0?{clientName:r.clientName}:{},...r.clientKind==="metadata_document"?{clientHost:mn(r.clientId)}:{},...r.displayName!==void 0?{subjectDisplayName:r.displayName}:{},...r.details!==void 0?{details:r.details}:{},...o.fieldErrors!==void 0?{fieldErrors:o.fieldErrors}:{},...o.submitted!==void 0?{submitted:o.submitted}:{}})),c=Xt(r.redirectUri),d=[...o.setCookies??[]];return o.binding!==void 0&&d.push(ze(X(i.cookiePrefix,r.id),o.binding,Math.ceil(i.pendingTtlMs/1e3))),Se(o.status??200,a,{formActionOrigins:c===void 0?[]:[c],setCookies:d,scriptHashes:i.scriptHashes})}s(Fe,"consentPageResponse");var hn=512;function gn(e){return typeof e=="string"&&e!==""&&e.length<=hn&&e.trim()===e&&e.normalize("NFC")===e&&!ie(e)}s(gn,"isUsableSubject");function yn(e){if(typeof e!="object"||e===null)return;let t=Reflect.get(e,"subject"),r=Reflect.get(e,"displayName");return{subject:t,displayName:r}}s(yn,"readMapped");async function ur(e,t,r){let{mapSubject:n,allowSubject:o,limits:i}=e.options,a=t.claims??{},c=t.subject,d=t.displayName;if(n!==void 0){let h;try{h=yn(await n(M({subject:t.subject,claims:a,...t.displayName!==void 0?{displayName:t.displayName}:{}})))}catch{return{ok:!1}}if(h===void 0)return{ok:!1};c=h.subject,d=h.displayName}if(!gn(c))return{ok:!1};let l=d===void 0?void 0:Y(d,i.clientNameLength),g=l===void 0?{subject:c}:{subject:c,displayName:l};if(o!==void 0){let h=await se(()=>o(M({...g,claims:a,client:r})));if(!h.allowed)return h.reason===void 0?{ok:!1}:{ok:!1,policyReason:h.reason}}return{ok:!0,person:g}}s(ur,"resolvePerson");var _n=["state","code","error","error_description","error_uri","iss"];async function lr(e,t){let{options:r}=e;if(!await e.allowed(t,"callback"))return e.errorPage(t,"rate_limited");let n=Z(new URL(t.url).searchParams);if(Q(n,_n).length>0)return e.errorPage(t,"malformed_response");let o=_(n,"state");if(o===void 0)return e.errorPage(t,"flow_ended");let i=X(r.cookiePrefix,o),a=Ge(i),c=await r.store.getPendingAuthorization(o);if(c===void 0||S(c.expiresAt,r.now()))return e.errorPage(t,"flow_ended");let d=$e(t,i);if(d===void 0||!ue(A(d),c.bindingHash))return await e.emit({type:"flow_binding_mismatch",step:"callback"}),e.errorPage(t,"browser_mismatch",{setCookies:[a]});let l=await r.store.consumePendingAuthorization(o);if(l===void 0||S(l.expiresAt,r.now())||l.bindingHash!==c.bindingHash)return e.errorPage(t,"flow_ended");let g=_(n,"error");if(g!==void 0){let j=g==="access_denied";return await e.emit({type:"identity_provider_error",clientId:l.clientId,reason:j?"person_cancelled":"provider_reported_error"}),ne(Ne(l.redirectUri,{error:j?"access_denied":"server_error",error_description:j?"The person stopped at the sign-in step":"The identity provider could not complete the sign-in",state:l.state,iss:r.issuer}),[a])}let h=_(n,"code");if(h===void 0)return e.errorPage(t,"malformed_response",{setCookies:[a]});let u=_(n,"iss"),p;try{p=await r.identityProvider.exchangeCode({code:h,codeVerifier:l.upstreamCodeVerifier,redirectUri:r.callbackUrl,nonce:l.upstreamNonce,...u!==void 0?{issuer:u}:{}})}catch(j){return await e.emit({type:"identity_provider_error",clientId:l.clientId,reason:j instanceof Error?j.name:"exchange_failed"}),e.errorPage(t,"sign_in_not_confirmed",{setCookies:[a]})}let f=s(async()=>{p.refreshToken!==void 0&&await rt(e,p.refreshToken)},"releaseUpstream");if(typeof p.subject!="string"||p.subject.length===0)return await f(),await e.emit({type:"identity_provider_error",clientId:l.clientId,reason:"subject_missing"}),e.errorPage(t,"sign_in_not_confirmed",{setCookies:[a]});let m={clientId:l.clientId,kind:l.clientKind,...l.clientName!==void 0?{clientName:l.clientName}:{}},y=await ur(e,p,m);if(!y.ok)return await f(),await e.emit({type:"identity_provider_error",clientId:l.clientId,reason:"subject_not_permitted"}),e.errorPage(t,"subject_not_permitted",{setCookies:[a],...y.policyReason!==void 0?{policyReason:y.policyReason}:{}});let{person:k}=y,R;if(r.getConsentDetails!==void 0)try{R=W(await r.getConsentDetails(Object.freeze({...M({subject:k.subject,client:m,scopes:[...l.scopes]}),request:t})),r.limits.consentDetailsBytes,"getConsentDetails")}catch{return await f(),e.errorPage(t,"server_error",{setCookies:[a]})}let x=r.now(),v=wn(),L=N(),{sealer:q}=r,D=p.expiresIn!==void 0&&Number.isFinite(p.expiresIn)?Math.min(Math.max(p.expiresIn,0),Te):void 0,C={id:N(),grantId:v,clientId:l.clientId,clientKind:l.clientKind,redirectUri:l.redirectUri,codeChallenge:l.codeChallenge,resource:l.resource,scopes:l.scopes,subject:k.subject,csrfHash:A(L),bindingHash:l.bindingHash,expiresAt:x+r.pendingTtlMs,...l.allowRefresh!==void 0?{allowRefresh:l.allowRefresh}:{},...l.clientName!==void 0?{clientName:l.clientName}:{},...l.state!==void 0?{state:l.state}:{},...k.displayName!==void 0?{displayName:k.displayName}:{},...R!==void 0?{details:R}:{},...p.refreshToken!==void 0?{sealedUpstreamRefreshToken:await q.seal(p.refreshToken,v)}:{},...p.accessToken!==void 0&&D!==void 0?{sealedUpstreamAccessToken:await q.seal(p.accessToken,`${v}#access`),upstreamAccessTokenExpiresAt:x+D*1e3}:{}},G;try{G=Fe(e,t,C,L,{binding:d,setCookies:[a]})}catch(j){throw await f(),j}return await r.store.putConsentRequest(C),G}s(lr,"handleCallback");var F=class extends Error{static{s(this,"BodyTooLargeError")}constructor(){super("Body exceeds the configured size limit"),this.name="BodyTooLargeError"}};function ye(e,t){let r=e.headers.get("content-type");if(r===null)return!1;let[n]=r.split(";");return(n??"").trim().toLowerCase()===t}s(ye,"hasContentType");async function we(e,t){let r=Number(e.headers.get("content-length"));if(Number.isFinite(r)&&r>t)throw new F;if(e.body===null)return"";let n=e.body.getReader(),o=[],i=0;for(;;){let a=await n.read();if(a.done)break;let c=a.value;if(!(c instanceof Uint8Array))throw new TypeError("Body is not bytes");if(i+=c.byteLength,i>t)throw await n.cancel(),new F;o.push(c)}return Buffer.concat(o).toString("utf8")}s(we,"readBody");var fr=Object.values(K),kn=50,pr=200;function Rn(e){let t=[];for(let[r,n]of e){let[o]=n;!fr.includes(r)&&o!==void 0&&t.push([r,o])}return Object.fromEntries(t)}s(Rn,"extraFields");function bn(e){if(!O(e))return;let t=Object.entries(e);if(t.length===0||t.length>kn)return;let r=[];for(let[n,o]of t){if(typeof o!="string"||o===""||o.length>pr||n.length>pr)return;r.push([n,o])}return Object.fromEntries(r)}s(bn,"readFieldErrors");function mr(e){return{clientId:e.clientId,kind:e.clientKind,...e.clientName!==void 0?{clientName:e.clientName}:{}}}s(mr,"hookClient");async function Cn(e,t,r){let n=e.options.readConsentFields;if(n===void 0)return{kind:"accepted",grantData:void 0};let o;try{o=await n(M({form:{...r},details:t.details,subject:t.subject,client:mr(t),scopes:[...t.scopes]}))}catch{return{kind:"failed"}}if(!O(o))return{kind:"failed"};switch(o.ok){case!0:try{return{kind:"accepted",grantData:W(o.grantData,e.options.limits.grantDataBytes,"readConsentFields")}}catch{return{kind:"failed"}}case!1:{let i=bn(o.fieldErrors);return i===void 0?{kind:"failed"}:{kind:"correct",fieldErrors:i}}default:return{kind:"failed"}}}s(Cn,"readFields");async function hr(e,t){let{options:r}=e;if(!await e.allowed(t,"consent"))return e.errorPage(t,"rate_limited");let n=t.headers.get("origin");if(n!==null&&n!=="null"&&n!==r.issuerOrigin)return e.errorPage(t,"consent_unavailable");if(!ye(t,Ee))return e.errorPage(t,"unsupported_submission");let o;try{o=Z(new URLSearchParams(await we(t,r.limits.formBytes)))}catch(U){if(U instanceof F)return e.errorPage(t,"consent_unavailable");throw U}if(Q(o,fr).length>0)return e.errorPage(t,"consent_unavailable");let i=_(o,K.id),a=_(o,K.csrf);if(i===void 0||a===void 0)return e.errorPage(t,"consent_unavailable");let{store:c,sealer:d}=r,l=X(r.cookiePrefix,i),g=Ge(l),h=$e(t,l),u=s(()=>e.errorPage(t,"consent_unavailable",{setCookies:[g]}),"ended"),p=h===void 0?void 0:A(`${A(h)}:${A(a)}`),f=s(async()=>{if(p===void 0||c.getConsentOutcome===void 0)return u();let U=await c.getConsentOutcome(p);if(U===void 0)return u();let H;try{H=JSON.parse(await d.open(U,p))}catch{return u()}return!O(H)||typeof H.location!="string"||typeof H.expiresAt!="number"||S(H.expiresAt,r.now())?u():ne(H.location,[g],303)},"replay"),m=await c.getConsentRequest(i);if(m===void 0)return f();let y=s(()=>nt(e,m.sealedUpstreamRefreshToken,m.grantId),"releaseUpstream"),k=s(async()=>{await c.consumeConsentRequest(i),await y()},"abandon");if(S(m.expiresAt,r.now()))return await k(),u();let R=ue(A(a),m.csrfHash),x=h!==void 0&&ue(A(h),m.bindingHash);if(!R||!x)return await e.emit({type:"flow_binding_mismatch",step:"consent"}),await k(),u();let v=_(o,K.decision)===St,L;if(v){let U=Rn(o),H=await Cn(e,m,U);switch(H.kind){case"correct":return Fe(e,t,m,a,{status:400,fieldErrors:H.fieldErrors,submitted:{...U}});case"failed":return await k(),e.errorPage(t,"server_error",{setCookies:[g]});case"accepted":L=H.grantData;break}}if((await c.consumeConsentRequest(i))?.csrfHash!==m.csrfHash)return f();let D=s(async U=>{let H=Ne(m.redirectUri,{...U,state:m.state,iss:r.issuer});if(p!==void 0&&r.consentReplayMs>0&&c.putConsentOutcome!==void 0&&c.getConsentOutcome!==void 0){let gt=r.now()+r.consentReplayMs;await c.putConsentOutcome(p,await d.seal(JSON.stringify({location:H,expiresAt:gt}),p),gt)}return ne(H,[g],303)},"answer");if(!v)return await y(),await e.emit({type:"consent_declined",clientId:m.clientId,subject:m.subject}),D({error:"access_denied",error_description:"The person declined to grant access"});let C=r.beforeGrant;if(C!==void 0){let U=await se(()=>C(Object.freeze({...M({subject:m.subject,client:mr(m),scopes:[...m.scopes],grantData:L}),request:t})));if(!U.allowed)return await y(),await e.emit({type:"authorization_refused",clientId:m.clientId,reason:U.reason??"before_grant"}),D({error:"access_denied",error_description:"Access was not granted"})}let G=r.now(),j={grantId:m.grantId,clientId:m.clientId,subject:m.subject,scopes:m.scopes,resource:m.resource,createdAt:G,expiresAt:G+r.grantTtlMs,...L!==void 0?{data:L}:{},...m.allowRefresh!==void 0?{allowRefresh:m.allowRefresh}:{},...m.clientName!==void 0?{clientName:m.clientName}:{},...m.displayName!==void 0?{displayName:m.displayName}:{},...m.sealedUpstreamRefreshToken!==void 0?{sealedUpstreamRefreshToken:m.sealedUpstreamRefreshToken}:{},...m.sealedUpstreamAccessToken!==void 0&&m.upstreamAccessTokenExpiresAt!==void 0?{sealedUpstreamAccessToken:m.sealedUpstreamAccessToken,upstreamAccessTokenExpiresAt:m.upstreamAccessTokenExpiresAt}:{}};await c.putGrant(j);let mt=N();await c.putAuthorizationCode({codeHash:A(mt),grantId:j.grantId,clientId:m.clientId,redirectUri:m.redirectUri,codeChallenge:m.codeChallenge,resource:m.resource,scopes:m.scopes,expiresAt:G+r.codeTtlMs});let ht=r.afterGrant;if(ht!==void 0)try{await ht(Object.freeze({grant:le(j)}))}catch(U){return await c.deleteGrant(j.grantId),await y(),await e.emit({type:"unexpected_failure",where:"afterGrant",errorName:U instanceof Error?U.name:typeof U}),D({error:"server_error",error_description:"The connection could not be completed"})}return await e.emit({type:"consent_approved",grantId:j.grantId,clientId:j.clientId,subject:j.subject,scopes:j.scopes}),D({code:mt})}s(hr,"handleConsent");function ee(e){return $(400,"invalid_client_metadata",e)}s(ee,"badMetadata");function ut(e){return $(400,"invalid_redirect_uri",e)}s(ut,"badRedirect");async function gr(e,t){let{options:r}=e,{limits:n}=r;if(!await e.allowed(t,"register"))return $(429,"temporarily_unavailable","Registration rate exceeded; retry later");if(!ye(t,"application/json"))return ee("Send the client metadata as application/json");let o;try{o=JSON.parse(await we(t,n.registrationBytes))}catch(m){return ee(m instanceof F?`The metadata exceeds ${n.registrationBytes} bytes`:"The body is not a JSON object")}if(!O(o))return ee("The body is not a JSON object");let i=o.redirect_uris;if(!z(i)||i.length===0)return ut("List at least one redirect URI in redirect_uris");if(i.length>n.redirectUris)return ut(`Register at most ${n.redirectUris} redirect URIs`);for(let m of i){let y=Ce(m,n);if(y!==void 0)return ut(`Redirect URI refused (${y}). Allowed: https URLs, or http on 127.0.0.1, [::1] or localhost`)}let a=o.token_endpoint_auth_method;if(a!==void 0&&a!=="none")return ee('This server registers public clients only; token_endpoint_auth_method must be "none"');let c=me(o.grant_types,!0);if(c===void 0)return ee('grant_types must include "authorization_code" and may add "refresh_token"; nothing else is offered');let d=o.response_types??["code"];if(!z(d)||d.length!==1||d[0]!=="code")return ee('The only response type offered is "code"');let l=Ue(o.scope,r.scopes,!0,n.scopeLength);if(l===void 0)return ee(`Available scopes: ${r.scopes.join(" ")}`);let g;if(o.client_name!==void 0&&(g=Y(o.client_name,n.clientNameLength),g===void 0))return ee(`client_name needs 1 to ${n.clientNameLength} visible characters`);let h=r.allowRegistration;if(h!==void 0&&!await pe(()=>h({metadata:M(o),request:t})))return $(403,"invalid_client_metadata","This server does not accept the registration of this client");let u=r.now(),p=[...new Set(i)],f={clientId:`client-${N()}`,redirectUris:p,kind:"dynamic",createdAt:u,grantTypes:c,...l!==null?{scopes:l}:{},...g!==void 0?{clientName:g}:{}};return await r.store.putClient(f),await e.emit({type:"client_registered",clientId:f.clientId,redirectHosts:[...new Set(p.map(Le))],...g!==void 0?{clientName:g}:{}}),re(201,{client_id:f.clientId,client_id_issued_at:Math.floor(u/1e3),redirect_uris:p,grant_types:c,response_types:["code"],token_endpoint_auth_method:"none",...l!==null?{scope:l.join(" ")}:{},...g!==void 0?{client_name:g}:{}},{cors:!0})}s(gr,"handleRegister");var b=class extends Error{constructor(r,n,o=400,i,a){super(n);this.error=r;this.description=n;this.status=o;this.challenge=i;this.detail=a;this.name="EndpointRefusal"}error;description;status;challenge;detail;static{s(this,"EndpointRefusal")}};var Tn=/^[!#$%&'*+.^_`|~0-9A-Za-z-]{1,32}$/,An=["client_id","client_secret","client_assertion","client_assertion_type"];function En(e){let t=e.trim().split(" ")[0]??"";return Tn.test(t)?t:"Basic"}s(En,"schemeOf");async function Be(e,t,r){if(!ye(e,Ee))throw new b("invalid_request","Send the parameters as an application/x-www-form-urlencoded body");let n;try{n=Z(new URLSearchParams(await we(e,t)))}catch(c){throw c instanceof F?new b("invalid_request",`The body exceeds ${t} bytes`):c}let o=Q(n,[...An,...r]);if(o.length>0)throw new b("invalid_request",`Parameter sent more than once: ${o.join(", ")}`);let i=e.headers.get("authorization"),a="Clients here authenticate with PKCE alone; remove the client credentials";if(i!==null)throw new b("invalid_client",a,401,En(i));if(n.has("client_secret")||n.has("client_assertion"))throw new b("invalid_client",a);return{form:n,clientId:_(n,"client_id")}}s(Be,"readPublicClientForm");function qe(e,t){let r=_(t,"resource");if(r!==void 0&&!ge(e.options.resource,r))throw new b("invalid_target",`Tokens from this server are only for ${e.options.resource}`)}s(qe,"requireOwnResource");var xn={"Cache-Control":"no-store",Pragma:"no-cache","Access-Control-Allow-Origin":"*"},Sn=["token","token_type_hint"];async function yr(e,t,r){let{store:n,limits:o}=e.options,i=s(()=>new Response(null,{status:200,headers:xn}),"done");try{if(!await e.allowed(t,"revoke"))return $(429,"temporarily_unavailable","Request rate exceeded; retry later");let{form:a,clientId:c}=await Be(t,o.formBytes,Sn),d=_(a,"token");if(d===void 0)throw new b("invalid_request","Missing parameter: token");if(!J(d))return i();let l=A(d),g=s(f=>c===void 0||c===f,"callerMayAct"),h=s(async()=>{let f=await n.getRefreshToken(l);return f===void 0||!g(f.clientId)?!1:(await r(f.grantId,"revocation_request"),!0)},"asRefreshToken"),u=s(async()=>{let f=await n.getAccessToken(l);return f===void 0||!g(f.clientId)?!1:(await n.deleteAccessToken(l),!0)},"asAccessToken"),p=_(a,"token_type_hint")==="access_token"?[u,h]:[h,u];for(let f of p)if(await f())break;return i()}catch(a){if(!(a instanceof b))throw a;return $(a.status,a.error,a.description,a.challenge)}}s(yr,"handleRevoke");async function Ke(e,t,r){let n=e.options.beforeTokenIssue;if(n===void 0)return;let o;try{o=await n(Object.freeze({grant:le(t),grantType:r}))}catch{throw new b("temporarily_unavailable","Tokens cannot be issued right now; retry later",503)}if(!ot(o).allowed)throw new b("invalid_grant","Tokens are not issued for this grant")}s(Ke,"requireTokenIssue");async function wr(e,t,r,n){let{options:o}=e,i=_(t,"code"),a=_(t,"code_verifier"),c=_(t,"redirect_uri"),d=[i===void 0?"code":void 0,a===void 0?"code_verifier":void 0].filter(v=>v!==void 0);if(i===void 0||a===void 0)throw new b("invalid_request",`Missing parameter: ${d.join(", ")}`);qe(e,t);let l=s(v=>new b("invalid_grant","This authorization code cannot be exchanged",400,void 0,v),"unusable");if(!J(i))throw l("code_malformed");let g=A(i),h=await o.store.getAuthorizationCode(g);if(h===void 0)throw l("code_unknown");let u=h.record,p=_(t,"resource"),m=[["client_id",u.clientId!==r],["redirect_uri",c!==void 0&&u.redirectUri!==c],["resource",p!==void 0&&!ge(u.resource,p)],["code_verifier",!Dt(a,u.codeChallenge)]].find(([,v])=>v)?.[0];if(m!==void 0)throw l(`${m}_mismatch`);let y=s(async()=>(await e.emit({type:"authorization_code_replayed",grantId:u.grantId,clientId:u.clientId}),await n(u.grantId,"authorization_code_replay"),l("code_replayed")),"replayed");if(h.consumed)throw await y();if(S(u.expiresAt,o.now()))throw await n(u.grantId,"authorization_code_expired"),l("code_expired");let k=await oe(e,u.grantId,r);if(k===void 0)throw new b("invalid_grant","Access has been withdrawn");await Ke(e,k,"authorization_code");let R=await o.store.consumeAuthorizationCode(g);if(R===void 0)throw l("code_unknown");if(!R.firstUse)throw await y();let x=await ve(e,k,u.scopes);return await e.emit({type:"token_issued",grantId:k.grantId,clientId:r,subject:k.subject,grantType:"authorization_code"}),x}s(wr,"exchangeCode");async function _r(e,t,r,n){let{options:o}=e,i=_(t,"refresh_token");if(i===void 0)throw new b("invalid_request","Missing parameter: refresh_token");qe(e,t);let a=s(()=>new b("invalid_grant","This refresh token cannot be used"),"unusable");if(!J(i))throw a();let c=A(i),d=o.now(),l=await o.store.getRefreshToken(c);if(l===void 0||l.clientId!==r||S(l.expiresAt,d))throw a();let g=l.scopes,h=_(t,"scope");if(h!==void 0){let R=[...new Set(h.split(" ").filter(x=>x.length>0))];if(R.length===0||R.some(x=>!l.scopes.includes(x)))throw new b("invalid_scope","A refreshed token can only carry scopes already granted");g=R}let u=await oe(e,l.grantId,r);if(u===void 0||u.allowRefresh===!1)throw new b("invalid_grant","Access has been withdrawn");await Ke(e,u,"refresh_token");let p=await o.store.useRefreshToken(c,d);if(p===void 0)throw a();let f=p.previousUsedAt,m=f!==void 0&&o.refreshReuseGraceMs>0&&d-f<=o.refreshReuseGraceMs;if(f!==void 0&&!m)throw await e.emit({type:"refresh_token_replayed",grantId:p.record.grantId,clientId:r}),await n(p.record.grantId,"refresh_token_replay"),a();let y=await oe(e,p.record.grantId,r);if(y===void 0||y.allowRefresh===!1)throw new b("invalid_grant","Access has been withdrawn");let k=await ve(e,y,g,l.scopes);return await e.emit({type:"token_issued",grantId:y.grantId,clientId:r,subject:y.subject,grantType:"refresh_token"}),k}s(_r,"exchangeRefreshToken");var Pn=["grant_type","code","redirect_uri","code_verifier","refresh_token","scope","resource"];async function kr(e,t,r){let n;try{if(!await e.allowed(t,"token"))return $(429,"temporarily_unavailable","Request rate exceeded; retry later");let o=await Be(t,e.options.limits.formBytes,Pn);if(n=o.clientId,n===void 0)throw new b("invalid_client","Missing parameter: client_id");let i=fe(n),a=i?void 0:await He(e,n);if(!i&&a===void 0)throw new b("invalid_client","No client is registered under this client_id");let c=_(o.form,"grant_type");if(c==="refresh_token"&&a?.grantTypes!==void 0&&!a.grantTypes.includes("refresh_token"))throw new b("unauthorized_client","refresh_token is not among this client's registered grant_types");let d;switch(c){case"authorization_code":d=await wr(e,o.form,n,r);break;case"refresh_token":d=await _r(e,o.form,n,r);break;case void 0:throw new b("invalid_request","Missing parameter: grant_type");default:throw new b("unsupported_grant_type","This server only exchanges authorization codes and refresh tokens")}return re(200,d,{cors:!0})}catch(o){if(!(o instanceof b))throw o;return await e.emit({type:"token_request_refused",error:o.error,reason:o.detail??o.description,...n!==void 0?{clientId:n}:{}}),$(o.status,o.error,o.description,o.challenge)}}s(kr,"handleToken");function Rr(e){let t=s(r=>`${e.issuerOrigin}${r}`,"at");return{issuer:e.issuer,authorization_endpoint:t(e.paths.authorize),token_endpoint:t(e.paths.token),...e.dynamicClientRegistration?{registration_endpoint:t(e.paths.register)}:{},revocation_endpoint:t(e.paths.revoke),scopes_supported:e.scopes,response_types_supported:["code"],response_modes_supported:["query"],grant_types_supported:["authorization_code","refresh_token"],code_challenge_methods_supported:["S256"],token_endpoint_auth_methods_supported:["none"],revocation_endpoint_auth_methods_supported:["none"],client_id_metadata_document_supported:e.clientIdMetadataDocuments,authorization_response_iss_parameter_supported:!0}}s(Rr,"authorizationServerMetadata");function br(e){return{resource:e.resource,authorization_servers:[e.issuer],scopes_supported:e.scopes,bearer_methods_supported:["header"],...e.resourceName!==void 0?{resource_name:e.resourceName}:{}}}s(br,"protectedResourceMetadata");async function _e(e,t,r,n){try{return await r()}catch(o){return await e.emit({type:"unexpected_failure",where:t,errorName:o instanceof Error?o.name:"unknown"}),n()}}s(_e,"guarded");function Cr(e,t){let{options:r}=e,n=s(()=>$(500,"server_error","An unexpected condition stopped the request"),"serverError"),o=s(d=>e.errorPage(d,"server_error"),"pageError"),i=new Map,a=s((d,l)=>{i.has(d)||i.set(d,l)},"add"),c=s(d=>({methods:["GET"],cors:!0,run:s(()=>Promise.resolve(re(200,d,{cors:!0,cacheable:!0})),"run")}),"document");for(let d of r.resourceMetadataPaths)a(d,c(br(r)));for(let d of r.authorizationServerMetadataPaths)a(d,c(Rr(r)));return r.dynamicClientRegistration&&a(r.paths.register,{methods:["POST"],cors:!0,run:s(d=>_e(e,"register",()=>gr(e,d),n),"run")}),a(r.paths.authorize,{methods:["GET"],cors:!1,run:s(d=>_e(e,"authorize",()=>dr(e,d),()=>o(d)),"run")}),a(r.paths.callback,{methods:["GET"],cors:!1,run:s(d=>_e(e,"callback",()=>lr(e,d),()=>o(d)),"run")}),a(r.paths.consent,{methods:["POST"],cors:!1,run:s(d=>_e(e,"consent",()=>hr(e,d),()=>o(d)),"run")}),a(r.paths.token,{methods:["POST"],cors:!0,run:s(d=>_e(e,"token",()=>kr(e,d,t),n),"run")}),a(r.paths.revoke,{methods:["POST"],cors:!0,run:s(d=>_e(e,"revoke",()=>yr(e,d,t),n),"run")}),i}s(Cr,"buildRoutes");var ce=class extends Error{static{s(this,"GrantInactiveError")}constructor(){super("The grant this token belonged to has been removed"),this.name="GrantInactiveError"}};var ke=class extends Error{static{s(this,"UpstreamTokenError")}constructor(t,r){super(t,r),this.name="UpstreamTokenError"}};var Ve=class{static{s(this,"UpstreamTokenCache")}#e;#t=new Map;#r=new Map;#o=new Set;constructor(t){this.#e=t}forget(t){if(this.#t.delete(t),this.#o.size>=Ze){let r=this.#o.values().next();r.done!==!0&&this.#o.delete(r.value)}this.#o.add(t)}get(t,r=!1){let n=this.#r.get(t);if(!r){let i=this.#e.options.now(),a=this.#t.get(t);return a!==void 0&&!S(a.expiresAt-Xe,i)?Promise.resolve(a.token):n!==void 0?n.promise:this.#s(t,!1,this.#c(t))}if(n?.forced===!0)return n.promise;let o=n===void 0?this.#n(t):n.promise.then(()=>this.#n(t),()=>this.#n(t));return this.#s(t,!0,o)}#s(t,r,n){let o=n.finally(()=>{this.#r.get(t)?.promise===o&&this.#r.delete(t)});return this.#r.set(t,{promise:o,forced:r}),o}async#n(t){let{options:r}=this.#e;this.#t.delete(t);let n=await r.store.getGrant(t);if(n===void 0||S(n.expiresAt,r.now()))throw new ce;return n.sealedUpstreamAccessToken!==void 0&&await r.store.updateGrant(t,{upstreamAccessTokenExpiresAt:0}),this.#a(n)}#i(t,r){if(this.#t.size>=Ze&&!this.#t.has(t)){let n=this.#t.keys().next();n.done!==!0&&this.#t.delete(n.value)}this.#t.delete(t),this.#t.set(t,r)}async#c(t){let{options:r}=this.#e,n=await r.store.getGrant(t);if(n===void 0||S(n.expiresAt,r.now()))throw new ce;let o=await this.#d(n);return o!==void 0?o:this.#a(n)}async#d(t){let{options:r}=this.#e;if(!(t.sealedUpstreamAccessToken===void 0||t.upstreamAccessTokenExpiresAt===void 0||S(t.upstreamAccessTokenExpiresAt-Xe,r.now())))try{let n=await r.sealer.open(t.sealedUpstreamAccessToken,`${t.grantId}#access`);return this.#i(t.grantId,{token:n,expiresAt:t.upstreamAccessTokenExpiresAt}),n}catch{return}}async#a(t){let{options:r}=this.#e,n=t.grantId;if(t.sealedUpstreamRefreshToken===void 0)throw new ke("This grant has no upstream refresh token to renew with");let o;try{let l=await r.sealer.open(t.sealedUpstreamRefreshToken,n);o=await r.identityProvider.refresh(l,Object.freeze({grantId:n,subject:t.subject}))}catch(l){throw await this.#e.emit({type:"upstream_token_refresh_failed",grantId:n,reason:l instanceof Error?l.name:"unknown"}),new ke("The identity provider would not renew the upstream token",{cause:l})}let i=r.now(),a=Math.max(0,Math.min(Number.isFinite(o.expiresIn)?o.expiresIn:0,Te)),c=i+a*1e3;if(!await r.store.updateGrant(n,{sealedUpstreamAccessToken:await r.sealer.seal(o.accessToken,`${n}#access`),upstreamAccessTokenExpiresAt:c,...o.refreshToken!==void 0?{sealedUpstreamRefreshToken:await r.sealer.seal(o.refreshToken,n)}:{}})||this.#o.has(n)){if(this.#t.delete(n),o.refreshToken!==void 0&&r.identityProvider.revoke!==void 0)try{await r.identityProvider.revoke(o.refreshToken)}catch{}throw new ce}return this.#i(n,{token:o.accessToken,expiresAt:c}),o.accessToken}};function vn(e){let t=nr(e,{consent:Kt,error:Vt}),r=qt(t),n=new Ve(r),o=s((a,c)=>zt(r,a,c,d=>{n.forget(d)}),"revoke"),i=Cr(r,o);return{async handle(a){let c=i.get(new URL(a.url).pathname);if(c!==void 0)return a.method==="OPTIONS"&&c.cors?It([...c.methods,"OPTIONS"].join(", ")):c.methods.includes(a.method)?c.run(a):Mt(c.methods.join(", "))},authenticate(a){return Gt(r,a,(c,d)=>n.get(c,d))},unauthorized(a,c){return Me(r,c)},revokeGrant(a){return o(a,"revoke_grant_call")},renewUpstream(a){return n.get(a,!0)},async updateGrantData(a,c){let d=W(c,t.limits.grantDataBytes,"updateGrantData");return t.store.updateGrant(a,{data:d})},async revokeGrantsForSubject(a){let{store:c}=t;if(c.listGrantsBySubject===void 0)throw new w("revokeGrantsForSubject needs a store with listGrantsBySubject");let d=await c.listGrantsBySubject(a),l=0;for(let g of d)g.subject===a&&(await o(g.grantId,"revoke_subject_call"),l+=1);return l}}}s(vn,"createMcpAuth");import{createCipheriv as In,createDecipheriv as Mn,randomBytes as jn}from"node:crypto";var V=class extends Error{static{s(this,"SealerError")}constructor(t){super(t),this.name="SealerError"}};var Tr=12,lt=16,On=/^[A-Za-z0-9_-]{1,32}$/,pt="v1";function Ar(e){try{return Promise.resolve(e())}catch(t){return Promise.reject(t instanceof Error?t:new V("Sealing failed"))}}s(Ar,"attempt");function Er(e,t){return Buffer.from(`${pt}\0${e}\0${t}`,"utf8")}s(Er,"additionalData");function Un(e){let t=new Map;for(let[o,i]of Object.entries(e.keys)){if(!On.test(o))throw new TypeError(`Key id ${JSON.stringify(o)} has characters outside A-Z a-z 0-9 _ -, or is too long`);if(!(i instanceof Uint8Array)||i.byteLength!==32)throw new TypeError(`Key ${o} is not 32 bytes long`);t.set(o,Buffer.from(i))}let r=t.get(e.currentKid);if(r===void 0)throw new TypeError("currentKid has no matching entry in keys");let n=e.currentKid;return{seal(o,i){return Ar(()=>{let a=jn(Tr),c=In("aes-256-gcm",r,a,{authTagLength:lt});c.setAAD(Er(n,i));let d=Buffer.concat([c.update(o,"utf8"),c.final()]);return[pt,n,a.toString("base64url"),d.toString("base64url"),c.getAuthTag().toString("base64url")].join(".")})},open(o,i){return Ar(()=>{let a=o.split(".");if(a.length!==5||a[0]!==pt)throw new V("Value is not in sealed format");let[,c="",d="",l="",g=""]=a,h=t.get(c);if(h===void 0)throw new V("Value was sealed with a key that is not configured");let u=Buffer.from(d,"base64url"),p=Buffer.from(g,"base64url");if(u.byteLength!==Tr||p.byteLength!==lt)throw new V("Value is not in sealed format");try{let f=Mn("aes-256-gcm",h,u,{authTagLength:lt});return f.setAAD(Er(c,i)),f.setAuthTag(p),Buffer.concat([f.update(Buffer.from(l,"base64url")),f.final()]).toString("utf8")}catch{throw new V("Value was altered or belongs to a different owner")}})}}}s(Un,"createAesGcmSealer");var E=class extends Error{static{s(this,"IdentityProviderError")}code;constructor(t,r,n){super(t,n),this.name="IdentityProviderError",this.code=r}};import{createRemoteJWKSet as Ln,customFetch as Nn,jwtVerify as Dn}from"jose";var xr=["RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512","EdDSA"],Sr=new Set(["state","nonce","code_challenge","code_challenge_method","client_id","redirect_uri","response_type","scope"]);function ft(e){return e===void 0||typeof e=="string"}s(ft,"optionalString");function Pr(e){return O(e)&&typeof e.issuer=="string"&&typeof e.authorization_endpoint=="string"&&typeof e.token_endpoint=="string"&&typeof e.jwks_uri=="string"&&ft(e.revocation_endpoint)&&(e.token_endpoint_auth_methods_supported===void 0||z(e.token_endpoint_auth_methods_supported))&&(e.authorization_response_iss_parameter_supported===void 0||typeof e.authorization_response_iss_parameter_supported=="boolean")&&(e.code_challenge_methods_supported===void 0||z(e.code_challenge_methods_supported))}s(Pr,"isDiscovery");function vr(e){return O(e)&&typeof e.access_token=="string"&&e.access_token!==""&&ft(e.id_token)&&ft(e.refresh_token)&&(e.expires_in===void 0||typeof e.expires_in=="number"&&Number.isFinite(e.expires_in))}s(vr,"isTokenResponse");function Re(e,t,r){let n;try{n=new URL(t)}catch{throw new E(`Identity provider ${e} cannot be parsed as a URL`)}let o=n.protocol==="http:"&&de.has(n.hostname);if(n.protocol!=="https:"&&!(o&&r))throw new E(`Identity provider ${e} is not an https URL`);return n}s(Re,"checkEndpoint");function Hn(e){let t=e.allowInsecureLocalhost===!0,r=e.timeoutMs??1e4,n=e.fetch??fetch,o=[...e.algorithms??xr];if(!e.scopes.includes("openid"))throw new TypeError("OIDC scopes need to contain openid");if(o.length===0||o.some(h=>h.toLowerCase()==="none"||h.toUpperCase().startsWith("HS")))throw new TypeError("Only asymmetric signature algorithms are allowed (no none, no HS*)");for(let h of Object.keys(e.extraAuthorizationParams??{}))if(Sr.has(h))throw new TypeError(`extraAuthorizationParams may not override ${h}`);try{Re("issuer",e.issuer,t)}catch(h){throw new TypeError(h instanceof Error?h.message:"Identity provider issuer is not usable")}let i=s((h,u={})=>n(h,{...u,redirect:"error",signal:AbortSignal.timeout(r)}),"timedFetch"),a=null,c=s(()=>{if(a!==null)return a;let h=(async()=>{let u=ae(e.issuer,"/"),p;try{p=await i(`${u}/.well-known/openid-configuration`,{headers:{Accept:"application/json"}})}catch(k){throw new E("Could not reach the identity provider's discovery document",void 0,{cause:k})}if(!p.ok)throw new E(`Discovery document request returned HTTP ${p.status}`);let f=await p.json().catch(()=>{});if(!Pr(f))throw new E("Discovery document lacks required fields");if(f.issuer!==e.issuer)throw new E("Discovery document names a different issuer than configured");if(f.code_challenge_methods_supported!==void 0&&!f.code_challenge_methods_supported.includes("S256"))throw new E("Identity provider does not offer S256 code challenges");Re("authorization_endpoint",f.authorization_endpoint,t),Re("token_endpoint",f.token_endpoint,t);let m=Re("jwks_uri",f.jwks_uri,t);f.revocation_endpoint!==void 0&&Re("revocation_endpoint",f.revocation_endpoint,t);let y=Ln(m,{timeoutDuration:r,[Nn]:(k,R)=>n(k,{...R,redirect:"error"})});return{document:f,jwks:y}})();return a=h,h.catch(()=>{a===h&&(a=null)}),h},"discover"),d=s((h,u)=>{if(u.set("client_id",e.clientId),e.clientSecret===void 0)return{};let p=h.token_endpoint_auth_methods_supported??["client_secret_basic"];if(p.includes("client_secret_basic")){let f=encodeURIComponent(e.clientId),m=encodeURIComponent(e.clientSecret);return{Authorization:`Basic ${Buffer.from(`${f}:${m}`).toString("base64")}`}}if(p.includes("client_secret_post"))return u.set("client_secret",e.clientSecret),{};throw new E("Identity provider accepts no client-secret method this library implements")},"clientAuth"),l=s(async(h,u)=>{let p={"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json",...d(h,u)},f;try{f=await i(h.token_endpoint,{method:"POST",headers:p,body:u.toString()})}catch(y){throw new E("Could not reach the identity provider's token endpoint",void 0,{cause:y})}let m=await f.json().catch(()=>{});if(!f.ok){let y=O(m)&&typeof m.error=="string"?m.error.slice(0,64):void 0;throw new E(`Token endpoint returned HTTP ${f.status}`,y)}if(!vr(m))throw new E("Token endpoint reply lacks an access_token");return m},"postToken"),g=s(async(h,u,p,f)=>{let m;try{({payload:m}=await Dn(p,u,{issuer:h.issuer,audience:e.clientId,algorithms:o,clockTolerance:e.clockToleranceSeconds??60,requiredClaims:["sub","exp","iat"]}))}catch(k){throw new E("ID token signature or claims did not verify",void 0,{cause:k})}if(m.nonce!==f)throw new E("ID token nonce differs from the one sent");if(((Array.isArray(m.aud)?m.aud:[m.aud]).length>1||m.azp!==void 0)&&m.azp!==e.clientId)throw new E("ID token azp names some other client");return m},"verifyIdToken");return{async authorizationUrl({state:h,codeChallenge:u,redirectUri:p,nonce:f}){if(p!==e.redirectUri)throw new E("Callback URL differs from the redirectUri this provider was configured with");let{document:m}=await c(),y=new URL(m.authorization_endpoint);for(let[k,R]of Object.entries(e.extraAuthorizationParams??{}))y.searchParams.set(k,R);return y.searchParams.set("response_type","code"),y.searchParams.set("client_id",e.clientId),y.searchParams.set("redirect_uri",p),y.searchParams.set("scope",e.scopes.join(" ")),y.searchParams.set("state",h),y.searchParams.set("nonce",f),y.searchParams.set("code_challenge",u),y.searchParams.set("code_challenge_method","S256"),y.toString()},async exchangeCode({code:h,codeVerifier:u,redirectUri:p,nonce:f,issuer:m}){let{document:y,jwks:k}=await c();if(m!==void 0&&m!==y.issuer)throw new E("Authorization response iss names another issuer");if(m===void 0&&y.authorization_response_iss_parameter_supported===!0)throw new E("Authorization response omits the promised iss");let R=await l(y,new URLSearchParams({grant_type:"authorization_code",code:h,redirect_uri:p,code_verifier:u}));if(R.id_token===void 0)throw new E("Token endpoint reply has no id_token");let x=await g(y,k,R.id_token,f),v=x.sub;if(typeof v!="string"||v==="")throw new E("ID token carries no sub claim");let L=[x.name,x.email,x.preferred_username].find(D=>typeof D=="string"&&D!=="");return{subject:v,claims:{...x},accessToken:R.access_token,expiresIn:R.expires_in??300,...L!==void 0?{displayName:L}:{},...R.refresh_token!==void 0?{refreshToken:R.refresh_token}:{}}},async refresh(h){let{document:u}=await c(),p=await l(u,new URLSearchParams({grant_type:"refresh_token",refresh_token:h}));return{accessToken:p.access_token,expiresIn:p.expires_in??300,...p.refresh_token!==void 0?{refreshToken:p.refresh_token}:{}}},async revoke(h){let{document:u}=await c();if(u.revocation_endpoint===void 0)return;let p=new URLSearchParams({token:h,token_type_hint:"refresh_token"}),f={"Content-Type":"application/x-www-form-urlencoded",...d(u,p)};try{await i(u.revocation_endpoint,{method:"POST",headers:f,body:p.toString()})}catch(m){throw new E("Could not reach the identity provider's revocation endpoint",void 0,{cause:m})}}}}s(Hn,"createOidcProvider");var We=class{static{s(this,"ClientCollection")}#e=new Map;#t=new Map;#r=new Map;#o;#s;#n;constructor(t,r,n){this.#o=t,this.#s=r,this.#n=n}#i(t){for(this.#t.delete(t.clientId);this.#t.size>=this.#o;){let r=this.#t.keys().next();if(r.done===!0)break;this.#t.delete(r.value)}this.#t.set(t.clientId,{client:t,usedAt:this.#n()})}put(t){this.#e.delete(t.clientId),this.#t.delete(t.clientId),t.kind==="static"||(this.#r.get(t.clientId)??0)>0?this.#e.set(t.clientId,t):this.#i(t)}get(t){let r=this.#e.get(t);if(r!==void 0)return r;let n=this.#t.get(t);if(n!==void 0&&(this.#t.delete(t),!S(n.usedAt+this.#s,this.#n())))return this.#t.set(t,{client:n.client,usedAt:this.#n()}),n.client}grantAdded(t){this.#r.set(t,(this.#r.get(t)??0)+1);let r=this.#t.get(t);r!==void 0&&(this.#t.delete(t),this.#e.set(t,r.client))}grantRemoved(t){let r=(this.#r.get(t)??0)-1;if(r>0){this.#r.set(t,r);return}this.#r.delete(t);let n=this.#e.get(t);n!==void 0&&n.kind!=="static"&&(this.#e.delete(t),this.#i(n))}};var B=class{static{s(this,"Collection")}#e=new Map;#t;#r;#o;#s;constructor(t,r,n,o=()=>{}){this.#t=t,this.#o=r,this.#r=n,this.#s=o}#n(t,r){this.#e.delete(t),this.#s(r)}get(t){let r=this.#e.get(t);if(r!==void 0){if(S(this.#r(r),this.#o())){this.#n(t,r);return}return r}}set(t,r){let n=this.#e.get(t);for(n!==void 0&&this.#n(t,n);this.#e.size>=this.#t;){let o=this.#e.entries().next();if(o.done===!0)break;this.#n(o.value[0],o.value[1])}this.#e.set(t,r)}peek(t){return this.#e.get(t)}take(t,r=!1){let n=r?this.#e.get(t):this.get(t);return n!==void 0&&this.#n(t,n),n}delete(t){let r=this.#e.get(t);r!==void 0&&this.#n(t,r)}values(){let t=this.#o();return[...this.#e.values()].filter(r=>!S(this.#r(r),t))}deleteWhere(t){for(let[r,n]of this.#e)t(n)&&this.#n(r,n)}};var te=s(e=>e.expiresAt,"expiry");function T(e){try{return Promise.resolve(e())}catch(t){return Promise.reject(t instanceof Error?t:new Error("Memory store failure"))}}s(T,"settle");function $n(e={}){let t=e.maxEntriesPerCollection??bt,r=Pe(e.now??Date.now),n=new We(t,(e.dynamicClientIdleSeconds??Ct)*1e3,r),o=new B(t,r,te),i=new B(t,r,te),a=new B(t,r,te),c=new B(t,r,te),d=new B(t,r,te),l=new B(t,r,te,u=>{n.grantRemoved(u.clientId)}),g=new B(t,r,te),h=new B(t,r,te);return{getClient(u){return T(()=>n.get(u))},putClient(u){return T(()=>{n.put(u)})},getCachedClientMetadata(u){return T(()=>o.get(u)?.client)},putCachedClientMetadata(u,p,f){return T(()=>{o.set(u,{client:p,expiresAt:f})})},putPendingAuthorization(u){return T(()=>{i.set(u.id,u)})},getPendingAuthorization(u){return T(()=>i.get(u))},consumePendingAuthorization(u){return T(()=>i.take(u))},putConsentRequest(u){return T(()=>{a.set(u.id,u)})},getConsentRequest(u){return T(()=>a.peek(u))},putConsentOutcome(u,p,f){return T(()=>{c.set(u,{sealedLocation:p,expiresAt:f})})},getConsentOutcome(u){return T(()=>c.get(u)?.sealedLocation)},listGrantsBySubject(u){return T(()=>l.values().filter(p=>p.subject===u))},consumeConsentRequest(u){return T(()=>a.take(u,!0))},putAuthorizationCode(u){return T(()=>{d.set(u.codeHash,{record:u,consumed:!1,expiresAt:u.expiresAt})})},getAuthorizationCode(u){return T(()=>{let p=d.get(u);return p===void 0?void 0:{record:p.record,consumed:p.consumed}})},consumeAuthorizationCode(u){return T(()=>{let p=d.get(u);if(p===void 0)return;let f={record:p.record,firstUse:!p.consumed};return d.set(u,{...p,consumed:!0}),f})},putGrant(u){return T(()=>{n.grantAdded(u.clientId),l.set(u.grantId,u)})},getGrant(u){return T(()=>l.get(u))},updateGrant(u,p){return T(()=>{let f=l.get(u);return f===void 0?!1:(n.grantAdded(f.clientId),l.set(u,{...f,...p}),!0)})},deleteGrant(u){return T(()=>{let p=l.take(u,!0);return g.deleteWhere(f=>f.grantId===u),h.deleteWhere(f=>f.grantId===u),d.deleteWhere(f=>f.record.grantId===u),p})},putAccessToken(u){return T(()=>{g.set(u.tokenHash,u)})},getAccessToken(u){return T(()=>g.get(u))},deleteAccessToken(u){return T(()=>{g.delete(u)})},putRefreshToken(u){return T(()=>{h.set(u.tokenHash,u)})},getRefreshToken(u){return T(()=>h.get(u))},useRefreshToken(u,p){return T(()=>{let f=h.get(u);if(f===void 0)return;if(f.usedAt!==void 0)return{record:f,previousUsedAt:f.usedAt};let m={...f,usedAt:p};return h.set(u,m),{record:m}})}}}s($n,"createMemoryStore");export{ce as GrantInactiveError,E as IdentityProviderError,w as McpAuthConfigError,V as SealerError,ke as UpstreamTokenError,Un as createAesGcmSealer,vn as createMcpAuth,$n as createMemoryStore,Hn as createOidcProvider,P as escapeHtml};
44
+ </form>`)}i(Zt,"defaultConsentPage");function Qt(e){return ut(e.title,`<h1>${v(e.title)}</h1>
45
+ <p>${v(e.message)}</p>${e.detail===void 0?"":`
46
+ <p class="note">${v(e.detail)}</p>`}`)}i(Qt,"defaultErrorPage");function ge(e){if(e.length>Se||!e.startsWith("https://")||e.includes("#"))return!1;let t;try{t=new URL(e)}catch{return!1}return t.hostname!==""&&t.username===""&&t.password===""&&t.pathname.length>1&&t.href===e}i(ge,"isMetadataDocumentClientId");function X(e,t){if(typeof e!="string")return;let r=e.trim();if(!(r.length===0||r.length>t))return ce(r)?void 0:r}i(X,"cleanClientName");function on(e){return e==="authorization_code"||e==="refresh_token"}i(on,"isSupportedGrantType");function Z(e,t,r=["authorization_code"]){if(e===void 0)return[...r];if(!z(e)||!e.includes("authorization_code"))return;let n=e.filter(on);if(!(t&&n.length!==e.length))return[...new Set(n)]}i(Z,"parseGrantTypes");function He(e,t,r,n){if(e===void 0)return null;if(typeof e!="string"||e.length>n)return;let o=[...new Set(e.split(" ").filter(a=>a.length>0))],s=o.filter(a=>t.includes(a));if(s.length!==0&&!(r&&s.length<o.length))return s}i(He,"parseClientScopes");var sn=2048,an=["code","state","iss","error","error_description","error_uri"];function ye(e){try{return new URL(e)}catch{return}}i(ye,"tryParse");function Te(e){return e.protocol==="http:"&&pe.has(e.hostname)}i(Te,"isLoopbackHttp");function tr(e){let t=ye(e);return t!==void 0&&Te(t)}i(tr,"isLoopbackRedirectUri");function Ae(e,t={redirectUriLength:sn}){if(e.length>t.redirectUriLength)return"over_length";let r=ye(e);return r===void 0?"unparseable":e.includes("#")?"has_fragment":r.username.length>0||r.password.length>0?"has_credentials":!(r.protocol==="https:"&&r.hostname.length>0)&&!Te(r)?"disallowed_scheme":an.some(o=>r.searchParams.has(o))?"reserved_query_parameter":void 0}i(Ae,"redirectUriProblem");function lt(e,t){return Ae(e,t)===void 0}i(lt,"isAcceptableRedirectUri");function cn(e){return e>=48&&e<=57}i(cn,"isDigit");function er(e,t){let r=`${t.protocol}//${t.hostname}`;if(e.slice(0,r.length).toLowerCase()!==r.toLowerCase())return e;let n=e.slice(r.length);if(n.startsWith(":")){let o=1;for(;o<n.length&&cn(n.charCodeAt(o));)o+=1;n=n.slice(o)}return r.toLowerCase()+n}i(er,"portless");function dn(e,t,r){if(!lt(t,r))return!1;if(t===e)return!0;let n=ye(e),o=ye(t);return n===void 0||o===void 0||!Te(n)||!Te(o)?!1:er(e,n)===er(t,o)}i(dn,"redirectUriMatches");function rr(e,t,r){return e.some(n=>dn(n,t,r))}i(rr,"matchesAnyRedirectUri");function Ge(e){let t=ye(e);return t===void 0?"":Te(t)?t.hostname:t.host}i(Ge,"redirectHostOf");function nr(e){return ye(e)?.origin}i(nr,"originOf");function $e(e,t){let r=new URL(e);for(let[n,o]of Object.entries(t))o!==void 0&&r.searchParams.append(n,o);return r.toString()}i($e,"buildRedirect");function or(e,t={}){for(let[n,o]of Object.entries(t)){if(!e.includes(n))throw new _(`scopeDescriptions names ${n}, which is not in scopes`);if(o.trim()===""||o.length>200||ce(o))throw new _(`scopeDescriptions.${n} must be 1 to 200 visible characters`)}let r=Object.fromEntries(Object.entries(t));return Object.setPrototypeOf(r,null),Object.freeze(r)}i(or,"resolveScopeDescriptions");function ir(e=[],t,r,n){let o=new Map;for(let s of e){let a=s.clientId,c=`clients[${JSON.stringify(a)}]`;if(a.trim()===""||a.length>255||ce(a))throw new _(`${c}: clientId must be 1 to 255 visible characters`);if(ge(a)||/^https:/i.test(a))throw new _(`${c}: clientId must not be an https URL`);if(o.has(a))throw new _(`${c}: listed twice`);if(s.redirectUris.length===0||s.redirectUris.length>r.redirectUris)throw new _(`${c}: list 1 to ${r.redirectUris} redirectUris`);for(let h of s.redirectUris){let m=Ae(h,r);if(m!==void 0)throw new _(`${c}: redirect URI refused (${m})`)}let d=s.clientName===void 0?void 0:X(s.clientName,r.clientNameLength);if(s.clientName!==void 0&&d===void 0)throw new _(`${c}: clientName is not a valid display name`);let l=Z(s.grantTypes??["authorization_code","refresh_token"],!0);if(l===void 0)throw new _(`${c}: grantTypes must include authorization_code`);if(s.scopes?.some(h=>!t.includes(h))===!0)throw new _(`${c}: scopes must be a subset of scopes`);if(s.scopes?.length===0)throw new _(`${c}: scopes must not be empty`);o.set(a,qt({clientId:a,redirectUris:[...new Set(s.redirectUris)],kind:"static",createdAt:n(),grantTypes:l,...s.scopes!==void 0?{scopes:[...s.scopes]}:{},...d!==void 0?{clientName:d}:{}}))}return o}i(ir,"resolveStaticClients");function pt(e,t,r){let n;try{n=new URL(t)}catch{throw new _(`${e} must be an absolute URL`)}if(t.includes("#")||n.search!==""||t.includes("?"))throw new _(`${e} must have no query or fragment`);if(n.username!==""||n.password!=="")throw new _(`${e} must have no userinfo`);let o=n.protocol==="http:"&&pe.has(n.hostname);if(n.protocol!=="https:"&&!(o&&r))throw new _(`${e} must use https (http is allowed only for localhost with allowInsecureLocalhost)`);return n}i(pt,"parseServerUrl");function ft(e){return de(e,"/")}i(ft,"trimPath");function sr(e,t,r,n,o){let s=t??r;if(!Number.isInteger(s)||s<n||s>o)throw new _(`lifetimes.${e} must be an integer from ${n} to ${o}`);return s*1e3}i(sr,"seconds");function un(e,t,r){let n=t??r;if(!Number.isInteger(n)||n<1)throw new _(`limits.${e} must be a positive integer`);return n}i(un,"positive");function ar(e={}){let t=i(r=>un(r,e[r],Tt[r]),"pick");return{clientNameLength:t("clientNameLength"),redirectUris:t("redirectUris"),redirectUriLength:t("redirectUriLength"),stateLength:t("stateLength"),scopeLength:t("scopeLength"),registrationBytes:t("registrationBytes"),formBytes:t("formBytes"),clientMetadataBytes:t("clientMetadataBytes"),clientMetadataTimeoutMs:t("clientMetadataTimeoutMs"),clientMetadataFailures:t("clientMetadataFailures"),grantContextBytes:t("grantContextBytes"),consentDetailsBytes:t("consentDetailsBytes"),grantDataBytes:t("grantDataBytes")}}i(ar,"resolveLimits");function ln(e,t){let r=t.split("/").slice(1);if(!t.startsWith("/")||t.includes("//")||/[\\?#\s]/.test(t)||r.some(n=>n==="."||n===".."))throw new _(`paths.${e} must be one absolute path without //, \\, ?, #, dot segments or whitespace`);return t}i(ln,"checkPath");function cr(e,t={}){let r=i(s=>ln(s,t[s]??`${e}/${s}`),"pick"),n={authorize:r("authorize"),callback:r("callback"),consent:r("consent"),token:r("token"),register:r("register"),revoke:r("revoke")},o=Object.values(n);if(new Set(o).size!==o.length)throw new _("paths must be distinct");return n}i(cr,"resolvePaths");var pn=/^sha256-[A-Za-z0-9+/]{43}=$/,fn=/^__Host-[A-Za-z0-9_.-]{0,40}$/;function dr(e,t){let r=e.allowInsecureLocalhost===!0,n=pt("issuer",e.issuer,r),o=ft(n.pathname),s=`${n.origin}${o}`;if(e.issuer!==s&&!(o===""&&e.issuer===`${s}/`))throw new _(`issuer must be in normalized form, for example ${s}`);let a=pt("resource",e.resource,r),c=ft(a.pathname),d=e.scopes??At;if(d.length===0||!d.every(De))throw new _("scopes must be non-empty scope tokens");let l=e.defaultScopes??d;if(l.length===0||!l.every(E=>d.includes(E)))throw new _("defaultScopes must be a subset of scopes");let h=e.refreshReuseGraceSeconds??Et;if(!Number.isInteger(h)||h<0||h>tt)throw new _(`refreshReuseGraceSeconds must be an integer from 0 to ${tt}`);let m=e.lifetimes??{},u=i(E=>sr(E,m[E],Ct[E],et[E].min,et[E].max),"lifetime"),p=u("grantIdle")/1e3;if(p>0&&p<u("accessToken")/1e3)throw new _("lifetimes.grantIdle must be 0 or at least lifetimes.accessToken");let f=Z(e.defaultGrantTypes??["authorization_code"],!0);if(f===void 0)throw new _("defaultGrantTypes may only list authorization_code and refresh_token, and must include authorization_code");let w=cr(o,e.paths),y=e.cookiePrefix??xt;if(!fn.test(y))throw new _("cookiePrefix must start with __Host- and use only letters, digits, '.', '_' and '-'");let k=ar(e.limits),C=je(e.now??Date.now),O=[...e.scriptHashes??[]];for(let E of O)if(!pn.test(E))throw new _("scriptHashes entries must look like sha256-<base64 of 32 bytes>");let T=e.consentReplaySeconds??It;if(!Number.isInteger(T)||T<0||T>ot)throw new _(`consentReplaySeconds must be an integer from 0 to ${ot}`);let g=Mt,H=jt,G=c===""?[g]:[`${g}${c}`,g],N=o===""?[H]:[`${H}${o}`,H],q=new Set([...G,...N,a.pathname,c===""?"/":c]);for(let[E,le]of Object.entries(w))if(q.has(le))throw new _(`paths.${E} collides with a metadata path or the resource path`);return{issuer:s,issuerOrigin:n.origin,resource:e.resource,resourceMetadataUrl:`${a.origin}${g}${c}`,resourceMetadataPaths:G,authorizationServerMetadataPaths:N,scopes:[...d],defaultScopes:[...l],identityProvider:e.identityProvider,store:e.store,sealer:e.sealer,renderConsentPage:e.renderConsentPage??t.consent,renderErrorPage:e.renderErrorPage??t.error,accessTokenTtlMs:u("accessToken"),refreshTokenTtlMs:u("refreshToken"),grantTtlMs:u("grant"),grantIdleMs:u("grantIdle"),defaultGrantTypes:f,codeTtlMs:u("authorizationCode"),pendingTtlMs:u("pendingAuthorization"),clientMetadataCacheMs:u("clientMetadataCache"),clientMetadataFailureMs:u("clientMetadataFailure"),limits:k,cookiePrefix:y,scriptHashes:O,consentReplayMs:T*1e3,refreshReuseGraceMs:h*1e3,clientIdMetadataDocuments:e.clientIdMetadataDocuments??!0,dynamicClientRegistration:e.dynamicClientRegistration??!0,paths:w,callbackUrl:`${n.origin}${w.callback}`,trustProxy:e.trustProxy??!1,now:C,scopeDescriptions:or(d,e.scopeDescriptions),staticClients:ir(e.clients,d,k,C),...e.resourceName!==void 0?{resourceName:e.resourceName}:{},...e.rateLimit?{rateLimit:e.rateLimit}:{},...e.getClientIp?{getClientIp:e.getClientIp}:{},...e.onEvent?{onEvent:e.onEvent}:{},...e.fetchClientMetadata?{fetchClientMetadata:e.fetchClientMetadata}:{},...e.authorizeClient?{authorizeClient:e.authorizeClient}:{},...e.allowRegistration?{allowRegistration:e.allowRegistration}:{},...e.mapSubject?{mapSubject:e.mapSubject}:{},...e.allowSubject?{allowSubject:e.allowSubject}:{},...e.allowClientMetadataUrl?{allowClientMetadataUrl:e.allowClientMetadataUrl}:{},...e.getGrantContext?{getGrantContext:e.getGrantContext}:{},...e.getConsentDetails?{getConsentDetails:e.getConsentDetails}:{},...e.readConsentFields?{readConsentFields:e.readConsentFields}:{},...e.beforeGrant?{beforeGrant:e.beforeGrant}:{},...e.afterGrant?{afterGrant:e.afterGrant}:{},...e.beforeTokenIssue?{beforeTokenIssue:e.beforeTokenIssue}:{}}}i(dr,"resolveOptions");import{safeFetch as mn}from"@gydr-ai/safe-fetch";var M=class extends Error{static{i(this,"ClientMetadataError")}reason;constructor(t){super(`Client ID Metadata Document not accepted (${t})`),this.name="ClientMetadataError",this.reason=t}};function hn(e,t,r,n){if(!L(t))throw new M("not_an_object");if(t.client_id!==e)throw new M("client_id_differs_from_url");let o=t.token_endpoint_auth_methods_supported;if(t.token_endpoint_auth_method!==void 0&&t.token_endpoint_auth_method!=="none"||o!==void 0&&(!z(o)||!o.includes("none"))||t.client_secret!==void 0)throw new M("confidential_client");let s=Z(t.grant_types,!1,n.defaultGrantTypes);if(s===void 0)throw new M("grant_types_unusable");if(t.response_types!==void 0&&(!z(t.response_types)||!t.response_types.includes("code")))throw new M("response_types_unusable");let a=He(t.scope,n.scopes,!1,n.limits.scopeLength);if(a===void 0)throw new M("scope_unusable");if(!z(t.redirect_uris))throw new M("redirect_uris_absent");let c=t.redirect_uris.filter(l=>lt(l,n.limits)).slice(0,n.limits.redirectUris);if(c.length===0)throw new M("redirect_uris_unusable");let d=X(t.client_name,n.limits.clientNameLength);return{clientId:e,redirectUris:c,kind:"metadata_document",createdAt:r,grantTypes:s,...a!==null?{scopes:a}:{},...d!==void 0?{clientName:d}:{}}}i(hn,"validateClientMetadata");function gn(e){return(t,r)=>mn(t,{method:"GET",headers:{Accept:"application/json"},redirect:"error",signal:r.signal},{timeoutMs:e.limits.clientMetadataTimeoutMs,maxResponseBytes:e.limits.clientMetadataBytes,label:"client metadata"})}i(gn,"bundledFetcher");function ur(e,t){return t.aborted?Promise.reject(new M("timeout")):new Promise((r,n)=>{let o=i(()=>{n(new M("timeout"))},"onAbort");t.addEventListener("abort",o,{once:!0}),e.then(s=>{t.removeEventListener("abort",o),r(s)},s=>{t.removeEventListener("abort",o),n(s instanceof Error?s:new M(ze(s)))})})}i(ur,"beforeAbort");async function yn(e,t,r){let n=Number(e.headers.get("content-length"));if(Number.isFinite(n)&&n>t)throw await e.body?.cancel().catch(()=>{}),new M("too_large");if(e.body===null)return"";let o=e.body.getReader(),s=[],a=0;try{for(;;){let c=await ur(o.read(),r);if(c.done)break;let d=c.value;if(!(d instanceof Uint8Array))throw new M("not_bytes");if(a+=d.byteLength,a>t)throw new M("too_large");s.push(d)}}catch(c){throw await o.cancel().catch(()=>{}),c}return Buffer.concat(s).toString("utf8")}i(yn,"readLimited");function ze(e){return e instanceof M?e.reason:L(e)?typeof e.code=="string"?e.code:typeof e.reason=="string"?e.reason:"unreachable":"unreachable"}i(ze,"failureReason");function wn(e){if(e===null)return;let t;for(let r of e.split(",")){let[n="",o=""]=r.split("=",2);switch(n.trim().toLowerCase()){case"no-store":case"no-cache":return 0;case"max-age":{let a=o.trim().replace(/^"(.*)"$/,"$1");t=/^\d{1,10}$/.test(a)?Number(a):0;break}default:break}}return t}i(wn,"cacheControlSeconds");async function lr(e,t,r){let n=r.fetchClientMetadata??gn(r),o=AbortSignal.timeout(r.limits.clientMetadataTimeoutMs),s,a;try{let d=await ur(n(e,{signal:o}),o);if(d.status!==200)throw await d.body?.cancel().catch(()=>{}),new M(`status_${d.status}`);a=wn(d.headers.get("cache-control")),s=await yn(d,r.limits.clientMetadataBytes,o)}catch(d){throw d instanceof M?d:new M(ze(d))}let c;try{c=JSON.parse(s)}catch{throw new M("invalid_json")}return{client:hn(e,c,t,r),maxAgeSeconds:a}}i(lr,"fetchClientMetadata");function mt(e){try{return new URL(e).host}catch{return""}}i(mt,"hostOf");function pr(e){let t;try{t=new URL(e)}catch{return}let r=de(t.hostname,"."),n=de(t.pathname,"/");return`${t.protocol}//${r}:${t.port}${n}`}i(pr,"serverIdentity");function _n(e,t){let r=pr(e);return r!==void 0&&r===pr(t)}i(_n,"isIssuerUrl");async function Fe(e,t){let{options:r}=e;if(t.length>Se)return;if(!ge(t)){let h=r.staticClients.get(t);if(h!==void 0)return h;let m=await r.store.getClient(t);return m?.kind==="metadata_document"?void 0:m}if(!r.clientIdMetadataDocuments)return;if(_n(t,r.issuer)){await e.emit({type:"client_metadata_refused",host:mt(t),reason:"client_id_is_issuer"});return}let n=r.allowClientMetadataUrl;if(n!==void 0&&!await he(()=>n(t))){await e.emit({type:"client_metadata_refused",host:mt(t),reason:"not_allowed_by_policy"});return}let o=await r.store.getCachedClientMetadata(t);if(o?.clientId===t)return o;let{failures:s,inflight:a}=e.cimd,c=s.get(t);if(c!==void 0){if(c>r.now())return;s.delete(t)}let d=a.get(t);if(d!==void 0)return d;let l=kn(e,t).finally(()=>{a.delete(t)});return a.set(t,l),l}i(Fe,"resolveClient");async function kn(e,t){let{options:r}=e,n=r.now(),o;try{o=await lr(t,n,r)}catch(c){Rn(e,t),await e.emit({type:"client_metadata_refused",host:mt(t),reason:ze(c)});return}let s=o.maxAgeSeconds,a=s===void 0?r.clientMetadataCacheMs:Math.min(s*1e3,r.clientMetadataCacheMs);return a>0&&await r.store.putCachedClientMetadata(t,o.client,n+a),o.client}i(kn,"downloadAndRemember");function Rn(e,t){let{options:r}=e,{failures:n}=e.cimd;if(r.clientMetadataFailureMs!==0){for(n.delete(t);n.size>=r.limits.clientMetadataFailures;){let o=n.keys().next();if(o.done===!0)break;n.delete(o.value)}n.set(t,r.now()+r.clientMetadataFailureMs)}}i(Rn,"rememberFailure");function Be(e,t){let r=e.headers.get("cookie");if(r!==null)for(let n of r.split(";")){let o=n.indexOf("=");if(o!==-1&&n.slice(0,o).trim()===t)return n.slice(o+1).trim()}}i(Be,"readCookie");function qe(e,t,r){return`${e}=${t}; Path=/; Max-Age=${r}; HttpOnly; Secure; SameSite=Lax`}i(qe,"hostCookie");function Ke(e){return`${e}=; Path=/; Max-Age=0; HttpOnly; Secure; SameSite=Lax`}i(Ke,"clearHostCookie");function Q(e,t){return e+x(`binding:${t}`).slice(0,20)}i(Q,"bindingCookieName");function ee(e){let t=new Map;for(let[r,n]of e){let o=t.get(r);o?o.push(n):t.set(r,[n])}return t}i(ee,"groupParams");function R(e,t){let r=e.get(t)?.[0];return r===void 0||r===""?void 0:r}i(R,"single");function te(e,t){return t.filter(r=>(e.get(r)?.length??0)>1)}i(te,"repeatedDefined");function fr(e){let t=e.indexOf("://");if(t===-1)return;let r=e.indexOf("/",t+3),n=r===-1?e.length:r;return{authority:e.slice(0,n).toLowerCase(),rest:e.slice(n)}}i(fr,"splitAuthority");function we(e,t){if(t===e)return!0;let r=fr(e),n=fr(t);return r!==void 0&&n!==void 0&&r.authority===n.authority&&r.rest===n.rest}i(we,"sameResource");function mr(e,t,r,n){if(e===void 0)return r;if(e.length>n)return;let o=[...new Set(e.split(" ").filter(a=>a.length>0))];return o.length===0?void 0:o.every(a=>De(a)&&t.includes(a))?o:void 0}i(mr,"resolveScopes");var bn=["client_id","redirect_uri","response_type","code_challenge","code_challenge_method","resource","scope","state","prompt"];async function hr(e,t){let{options:r}=e,{limits:n}=r;if(!await e.allowed(t,"authorize"))return e.errorPage(t,"rate_limited");let o=ee(new URL(t.url).searchParams),s=i(async(N,q,E={})=>(await e.emit({type:"authorization_refused",reason:N,...q!==void 0?{clientId:q}:{}}),e.errorPage(t,N,E)),"refuse");if(te(o,bn).length>0)return s("repeated_parameter");let a=R(o,"client_id"),c=a===void 0?void 0:await Fe(e,a);if(a===void 0||c===void 0)return s("client_unknown");let d=R(o,"redirect_uri"),[l]=c.redirectUris.length===1?c.redirectUris:[],h=d??l;if(h===void 0||!rr(c.redirectUris,h,n))return s("redirect_uri_not_registered",a);let m=R(o,"state");if(m!==void 0&&m.length>n.stateLength)return s("invalid_request",a,{detail:`The state value exceeds ${n.stateLength} characters`});if(R(o,"response_type")!=="code")return s("unsupported_response_type",a,{detail:"Only the authorization code flow is offered"});let u=R(o,"code_challenge");if(u===void 0||!Ft(u))return s("invalid_request",a,{detail:"A 43-character S256 code_challenge must accompany the request"});if(R(o,"code_challenge_method")!=="S256")return s("invalid_request",a,{detail:"The only accepted code_challenge_method is S256"});let p=R(o,"resource");if(p===void 0||!we(r.resource,p))return s("invalid_target",a,{detail:`Tokens from this server are only for ${r.resource}`});let f=c.scopes??r.scopes,w=r.defaultScopes.filter(N=>f.includes(N)),y=mr(o.get("scope")?.[0],f,w.length>0?w:f,n.scopeLength);if(y===void 0)return s("invalid_scope",a);if(R(o,"prompt")?.split(" ").includes("none"))return s("consent_required",a);let k=r.authorizeClient;if(k!==void 0){let N=await ae(()=>k({client:j(c),redirectUri:h,scopes:j(y),request:t}));if(!N.allowed)return s("access_denied",a,N.reason===void 0?{}:{policyReason:N.reason})}let C=D(),O=D(),T=D(),g=D(),H={id:C,clientId:c.clientId,clientKind:c.kind,redirectUri:h,codeChallenge:u,resource:r.resource,scopes:y,upstreamCodeVerifier:T,upstreamNonce:g,bindingHash:x(O),allowRefresh:c.grantTypes?.includes("refresh_token")??!0,expiresAt:r.now()+r.pendingTtlMs,...c.clientName!==void 0?{clientName:c.clientName}:{},...m!==void 0?{state:m}:{}};await r.store.putPendingAuthorization(H);let G=await r.identityProvider.authorizationUrl({state:C,codeChallenge:it(T),redirectUri:r.callbackUrl,nonce:g});return await e.emit({type:"authorization_started",clientId:c.clientId,scopes:y}),ie(G,[qe(Q(r.cookiePrefix,C),O,Math.ceil(r.pendingTtlMs/1e3))])}i(hr,"handleAuthorize");import{randomUUID as xn}from"node:crypto";function Cn(e){try{return new URL(e).host}catch{return""}}i(Cn,"documentHost");function Ve(e,t,r,n,o={}){let{options:s}=e,a=s.renderConsentPage(j({clientId:r.clientId,clientKind:r.clientKind,redirectUri:r.redirectUri,redirectHost:Ge(r.redirectUri),redirectIsLoopback:tr(r.redirectUri),scopes:r.scopes,scopeDescriptions:{...s.scopeDescriptions},resource:r.resource,formAction:s.paths.consent,hiddenFields:{[K.id]:r.id,[K.csrf]:n},decisionField:K.decision,locales:Ne(t.headers.get("accept-language")),...r.clientName!==void 0?{clientName:r.clientName}:{},...r.clientKind==="metadata_document"?{clientHost:Cn(r.clientId)}:{},...r.displayName!==void 0?{subjectDisplayName:r.displayName}:{},...r.details!==void 0?{details:r.details}:{},...o.fieldErrors!==void 0?{fieldErrors:o.fieldErrors}:{},...o.submitted!==void 0?{submitted:o.submitted}:{}})),c=nr(r.redirectUri),d=[...o.setCookies??[]];return o.binding!==void 0&&d.push(qe(Q(s.cookiePrefix,r.id),o.binding,Math.ceil(s.pendingTtlMs/1e3))),Me(o.status??200,a,{formActionOrigins:c===void 0?[]:[c],setCookies:d,scriptHashes:s.scriptHashes})}i(Ve,"consentPageResponse");var Tn=512;function An(e){return typeof e=="string"&&e!==""&&e.length<=Tn&&e.trim()===e&&e.normalize("NFC")===e&&!ce(e)}i(An,"isUsableSubject");function En(e){if(typeof e!="object"||e===null)return;let t=Reflect.get(e,"subject"),r=Reflect.get(e,"displayName");return{subject:t,displayName:r}}i(En,"readMapped");async function gr(e,t,r){let{mapSubject:n,allowSubject:o,limits:s}=e.options,a=t.claims??{},c=t.subject,d=t.displayName;if(n!==void 0){let m;try{m=En(await n(j({subject:t.subject,claims:a,...t.displayName!==void 0?{displayName:t.displayName}:{}})))}catch{return{ok:!1}}if(m===void 0)return{ok:!1};c=m.subject,d=m.displayName}if(!An(c))return{ok:!1};let l=d===void 0?void 0:X(d,s.clientNameLength),h=l===void 0?{subject:c}:{subject:c,displayName:l};if(o!==void 0){let m=await ae(()=>o(j({...h,claims:a,client:r})));if(!m.allowed)return m.reason===void 0?{ok:!1}:{ok:!1,policyReason:m.reason}}return{ok:!0,person:h}}i(gr,"resolvePerson");var Pn=["state","code","error","error_description","error_uri","iss"];async function yr(e,t){let{options:r}=e;if(!await e.allowed(t,"callback"))return e.errorPage(t,"rate_limited");let n=ee(new URL(t.url).searchParams);if(te(n,Pn).length>0)return e.errorPage(t,"malformed_response");let o=R(n,"state");if(o===void 0)return e.errorPage(t,"flow_ended");let s=Q(r.cookiePrefix,o),a=Ke(s),c=await r.store.getPendingAuthorization(o);if(c===void 0||P(c.expiresAt,r.now()))return e.errorPage(t,"flow_ended");let d=Be(t,s);if(d===void 0||!fe(x(d),c.bindingHash))return await e.emit({type:"flow_binding_mismatch",step:"callback"}),e.errorPage(t,"browser_mismatch",{setCookies:[a]});let l=await r.store.consumePendingAuthorization(o);if(l===void 0||P(l.expiresAt,r.now())||l.bindingHash!==c.bindingHash)return e.errorPage(t,"flow_ended");let h=R(n,"error");if(h!==void 0){let E=h==="access_denied";return await e.emit({type:"identity_provider_error",clientId:l.clientId,reason:E?"person_cancelled":"provider_reported_error"}),ie($e(l.redirectUri,{error:E?"access_denied":"server_error",error_description:E?"The person stopped at the sign-in step":"The identity provider could not complete the sign-in",state:l.state,iss:r.issuer}),[a])}let m=R(n,"code");if(m===void 0)return e.errorPage(t,"malformed_response",{setCookies:[a]});let u=R(n,"iss"),p;try{p=await r.identityProvider.exchangeCode({code:m,codeVerifier:l.upstreamCodeVerifier,redirectUri:r.callbackUrl,nonce:l.upstreamNonce,...u!==void 0?{issuer:u}:{}})}catch(E){return await e.emit({type:"identity_provider_error",clientId:l.clientId,reason:E instanceof Error?E.name:"exchange_failed"}),e.errorPage(t,"sign_in_not_confirmed",{setCookies:[a]})}let f=i(async()=>{p.refreshToken!==void 0&&await at(e,p.refreshToken)},"releaseUpstream");if(typeof p.subject!="string"||p.subject.length===0)return await f(),await e.emit({type:"identity_provider_error",clientId:l.clientId,reason:"subject_missing"}),e.errorPage(t,"sign_in_not_confirmed",{setCookies:[a]});let w={clientId:l.clientId,kind:l.clientKind,...l.clientName!==void 0?{clientName:l.clientName}:{}},y=await gr(e,p,w);if(!y.ok)return await f(),await e.emit({type:"identity_provider_error",clientId:l.clientId,reason:"subject_not_permitted"}),e.errorPage(t,"subject_not_permitted",{setCookies:[a],...y.policyReason!==void 0?{policyReason:y.policyReason}:{}});let{person:k}=y,C;if(r.getConsentDetails!==void 0)try{C=J(await r.getConsentDetails(Object.freeze({...j({subject:k.subject,client:w,scopes:[...l.scopes]}),request:t})),r.limits.consentDetailsBytes,"getConsentDetails")}catch{return await f(),e.errorPage(t,"server_error",{setCookies:[a]})}let O=r.now(),T=xn(),g=D(),{sealer:H}=r,G=p.expiresIn!==void 0&&Number.isFinite(p.expiresIn)?Math.min(Math.max(p.expiresIn,0),Pe):void 0,N={id:D(),grantId:T,clientId:l.clientId,clientKind:l.clientKind,redirectUri:l.redirectUri,codeChallenge:l.codeChallenge,resource:l.resource,scopes:l.scopes,subject:k.subject,csrfHash:x(g),bindingHash:l.bindingHash,expiresAt:O+r.pendingTtlMs,...l.allowRefresh!==void 0?{allowRefresh:l.allowRefresh}:{},...l.clientName!==void 0?{clientName:l.clientName}:{},...l.state!==void 0?{state:l.state}:{},...k.displayName!==void 0?{displayName:k.displayName}:{},...C!==void 0?{details:C}:{},...p.refreshToken!==void 0?{sealedUpstreamRefreshToken:await H.seal(p.refreshToken,T)}:{},...p.accessToken!==void 0&&G!==void 0?{sealedUpstreamAccessToken:await H.seal(p.accessToken,`${T}#access`),upstreamAccessTokenExpiresAt:O+G*1e3}:{}},q;try{q=Ve(e,t,N,g,{binding:d,setCookies:[a]})}catch(E){throw await f(),E}return await r.store.putConsentRequest(N),q}i(yr,"handleCallback");function wr(e,t){let r=t+e.grantTtlMs;return e.grantIdleMs>0?Math.min(r,t+e.grantIdleMs):r}i(wr,"initialGrantExpiry");function _r(e,t,r){let n=t.createdAt+e.grantTtlMs,o=e.grantIdleMs>0?Math.min(n,r+e.grantIdleMs):n;return o>t.expiresAt?o:void 0}i(_r,"slidGrantExpiry");var F=class extends Error{static{i(this,"BodyTooLargeError")}constructor(){super("Body exceeds the configured size limit"),this.name="BodyTooLargeError"}};function _e(e,t){let r=e.headers.get("content-type");if(r===null)return!1;let[n]=r.split(";");return(n??"").trim().toLowerCase()===t}i(_e,"hasContentType");async function ke(e,t){let r=Number(e.headers.get("content-length"));if(Number.isFinite(r)&&r>t)throw new F;if(e.body===null)return"";let n=e.body.getReader(),o=[],s=0;for(;;){let a=await n.read();if(a.done)break;let c=a.value;if(!(c instanceof Uint8Array))throw new TypeError("Body is not bytes");if(s+=c.byteLength,s>t)throw await n.cancel(),new F;o.push(c)}return Buffer.concat(o).toString("utf8")}i(ke,"readBody");import{setTimeout as Sn}from"node:timers/promises";var kr=200,br=Object.values(K),vn=50,Rr=200;function In(e){let t=[];for(let[r,n]of e){let[o]=n;!br.includes(r)&&o!==void 0&&t.push([r,o])}return Object.fromEntries(t)}i(In,"extraFields");function Mn(e){if(!L(e))return;let t=Object.entries(e);if(t.length===0||t.length>vn)return;let r=[];for(let[n,o]of t){if(typeof o!="string"||o===""||o.length>Rr||n.length>Rr)return;r.push([n,o])}return Object.fromEntries(r)}i(Mn,"readFieldErrors");function Cr(e){return{clientId:e.clientId,kind:e.clientKind,...e.clientName!==void 0?{clientName:e.clientName}:{}}}i(Cr,"hookClient");async function jn(e,t,r){let n=e.options.readConsentFields;if(n===void 0)return{kind:"accepted",grantData:void 0};let o;try{o=await n(j({form:{...r},details:t.details,subject:t.subject,client:Cr(t),scopes:[...t.scopes]}))}catch{return{kind:"failed"}}if(!L(o))return{kind:"failed"};switch(o.ok){case!0:try{return{kind:"accepted",grantData:J(o.grantData,e.options.limits.grantDataBytes,"readConsentFields")}}catch{return{kind:"failed"}}case!1:{let s=Mn(o.fieldErrors);return s===void 0?{kind:"failed"}:{kind:"correct",fieldErrors:s}}default:return{kind:"failed"}}}i(jn,"readFields");async function Tr(e,t){let{options:r}=e;if(!await e.allowed(t,"consent"))return e.errorPage(t,"rate_limited");let n=t.headers.get("origin");if(n!==null&&n!=="null"&&n!==r.issuerOrigin)return e.errorPage(t,"consent_unavailable");if(!_e(t,ve))return e.errorPage(t,"unsupported_submission");let o;try{o=ee(new URLSearchParams(await ke(t,r.limits.formBytes)))}catch(I){if(I instanceof F)return e.errorPage(t,"consent_unavailable");throw I}if(te(o,br).length>0)return e.errorPage(t,"consent_unavailable");let s=R(o,K.id),a=R(o,K.csrf);if(s===void 0||a===void 0)return e.errorPage(t,"consent_unavailable");let{store:c,sealer:d}=r,l=Q(r.cookiePrefix,s),h=Ke(l),m=Be(t,l),u=i(()=>e.errorPage(t,"consent_unavailable",{setCookies:[h]}),"ended"),p=m===void 0?void 0:x(`${x(m)}:${x(a)}`),f=p!==void 0&&r.consentReplayMs>0&&c.putConsentOutcome!==void 0&&c.getConsentOutcome!==void 0,w=i(async I=>{if(f)try{let U=r.now()+r.consentReplayMs;await c.putConsentOutcome?.(p,await d.seal(JSON.stringify({...I,expiresAt:U}),p),U)}catch{}},"remember"),y,k,C=0,O=i(async()=>{if(!f)return;let I=await c.getConsentOutcome?.(p);if(I===void 0)return;if(I===y&&k!==void 0)return"pending"in k&&!P(C,r.now())?k:void 0;let U;try{U=JSON.parse(await d.open(I,p))}catch{return}if(!(!L(U)||typeof U.expiresAt!="number"||P(U.expiresAt,r.now())))return y=I,C=U.expiresAt,k=U.pending===!0?{pending:!0}:typeof U.location=="string"?{location:U.location}:void 0,k},"recall"),T=i(async I=>{if(!f)return u();let U=Math.ceil(r.consentReplayMs/kr);for(let bt=0;;bt+=1){let xe=await O();if(xe!==void 0&&"location"in xe)return ie(xe.location,[h],303);if(xe===void 0&&!I||bt>=U||t.signal.aborted)return u();await Sn(kr)}},"replay"),g=await c.getConsentRequest(s);if(g===void 0)return T(!1);let H=i(()=>ct(e,g.sealedUpstreamRefreshToken,g.grantId),"releaseUpstream"),G=i(async()=>{await c.consumeConsentRequest(s),await H()},"abandon");if(P(g.expiresAt,r.now()))return await G(),u();let N=fe(x(a),g.csrfHash),q=m!==void 0&&fe(x(m),g.bindingHash);if(!N||!q)return await e.emit({type:"flow_binding_mismatch",step:"consent"}),await G(),u();let E=R(o,K.decision)===Ot,le;if(E){let I=In(o),U=await jn(e,g,I);switch(U.kind){case"correct":return Ve(e,t,g,a,{status:400,fieldErrors:U.fieldErrors,submitted:{...I}});case"failed":return await G(),e.errorPage(t,"server_error",{setCookies:[h]});case"accepted":le=U.grantData;break}}if((await c.consumeConsentRequest(s))?.csrfHash!==g.csrfHash)return T(!0);await w({pending:!0});let Ee=i(async I=>{let U=$e(g.redirectUri,{...I,state:g.state,iss:r.issuer});return await w({location:U}),ie(U,[h],303)},"answer");if(!E)return await H(),await e.emit({type:"consent_declined",clientId:g.clientId,subject:g.subject}),Ee({error:"access_denied",error_description:"The person declined to grant access"});let _t=r.beforeGrant;if(_t!==void 0){let I=await ae(()=>_t(Object.freeze({...j({subject:g.subject,client:Cr(g),scopes:[...g.scopes],grantData:le}),request:t})));if(!I.allowed)return await H(),await e.emit({type:"authorization_refused",clientId:g.clientId,reason:I.reason??"before_grant"}),Ee({error:"access_denied",error_description:"Access was not granted"})}let Qe=r.now(),W={grantId:g.grantId,clientId:g.clientId,subject:g.subject,scopes:g.scopes,resource:g.resource,createdAt:Qe,expiresAt:wr(r,Qe),redirectUri:g.redirectUri,...le!==void 0?{data:le}:{},...g.allowRefresh!==void 0?{allowRefresh:g.allowRefresh}:{},...g.clientName!==void 0?{clientName:g.clientName}:{},...g.displayName!==void 0?{displayName:g.displayName}:{},...g.sealedUpstreamRefreshToken!==void 0?{sealedUpstreamRefreshToken:g.sealedUpstreamRefreshToken}:{},...g.sealedUpstreamAccessToken!==void 0&&g.upstreamAccessTokenExpiresAt!==void 0?{sealedUpstreamAccessToken:g.sealedUpstreamAccessToken,upstreamAccessTokenExpiresAt:g.upstreamAccessTokenExpiresAt}:{}};await c.putGrant(W);let kt=D();await c.putAuthorizationCode({codeHash:x(kt),grantId:W.grantId,clientId:g.clientId,redirectUri:g.redirectUri,codeChallenge:g.codeChallenge,resource:g.resource,scopes:g.scopes,expiresAt:Qe+r.codeTtlMs});let Rt=r.afterGrant;if(Rt!==void 0)try{await Rt(Object.freeze({grant:me(W)}))}catch(I){return await c.deleteGrant(W.grantId),await H(),await e.emit({type:"unexpected_failure",where:"afterGrant",errorName:I instanceof Error?I.name:typeof I}),Ee({error:"server_error",error_description:"The connection could not be completed"})}return await e.emit({type:"consent_approved",grantId:W.grantId,clientId:W.clientId,subject:W.subject,scopes:W.scopes}),Ee({code:kt})}i(Tr,"handleConsent");function re(e){return $(400,"invalid_client_metadata",e)}i(re,"badMetadata");function ht(e){return $(400,"invalid_redirect_uri",e)}i(ht,"badRedirect");async function Ar(e,t){let{options:r}=e,{limits:n}=r;if(!await e.allowed(t,"register"))return $(429,"temporarily_unavailable","Registration rate exceeded; retry later");if(!_e(t,"application/json"))return re("Send the client metadata as application/json");let o;try{o=JSON.parse(await ke(t,n.registrationBytes))}catch(w){return re(w instanceof F?`The metadata exceeds ${n.registrationBytes} bytes`:"The body is not a JSON object")}if(!L(o))return re("The body is not a JSON object");let s=o.redirect_uris;if(!z(s)||s.length===0)return ht("List at least one redirect URI in redirect_uris");if(s.length>n.redirectUris)return ht(`Register at most ${n.redirectUris} redirect URIs`);for(let w of s){let y=Ae(w,n);if(y!==void 0)return ht(`Redirect URI refused (${y}). Allowed: https URLs, or http on 127.0.0.1, [::1] or localhost`)}let a=o.token_endpoint_auth_method;if(a!==void 0&&a!=="none")return re('This server registers public clients only; token_endpoint_auth_method must be "none"');let c=Z(o.grant_types,!0,r.defaultGrantTypes);if(c===void 0)return re('grant_types must include "authorization_code" and may add "refresh_token"; nothing else is offered');let d=o.response_types??["code"];if(!z(d)||d.length!==1||d[0]!=="code")return re('The only response type offered is "code"');let l=He(o.scope,r.scopes,!0,n.scopeLength);if(l===void 0)return re(`Available scopes: ${r.scopes.join(" ")}`);let h;if(o.client_name!==void 0&&(h=X(o.client_name,n.clientNameLength),h===void 0))return re(`client_name needs 1 to ${n.clientNameLength} visible characters`);let m=r.allowRegistration;if(m!==void 0&&!await he(()=>m({metadata:j(o),request:t})))return $(403,"invalid_client_metadata","This server does not accept the registration of this client");let u=r.now(),p=[...new Set(s)],f={clientId:`client-${D()}`,redirectUris:p,kind:"dynamic",createdAt:u,grantTypes:c,...l!==null?{scopes:l}:{},...h!==void 0?{clientName:h}:{}};return await r.store.putClient(f),await e.emit({type:"client_registered",clientId:f.clientId,redirectHosts:[...new Set(p.map(Ge))],...h!==void 0?{clientName:h}:{}}),oe(201,{client_id:f.clientId,client_id_issued_at:Math.floor(u/1e3),redirect_uris:p,grant_types:c,response_types:["code"],token_endpoint_auth_method:"none",...l!==null?{scope:l.join(" ")}:{},...h!==void 0?{client_name:h}:{}},{cors:!0})}i(Ar,"handleRegister");var b=class extends Error{constructor(r,n,o=400,s,a){super(n);this.error=r;this.description=n;this.status=o;this.challenge=s;this.detail=a;this.name="EndpointRefusal"}error;description;status;challenge;detail;static{i(this,"EndpointRefusal")}};var On=/^[!#$%&'*+.^_`|~0-9A-Za-z-]{1,32}$/,Un=["client_id","client_secret","client_assertion","client_assertion_type"];function Ln(e){let t=e.trim().split(" ")[0]??"";return On.test(t)?t:"Basic"}i(Ln,"schemeOf");async function We(e,t,r){if(!_e(e,ve))throw new b("invalid_request","Send the parameters as an application/x-www-form-urlencoded body");let n;try{n=ee(new URLSearchParams(await ke(e,t)))}catch(c){throw c instanceof F?new b("invalid_request",`The body exceeds ${t} bytes`):c}let o=te(n,[...Un,...r]);if(o.length>0)throw new b("invalid_request",`Parameter sent more than once: ${o.join(", ")}`);let s=e.headers.get("authorization"),a="Clients here authenticate with PKCE alone; remove the client credentials";if(s!==null)throw new b("invalid_client",a,401,Ln(s));if(n.has("client_secret")||n.has("client_assertion"))throw new b("invalid_client",a);return{form:n,clientId:R(n,"client_id")}}i(We,"readPublicClientForm");function Je(e,t){let r=R(t,"resource");if(r!==void 0&&!we(e.options.resource,r))throw new b("invalid_target",`Tokens from this server are only for ${e.options.resource}`)}i(Je,"requireOwnResource");var Nn={"Cache-Control":"no-store",Pragma:"no-cache","Access-Control-Allow-Origin":"*"},Dn=["token","token_type_hint"];async function Er(e,t,r){let{store:n,limits:o}=e.options,s=i(()=>new Response(null,{status:200,headers:Nn}),"done");try{if(!await e.allowed(t,"revoke"))return $(429,"temporarily_unavailable","Request rate exceeded; retry later");let{form:a,clientId:c}=await We(t,o.formBytes,Dn),d=R(a,"token");if(d===void 0)throw new b("invalid_request","Missing parameter: token");if(!Y(d))return s();let l=x(d),h=i(f=>c===void 0||c===f,"callerMayAct"),m=i(async()=>{let f=await n.getRefreshToken(l);return f===void 0||!h(f.clientId)?!1:(await r(f.grantId,"revocation_request"),!0)},"asRefreshToken"),u=i(async()=>{let f=await n.getAccessToken(l);return f===void 0||!h(f.clientId)?!1:(await n.deleteAccessToken(l),!0)},"asAccessToken"),p=R(a,"token_type_hint")==="access_token"?[u,m]:[m,u];for(let f of p)if(await f())break;return s()}catch(a){if(!(a instanceof b))throw a;return $(a.status,a.error,a.description,a.challenge)}}i(Er,"handleRevoke");async function Ye(e,t,r){let n=e.options.beforeTokenIssue;if(n===void 0)return;let o;try{o=await n(Object.freeze({grant:me(t),grantType:r}))}catch{throw new b("temporarily_unavailable","Tokens cannot be issued right now; retry later",503)}if(!dt(o).allowed)throw new b("invalid_grant","Tokens are not issued for this grant")}i(Ye,"requireTokenIssue");async function xr(e,t,r,n){let{options:o}=e,s=R(t,"code"),a=R(t,"code_verifier"),c=R(t,"redirect_uri"),d=[s===void 0?"code":void 0,a===void 0?"code_verifier":void 0].filter(T=>T!==void 0);if(s===void 0||a===void 0)throw new b("invalid_request",`Missing parameter: ${d.join(", ")}`);Je(e,t);let l=i(T=>new b("invalid_grant","This authorization code cannot be exchanged",400,void 0,T),"unusable");if(!Y(s))throw l("code_malformed");let h=x(s),m=await o.store.getAuthorizationCode(h);if(m===void 0)throw l("code_unknown");let u=m.record,p=R(t,"resource"),w=[["client_id",u.clientId!==r],["redirect_uri",c!==void 0&&u.redirectUri!==c],["resource",p!==void 0&&!we(u.resource,p)],["code_verifier",!Bt(a,u.codeChallenge)]].find(([,T])=>T)?.[0];if(w!==void 0)throw l(`${w}_mismatch`);let y=i(async()=>(await e.emit({type:"authorization_code_replayed",grantId:u.grantId,clientId:u.clientId}),await n(u.grantId,"authorization_code_replay"),l("code_replayed")),"replayed");if(m.consumed)throw await y();if(P(u.expiresAt,o.now()))throw await n(u.grantId,"authorization_code_expired"),l("code_expired");let k=await se(e,u.grantId,r);if(k===void 0)throw new b("invalid_grant","Access has been withdrawn");await Ye(e,k,"authorization_code");let C=await o.store.consumeAuthorizationCode(h);if(C===void 0)throw l("code_unknown");if(!C.firstUse)throw await y();let O=await Oe(e,k,u.scopes);return await e.emit({type:"token_issued",grantId:k.grantId,clientId:r,subject:k.subject,grantType:"authorization_code"}),O}i(xr,"exchangeCode");async function Pr(e,t,r,n){let{options:o}=e,s=R(t,"refresh_token");if(s===void 0)throw new b("invalid_request","Missing parameter: refresh_token");Je(e,t);let a=i(()=>new b("invalid_grant","This refresh token cannot be used"),"unusable");if(!Y(s))throw a();let c=x(s),d=o.now(),l=await o.store.getRefreshToken(c);if(l===void 0||l.clientId!==r||P(l.expiresAt,d))throw a();let h=l.scopes,m=R(t,"scope");if(m!==void 0){let T=[...new Set(m.split(" ").filter(g=>g.length>0))];if(T.length===0||T.some(g=>!l.scopes.includes(g)))throw new b("invalid_scope","A refreshed token can only carry scopes already granted");h=T}let u=await se(e,l.grantId,r);if(u===void 0||u.allowRefresh===!1)throw new b("invalid_grant","Access has been withdrawn");await Ye(e,u,"refresh_token");let p=await o.store.useRefreshToken(c,d);if(p===void 0)throw a();let f=p.previousUsedAt,w=f!==void 0&&o.refreshReuseGraceMs>0&&d-f<=o.refreshReuseGraceMs;if(f!==void 0&&!w)throw await e.emit({type:"refresh_token_replayed",grantId:p.record.grantId,clientId:r}),await n(p.record.grantId,"refresh_token_replay"),a();let y=await se(e,p.record.grantId,r);if(y===void 0||y.allowRefresh===!1)throw new b("invalid_grant","Access has been withdrawn");let k=_r(o,y,d),C=k!==void 0&&await o.store.updateGrant(y.grantId,{expiresAt:k})?{...y,expiresAt:k}:y,O=await Oe(e,C,h,l.scopes);return await e.emit({type:"token_issued",grantId:y.grantId,clientId:r,subject:y.subject,grantType:"refresh_token"}),O}i(Pr,"exchangeRefreshToken");var Hn=["grant_type","code","redirect_uri","code_verifier","refresh_token","scope","resource"];async function Sr(e,t,r){let n;try{if(!await e.allowed(t,"token"))return $(429,"temporarily_unavailable","Request rate exceeded; retry later");let o=await We(t,e.options.limits.formBytes,Hn);if(n=o.clientId,n===void 0)throw new b("invalid_client","Missing parameter: client_id");let s=ge(n),a=s?void 0:await Fe(e,n);if(!s&&a===void 0)throw new b("invalid_client","No client is registered under this client_id");let c=R(o.form,"grant_type");if(c==="refresh_token"&&a?.grantTypes!==void 0&&!a.grantTypes.includes("refresh_token"))throw new b("unauthorized_client","refresh_token is not among this client's registered grant_types");let d;switch(c){case"authorization_code":d=await xr(e,o.form,n,r);break;case"refresh_token":d=await Pr(e,o.form,n,r);break;case void 0:throw new b("invalid_request","Missing parameter: grant_type");default:throw new b("unsupported_grant_type","This server only exchanges authorization codes and refresh tokens")}return oe(200,d,{cors:!0})}catch(o){if(!(o instanceof b))throw o;return await e.emit({type:"token_request_refused",error:o.error,reason:o.detail??o.description,...n!==void 0?{clientId:n}:{}}),$(o.status,o.error,o.description,o.challenge)}}i(Sr,"handleToken");function vr(e){let t=i(r=>`${e.issuerOrigin}${r}`,"at");return{issuer:e.issuer,authorization_endpoint:t(e.paths.authorize),token_endpoint:t(e.paths.token),...e.dynamicClientRegistration?{registration_endpoint:t(e.paths.register)}:{},revocation_endpoint:t(e.paths.revoke),scopes_supported:e.scopes,response_types_supported:["code"],response_modes_supported:["query"],grant_types_supported:["authorization_code","refresh_token"],code_challenge_methods_supported:["S256"],token_endpoint_auth_methods_supported:["none"],revocation_endpoint_auth_methods_supported:["none"],client_id_metadata_document_supported:e.clientIdMetadataDocuments,authorization_response_iss_parameter_supported:!0}}i(vr,"authorizationServerMetadata");function Ir(e){return{resource:e.resource,authorization_servers:[e.issuer],scopes_supported:e.scopes,bearer_methods_supported:["header"],...e.resourceName!==void 0?{resource_name:e.resourceName}:{}}}i(Ir,"protectedResourceMetadata");async function Re(e,t,r,n){try{return await r()}catch(o){return await e.emit({type:"unexpected_failure",where:t,errorName:o instanceof Error?o.name:"unknown"}),n()}}i(Re,"guarded");function Mr(e,t){let{options:r}=e,n=i(()=>$(500,"server_error","An unexpected condition stopped the request"),"serverError"),o=i(d=>e.errorPage(d,"server_error"),"pageError"),s=new Map,a=i((d,l)=>{s.has(d)||s.set(d,l)},"add"),c=i(d=>({methods:["GET"],cors:!0,run:i(()=>Promise.resolve(oe(200,d,{cors:!0,cacheable:!0})),"run")}),"document");for(let d of r.resourceMetadataPaths)a(d,c(Ir(r)));for(let d of r.authorizationServerMetadataPaths)a(d,c(vr(r)));return r.dynamicClientRegistration&&a(r.paths.register,{methods:["POST"],cors:!0,run:i(d=>Re(e,"register",()=>Ar(e,d),n),"run")}),a(r.paths.authorize,{methods:["GET"],cors:!1,run:i(d=>Re(e,"authorize",()=>hr(e,d),()=>o(d)),"run")}),a(r.paths.callback,{methods:["GET"],cors:!1,run:i(d=>Re(e,"callback",()=>yr(e,d),()=>o(d)),"run")}),a(r.paths.consent,{methods:["POST"],cors:!1,run:i(d=>Re(e,"consent",()=>Tr(e,d),()=>o(d)),"run")}),a(r.paths.token,{methods:["POST"],cors:!0,run:i(d=>Re(e,"token",()=>Sr(e,d,t),n),"run")}),a(r.paths.revoke,{methods:["POST"],cors:!0,run:i(d=>Re(e,"revoke",()=>Er(e,d,t),n),"run")}),s}i(Mr,"buildRoutes");var ue=class extends Error{static{i(this,"GrantInactiveError")}constructor(){super("The grant this token belonged to has been removed"),this.name="GrantInactiveError"}};var be=class extends Error{static{i(this,"UpstreamTokenError")}constructor(t,r){super(t,r),this.name="UpstreamTokenError"}};var Xe=class{static{i(this,"UpstreamTokenCache")}#e;#t=new Map;#r=new Map;#o=new Set;constructor(t){this.#e=t}forget(t){if(this.#t.delete(t),this.#o.size>=nt){let r=this.#o.values().next();r.done!==!0&&this.#o.delete(r.value)}this.#o.add(t)}get(t,r=!1){let n=this.#r.get(t);if(!r){let s=this.#e.options.now(),a=this.#t.get(t);return a!==void 0&&!P(a.expiresAt-rt,s)?Promise.resolve(a.token):n!==void 0?n.promise:this.#i(t,!1,this.#c(t))}if(n?.forced===!0)return n.promise;let o=n===void 0?this.#n(t):n.promise.then(()=>this.#n(t),()=>this.#n(t));return this.#i(t,!0,o)}#i(t,r,n){let o=n.finally(()=>{this.#r.get(t)?.promise===o&&this.#r.delete(t)});return this.#r.set(t,{promise:o,forced:r}),o}async#n(t){let{options:r}=this.#e;this.#t.delete(t);let n=await r.store.getGrant(t);if(n===void 0||P(n.expiresAt,r.now()))throw new ue;return n.sealedUpstreamAccessToken!==void 0&&await r.store.updateGrant(t,{upstreamAccessTokenExpiresAt:0}),this.#a(n)}#s(t,r){if(this.#t.size>=nt&&!this.#t.has(t)){let n=this.#t.keys().next();n.done!==!0&&this.#t.delete(n.value)}this.#t.delete(t),this.#t.set(t,r)}async#c(t){let{options:r}=this.#e,n=await r.store.getGrant(t);if(n===void 0||P(n.expiresAt,r.now()))throw new ue;let o=await this.#d(n);return o!==void 0?o:this.#a(n)}async#d(t){let{options:r}=this.#e;if(!(t.sealedUpstreamAccessToken===void 0||t.upstreamAccessTokenExpiresAt===void 0||P(t.upstreamAccessTokenExpiresAt-rt,r.now())))try{let n=await r.sealer.open(t.sealedUpstreamAccessToken,`${t.grantId}#access`);return this.#s(t.grantId,{token:n,expiresAt:t.upstreamAccessTokenExpiresAt}),n}catch{return}}async#a(t){let{options:r}=this.#e,n=t.grantId;if(t.sealedUpstreamRefreshToken===void 0)throw new be("This grant has no upstream refresh token to renew with");let o;try{let l=await r.sealer.open(t.sealedUpstreamRefreshToken,n);o=await r.identityProvider.refresh(l,Object.freeze({grantId:n,subject:t.subject}))}catch(l){throw await this.#e.emit({type:"upstream_token_refresh_failed",grantId:n,reason:l instanceof Error?l.name:"unknown"}),new be("The identity provider would not renew the upstream token",{cause:l})}let s=r.now(),a=Math.max(0,Math.min(Number.isFinite(o.expiresIn)?o.expiresIn:0,Pe)),c=s+a*1e3;if(!await r.store.updateGrant(n,{sealedUpstreamAccessToken:await r.sealer.seal(o.accessToken,`${n}#access`),upstreamAccessTokenExpiresAt:c,...o.refreshToken!==void 0?{sealedUpstreamRefreshToken:await r.sealer.seal(o.refreshToken,n)}:{}})||this.#o.has(n)){if(this.#t.delete(n),o.refreshToken!==void 0&&r.identityProvider.revoke!==void 0)try{await r.identityProvider.revoke(o.refreshToken)}catch{}throw new ue}return this.#s(n,{token:o.accessToken,expiresAt:c}),o.accessToken}};function Gn(e){let t=dr(e,{consent:Zt,error:Qt}),r=Xt(t),n=new Xe(r),o=i((a,c)=>Vt(r,a,c,d=>{n.forget(d)}),"revoke"),s=Mr(r,o);return{async handle(a){let c=s.get(new URL(a.url).pathname);if(c!==void 0)return a.method==="OPTIONS"&&c.cors?Nt([...c.methods,"OPTIONS"].join(", ")):c.methods.includes(a.method)?c.run(a):Dt(c.methods.join(", "))},authenticate(a){return Wt(r,a,(c,d)=>n.get(c,d))},unauthorized(a,c){return Le(r,c)},revokeGrant(a){return o(a,"revoke_grant_call")},renewUpstream(a){return n.get(a,!0)},async updateGrantData(a,c){let d=J(c,t.limits.grantDataBytes,"updateGrantData");return t.store.updateGrant(a,{data:d})},async revokeGrantsForSubject(a){let{store:c}=t;if(c.listGrantsBySubject===void 0)throw new _("revokeGrantsForSubject needs a store with listGrantsBySubject");let d=await c.listGrantsBySubject(a),l=0;for(let h of d)h.subject===a&&(await o(h.grantId,"revoke_subject_call"),l+=1);return l}}}i(Gn,"createMcpAuth");import{createCipheriv as $n,createDecipheriv as zn,randomBytes as Fn}from"node:crypto";var V=class extends Error{static{i(this,"SealerError")}constructor(t){super(t),this.name="SealerError"}};var jr=12,gt=16,Bn=/^[A-Za-z0-9_-]{1,32}$/,yt="v1";function Or(e){try{return Promise.resolve(e())}catch(t){return Promise.reject(t instanceof Error?t:new V("Sealing failed"))}}i(Or,"attempt");function Ur(e,t){return Buffer.from(`${yt}\0${e}\0${t}`,"utf8")}i(Ur,"additionalData");function qn(e){let t=new Map;for(let[o,s]of Object.entries(e.keys)){if(!Bn.test(o))throw new TypeError(`Key id ${JSON.stringify(o)} has characters outside A-Z a-z 0-9 _ -, or is too long`);if(!(s instanceof Uint8Array)||s.byteLength!==32)throw new TypeError(`Key ${o} is not 32 bytes long`);t.set(o,Buffer.from(s))}let r=t.get(e.currentKid);if(r===void 0)throw new TypeError("currentKid has no matching entry in keys");let n=e.currentKid;return{seal(o,s){return Or(()=>{let a=Fn(jr),c=$n("aes-256-gcm",r,a,{authTagLength:gt});c.setAAD(Ur(n,s));let d=Buffer.concat([c.update(o,"utf8"),c.final()]);return[yt,n,a.toString("base64url"),d.toString("base64url"),c.getAuthTag().toString("base64url")].join(".")})},open(o,s){return Or(()=>{let a=o.split(".");if(a.length!==5||a[0]!==yt)throw new V("Value is not in sealed format");let[,c="",d="",l="",h=""]=a,m=t.get(c);if(m===void 0)throw new V("Value was sealed with a key that is not configured");let u=Buffer.from(d,"base64url"),p=Buffer.from(h,"base64url");if(u.byteLength!==jr||p.byteLength!==gt)throw new V("Value is not in sealed format");try{let f=zn("aes-256-gcm",m,u,{authTagLength:gt});return f.setAAD(Ur(c,s)),f.setAuthTag(p),Buffer.concat([f.update(Buffer.from(l,"base64url")),f.final()]).toString("utf8")}catch{throw new V("Value was altered or belongs to a different owner")}})}}}i(qn,"createAesGcmSealer");var S=class extends Error{static{i(this,"IdentityProviderError")}code;constructor(t,r,n){super(t,n),this.name="IdentityProviderError",this.code=r}};import{createRemoteJWKSet as Kn,customFetch as Vn,jwtVerify as Wn}from"jose";var Lr=["RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512","EdDSA"],Nr=new Set(["state","nonce","code_challenge","code_challenge_method","client_id","redirect_uri","response_type","scope"]);function wt(e){return e===void 0||typeof e=="string"}i(wt,"optionalString");function Dr(e){return L(e)&&typeof e.issuer=="string"&&typeof e.authorization_endpoint=="string"&&typeof e.token_endpoint=="string"&&typeof e.jwks_uri=="string"&&wt(e.revocation_endpoint)&&(e.token_endpoint_auth_methods_supported===void 0||z(e.token_endpoint_auth_methods_supported))&&(e.authorization_response_iss_parameter_supported===void 0||typeof e.authorization_response_iss_parameter_supported=="boolean")&&(e.code_challenge_methods_supported===void 0||z(e.code_challenge_methods_supported))}i(Dr,"isDiscovery");function Hr(e){return L(e)&&typeof e.access_token=="string"&&e.access_token!==""&&wt(e.id_token)&&wt(e.refresh_token)&&(e.expires_in===void 0||typeof e.expires_in=="number"&&Number.isFinite(e.expires_in))}i(Hr,"isTokenResponse");function Ce(e,t,r){let n;try{n=new URL(t)}catch{throw new S(`Identity provider ${e} cannot be parsed as a URL`)}let o=n.protocol==="http:"&&pe.has(n.hostname);if(n.protocol!=="https:"&&!(o&&r))throw new S(`Identity provider ${e} is not an https URL`);return n}i(Ce,"checkEndpoint");function Jn(e){let t=e.allowInsecureLocalhost===!0,r=e.timeoutMs??1e4,n=e.fetch??fetch,o=[...e.algorithms??Lr];if(!e.scopes.includes("openid"))throw new TypeError("OIDC scopes need to contain openid");if(o.length===0||o.some(m=>m.toLowerCase()==="none"||m.toUpperCase().startsWith("HS")))throw new TypeError("Only asymmetric signature algorithms are allowed (no none, no HS*)");for(let m of Object.keys(e.extraAuthorizationParams??{}))if(Nr.has(m))throw new TypeError(`extraAuthorizationParams may not override ${m}`);try{Ce("issuer",e.issuer,t)}catch(m){throw new TypeError(m instanceof Error?m.message:"Identity provider issuer is not usable")}let s=i((m,u={})=>n(m,{...u,redirect:"error",signal:AbortSignal.timeout(r)}),"timedFetch"),a=null,c=i(()=>{if(a!==null)return a;let m=(async()=>{let u=de(e.issuer,"/"),p;try{p=await s(`${u}/.well-known/openid-configuration`,{headers:{Accept:"application/json"}})}catch(k){throw new S("Could not reach the identity provider's discovery document",void 0,{cause:k})}if(!p.ok)throw new S(`Discovery document request returned HTTP ${p.status}`);let f=await p.json().catch(()=>{});if(!Dr(f))throw new S("Discovery document lacks required fields");if(f.issuer!==e.issuer)throw new S("Discovery document names a different issuer than configured");if(f.code_challenge_methods_supported!==void 0&&!f.code_challenge_methods_supported.includes("S256"))throw new S("Identity provider does not offer S256 code challenges");Ce("authorization_endpoint",f.authorization_endpoint,t),Ce("token_endpoint",f.token_endpoint,t);let w=Ce("jwks_uri",f.jwks_uri,t);f.revocation_endpoint!==void 0&&Ce("revocation_endpoint",f.revocation_endpoint,t);let y=Kn(w,{timeoutDuration:r,[Vn]:(k,C)=>n(k,{...C,redirect:"error"})});return{document:f,jwks:y}})();return a=m,m.catch(()=>{a===m&&(a=null)}),m},"discover"),d=i((m,u)=>{if(u.set("client_id",e.clientId),e.clientSecret===void 0)return{};let p=m.token_endpoint_auth_methods_supported??["client_secret_basic"];if(p.includes("client_secret_basic")){let f=encodeURIComponent(e.clientId),w=encodeURIComponent(e.clientSecret);return{Authorization:`Basic ${Buffer.from(`${f}:${w}`).toString("base64")}`}}if(p.includes("client_secret_post"))return u.set("client_secret",e.clientSecret),{};throw new S("Identity provider accepts no client-secret method this library implements")},"clientAuth"),l=i(async(m,u)=>{let p={"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json",...d(m,u)},f;try{f=await s(m.token_endpoint,{method:"POST",headers:p,body:u.toString()})}catch(y){throw new S("Could not reach the identity provider's token endpoint",void 0,{cause:y})}let w=await f.json().catch(()=>{});if(!f.ok){let y=L(w)&&typeof w.error=="string"?w.error.slice(0,64):void 0;throw new S(`Token endpoint returned HTTP ${f.status}`,y)}if(!Hr(w))throw new S("Token endpoint reply lacks an access_token");return w},"postToken"),h=i(async(m,u,p,f)=>{let w;try{({payload:w}=await Wn(p,u,{issuer:m.issuer,audience:e.clientId,algorithms:o,clockTolerance:e.clockToleranceSeconds??60,requiredClaims:["sub","exp","iat"]}))}catch(k){throw new S("ID token signature or claims did not verify",void 0,{cause:k})}if(w.nonce!==f)throw new S("ID token nonce differs from the one sent");if(((Array.isArray(w.aud)?w.aud:[w.aud]).length>1||w.azp!==void 0)&&w.azp!==e.clientId)throw new S("ID token azp names some other client");return w},"verifyIdToken");return{async authorizationUrl({state:m,codeChallenge:u,redirectUri:p,nonce:f}){if(p!==e.redirectUri)throw new S("Callback URL differs from the redirectUri this provider was configured with");let{document:w}=await c(),y=new URL(w.authorization_endpoint);for(let[k,C]of Object.entries(e.extraAuthorizationParams??{}))y.searchParams.set(k,C);return y.searchParams.set("response_type","code"),y.searchParams.set("client_id",e.clientId),y.searchParams.set("redirect_uri",p),y.searchParams.set("scope",e.scopes.join(" ")),y.searchParams.set("state",m),y.searchParams.set("nonce",f),y.searchParams.set("code_challenge",u),y.searchParams.set("code_challenge_method","S256"),y.toString()},async exchangeCode({code:m,codeVerifier:u,redirectUri:p,nonce:f,issuer:w}){let{document:y,jwks:k}=await c();if(w!==void 0&&w!==y.issuer)throw new S("Authorization response iss names another issuer");if(w===void 0&&y.authorization_response_iss_parameter_supported===!0)throw new S("Authorization response omits the promised iss");let C=await l(y,new URLSearchParams({grant_type:"authorization_code",code:m,redirect_uri:p,code_verifier:u}));if(C.id_token===void 0)throw new S("Token endpoint reply has no id_token");let O=await h(y,k,C.id_token,f),T=O.sub;if(typeof T!="string"||T==="")throw new S("ID token carries no sub claim");let g=[O.name,O.email,O.preferred_username].find(G=>typeof G=="string"&&G!=="");return{subject:T,claims:{...O},accessToken:C.access_token,expiresIn:C.expires_in??300,...g!==void 0?{displayName:g}:{},...C.refresh_token!==void 0?{refreshToken:C.refresh_token}:{}}},async refresh(m){let{document:u}=await c(),p=await l(u,new URLSearchParams({grant_type:"refresh_token",refresh_token:m}));return{accessToken:p.access_token,expiresIn:p.expires_in??300,...p.refresh_token!==void 0?{refreshToken:p.refresh_token}:{}}},async revoke(m){let{document:u}=await c();if(u.revocation_endpoint===void 0)return;let p=new URLSearchParams({token:m,token_type_hint:"refresh_token"}),f={"Content-Type":"application/x-www-form-urlencoded",...d(u,p)};try{await s(u.revocation_endpoint,{method:"POST",headers:f,body:p.toString()})}catch(w){throw new S("Could not reach the identity provider's revocation endpoint",void 0,{cause:w})}}}}i(Jn,"createOidcProvider");var Ze=class{static{i(this,"ClientCollection")}#e=new Map;#t=new Map;#r=new Map;#o;#i;#n;constructor(t,r,n){this.#o=t,this.#i=r,this.#n=n}#s(t){for(this.#t.delete(t.clientId);this.#t.size>=this.#o;){let r=this.#t.keys().next();if(r.done===!0)break;this.#t.delete(r.value)}this.#t.set(t.clientId,{client:t,usedAt:this.#n()})}put(t){this.#e.delete(t.clientId),this.#t.delete(t.clientId),t.kind==="static"||(this.#r.get(t.clientId)??0)>0?this.#e.set(t.clientId,t):this.#s(t)}get(t){let r=this.#e.get(t);if(r!==void 0)return r;let n=this.#t.get(t);if(n!==void 0&&(this.#t.delete(t),!P(n.usedAt+this.#i,this.#n())))return this.#t.set(t,{client:n.client,usedAt:this.#n()}),n.client}grantAdded(t){this.#r.set(t,(this.#r.get(t)??0)+1);let r=this.#t.get(t);r!==void 0&&(this.#t.delete(t),this.#e.set(t,r.client))}grantRemoved(t){let r=(this.#r.get(t)??0)-1;if(r>0){this.#r.set(t,r);return}this.#r.delete(t);let n=this.#e.get(t);n!==void 0&&n.kind!=="static"&&(this.#e.delete(t),this.#s(n))}};var B=class{static{i(this,"Collection")}#e=new Map;#t;#r;#o;#i;constructor(t,r,n,o=()=>{}){this.#t=t,this.#o=r,this.#r=n,this.#i=o}#n(t,r){this.#e.delete(t),this.#i(r)}get(t){let r=this.#e.get(t);if(r!==void 0){if(P(this.#r(r),this.#o())){this.#n(t,r);return}return r}}set(t,r){let n=this.#e.get(t);for(n!==void 0&&this.#n(t,n);this.#e.size>=this.#t;){let o=this.#e.entries().next();if(o.done===!0)break;this.#n(o.value[0],o.value[1])}this.#e.set(t,r)}peek(t){return this.#e.get(t)}take(t,r=!1){let n=r?this.#e.get(t):this.get(t);return n!==void 0&&this.#n(t,n),n}delete(t){let r=this.#e.get(t);r!==void 0&&this.#n(t,r)}values(){let t=this.#o();return[...this.#e.values()].filter(r=>!P(this.#r(r),t))}deleteWhere(t){for(let[r,n]of this.#e)t(n)&&this.#n(r,n)}};var ne=i(e=>e.expiresAt,"expiry");function A(e){try{return Promise.resolve(e())}catch(t){return Promise.reject(t instanceof Error?t:new Error("Memory store failure"))}}i(A,"settle");function Yn(e={}){let t=e.maxEntriesPerCollection??Pt,r=je(e.now??Date.now),n=new Ze(t,(e.dynamicClientIdleSeconds??St)*1e3,r),o=new B(t,r,ne),s=new B(t,r,ne),a=new B(t,r,ne),c=new B(t,r,ne),d=new B(t,r,ne),l=new B(t,r,ne,u=>{n.grantRemoved(u.clientId)}),h=new B(t,r,ne),m=new B(t,r,ne);return{getClient(u){return A(()=>n.get(u))},putClient(u){return A(()=>{n.put(u)})},getCachedClientMetadata(u){return A(()=>o.get(u)?.client)},putCachedClientMetadata(u,p,f){return A(()=>{o.set(u,{client:p,expiresAt:f})})},putPendingAuthorization(u){return A(()=>{s.set(u.id,u)})},getPendingAuthorization(u){return A(()=>s.get(u))},consumePendingAuthorization(u){return A(()=>s.take(u))},putConsentRequest(u){return A(()=>{a.set(u.id,u)})},getConsentRequest(u){return A(()=>a.peek(u))},putConsentOutcome(u,p,f){return A(()=>{c.set(u,{sealedLocation:p,expiresAt:f})})},getConsentOutcome(u){return A(()=>c.get(u)?.sealedLocation)},listGrantsBySubject(u){return A(()=>l.values().filter(p=>p.subject===u))},consumeConsentRequest(u){return A(()=>a.take(u,!0))},putAuthorizationCode(u){return A(()=>{d.set(u.codeHash,{record:u,consumed:!1,expiresAt:u.expiresAt})})},getAuthorizationCode(u){return A(()=>{let p=d.get(u);return p===void 0?void 0:{record:p.record,consumed:p.consumed}})},consumeAuthorizationCode(u){return A(()=>{let p=d.get(u);if(p===void 0)return;let f={record:p.record,firstUse:!p.consumed};return d.set(u,{...p,consumed:!0}),f})},putGrant(u){return A(()=>{n.grantAdded(u.clientId),l.set(u.grantId,u)})},getGrant(u){return A(()=>l.get(u))},updateGrant(u,p){return A(()=>{let f=l.get(u);return f===void 0?!1:(n.grantAdded(f.clientId),l.set(u,{...f,...p}),!0)})},deleteGrant(u){return A(()=>{let p=l.take(u,!0);return h.deleteWhere(f=>f.grantId===u),m.deleteWhere(f=>f.grantId===u),d.deleteWhere(f=>f.record.grantId===u),p})},putAccessToken(u){return A(()=>{h.set(u.tokenHash,u)})},getAccessToken(u){return A(()=>h.get(u))},deleteAccessToken(u){return A(()=>{h.delete(u)})},putRefreshToken(u){return A(()=>{m.set(u.tokenHash,u)})},getRefreshToken(u){return A(()=>m.get(u))},useRefreshToken(u,p){return A(()=>{let f=m.get(u);if(f===void 0)return;if(f.usedAt!==void 0)return{record:f,previousUsedAt:f.usedAt};let w={...f,usedAt:p};return m.set(u,w),{record:w}})}}}i(Yn,"createMemoryStore");export{ue as GrantInactiveError,S as IdentityProviderError,_ as McpAuthConfigError,V as SealerError,be as UpstreamTokenError,qn as createAesGcmSealer,Gn as createMcpAuth,Yn as createMemoryStore,Jn as createOidcProvider,v as escapeHtml};
47
47
  //# sourceMappingURL=index.js.map