@gydr-ai/mcp-oauth 0.1.2 → 0.1.4

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 Fr=Object.defineProperty;var s=(e,t)=>Fr(e,"name",{value:t,configurable:!0});var _=class extends Error{static{s(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)}s(J,"jsonCopy");var Tt={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}},Ct={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-",St=1e5,Pt=2419200,rt=6e4,nt=1e4,Pe=86400,ve=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",Ie="application/x-www-form-urlencoded",Ut="application/json";var Me={"Cache-Control":"no-store",Pragma:"no-cache"},Br="max-age=63072000; includeSubDomains",Lt={"Access-Control-Allow-Origin":"*","Access-Control-Expose-Headers":"WWW-Authenticate"};function se(e,t,r={}){let n=new Headers({"Content-Type":Ut,...r.cacheable?{"Cache-Control":`public, max-age=${vt}`}:Me,...r.cors?Lt:{},...r.headers});return new Response(JSON.stringify(t),{status:e,headers:n})}s(se,"json");function $(e,t,r,n){return se(e,r===void 0?{error:t}:{error:t,error_description:r},{cors:!0,...n!==void 0?{headers:{"WWW-Authenticate":n}}:{}})}s($,"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"}})}s(Nt,"preflight");function Dt(e){return new Response(null,{status:405,headers:{Allow:e,...Me}})}s(Dt,"methodNotAllowed");function qr(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",...Me}}s(qr,"pageHeaders");function je(e,t,r={}){let n=new Headers(qr(r.formActionOrigins,r.scriptHashes));for(let o of r.setCookies??[])n.append("Set-Cookie",o);return new Response(t,{status:e,headers:n})}s(je,"html");function ie(e,t=[],r=302){let n=new Headers({Location:e,"Referrer-Policy":"no-referrer",...Me});for(let o of t)n.append("Set-Cookie",o);return new Response(null,{status:r,headers:n})}s(ie,"redirect");function Ht(e,t){return t&&e.headers.set("Strict-Transport-Security",Br),e}s(Ht,"withTransportSecurity");import{createHash as Gt,randomBytes as Kr,timingSafeEqual as Vr}from"node:crypto";var Wr=32,$t=43;function D(){return Kr(Wr).toString("base64url")}s(D,"randomToken");function E(e){return Gt("sha256").update(e,"utf8").digest("hex")}s(E,"sha256Hex");function st(e){return Gt("sha256").update(e,"ascii").digest("base64url")}s(st,"pkceChallenge");function fe(e,t){let r=Buffer.from(e,"utf8"),n=Buffer.from(t,"utf8");return r.length===n.length&&Vr(r,n)}s(fe,"constantTimeEqual");var Jr="-_",Yr="-._~";function zt(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(zt,"charsetCheck");var Ft=zt(Jr),Xr=zt(Yr);function Zr(e){return e.length>=43&&e.length<=128&&Xr(e)}s(Zr,"isWellFormedVerifier");function Bt(e){return e.length===$t&&Ft(e)}s(Bt,"isWellFormedChallenge");function Y(e){return e.length===$t&&Ft(e)}s(Y,"isOpaqueToken");function qt(e,t){return Zr(e)&&fe(st(e),t)}s(qt,"pkceMatches");function it(e){if(typeof e=="object"&&e!==null&&!Object.isFrozen(e)){Object.freeze(e);for(let t of Reflect.ownKeys(e))it(Reflect.get(e,t))}return e}s(it,"deepFreeze");function O(e){return it(structuredClone(e))}s(O,"frozenCopy");function Kt(e){return it(e)}s(Kt,"freezeDeep");async function Vt(e,t){let r=e.options.getGrantContext;if(r===void 0)return;let n=await r(O({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")}s(Vt,"grantContextFor");function L(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(L,"isRecord");function z(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")}s(z,"isStringArray");function me(e){return O({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}:{}})}s(me,"grantSummary");function S(e,t){return!(Number.isFinite(e)&&Number.isFinite(t)&&e>t)}s(S,"hasExpired");function Oe(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(Oe,"checkedClock");async function Ce(e,t,r,n=r){let{options:o}=e,i=o.now(),a=D(),d=Math.min(i+o.accessTokenTtlMs,t.expiresAt);await o.store.putAccessToken({tokenHash:E(a),grantId:t.grantId,clientId:t.clientId,scopes:r,resource:t.resource,expiresAt:d});let c={access_token:a,token_type:"Bearer",expires_in:Math.max(0,Math.floor((d-i)/1e3)),scope:r.join(" ")};if(t.allowRefresh===!1)return c;let l=D();return await o.store.putRefreshToken({tokenHash:E(l),grantId:t.grantId,clientId:t.clientId,scopes:n,resource:t.resource,expiresAt:Math.min(i+o.refreshTokenTtlMs,t.expiresAt)}),{...c,refresh_token:l}}s(Ce,"issueTokenPair");async function X(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(X,"liveGrant");async function at(e,t){let r=e.options.identityProvider;if(r.revoke!==void 0)try{await r.revoke(t)}catch{}}s(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)}s(ct,"revokeSealedUpstreamToken");async function Wt(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:me(i)}),n(t);let a=await o.store.getGrant(t),d=await o.store.deleteGrant(t),c=L(d)&&d.grantId===t?d.sealedUpstreamRefreshToken:(a??i)?.sealedUpstreamRefreshToken;c!==void 0&&typeof c!="string"||await ct(e,c,t)}s(Wt,"revokeGrantById");function Ue(e){return`"${e.replace(/[\\"]/g,"\\$&").replace(/[\r\n]/g," ")}"`}s(Ue,"quoted");function Qr(e){switch(e){case"insufficient_scope":return 403;case"invalid_request":return 400;case"invalid_token":case void 0:return 401}}s(Qr,"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 i=Qr(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(Le,"bearerChallenge");function en(){return new Response(JSON.stringify({error:"server_error"}),{status:500,headers:{"Content-Type":"application/json","Cache-Control":"no-store"}})}s(en,"serverFailure");function tn(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(tn,"bearerToken");async function Jt(e,t,r){let{options:n}=e,o=tn(t);if(o===null)return{ok:!1,response:Le(e)};let i=s(l=>({ok:!1,response:Le(e,{error:"invalid_token",description:l})}),"invalid");if(o===void 0||!Y(o))return i("The bearer value is not in this server's token format");let a=await n.store.getAccessToken(E(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 d=await X(e,a.grantId,a.clientId);if(d===void 0)return i("Access behind this token has been withdrawn");let c;try{c=await Vt(e,d)}catch{return await e.emit({type:"grant_context_failed",grantId:d.grantId}),{ok:!1,response:en()}}return{ok:!0,subject:d.subject,grantId:d.grantId,clientId:d.clientId,scopes:a.scopes,context:c,getUpstreamAccessToken:s(l=>r(d.grantId,l?.forceRefresh===!0),"getUpstreamAccessToken")}}s(Jt,"authenticateRequest");var Yt={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 Xt(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(Xt,"clientIp");var rn=/^[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="",...i]=n.trim().split(";"),a=o.trim(),d=i.map(l=>l.trim()).find(l=>l.startsWith("q=")),c=d===void 0?1:Number(d.slice(2));rn.test(a)&&Number.isFinite(c)&&c>0&&c<=1&&t.push({tag:a,q:c,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(Ne,"parseLocales");var nn=/^[A-Za-z0-9_.:-]{1,64}$/;async function ae(e){let t;try{t=await e()}catch{return{allowed:!1}}return dt(t)}s(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"&&nn.test(t)?{allowed:!1,reason:t}:{allowed:!1}}s(dt,"judge");async function he(e){return(await ae(e)).allowed}s(he,"permits");function Zt(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 he(()=>o(Xt(e,r),n));return i||await t({type:"request_throttled",scope:n}),i},errorPage(r,n,o={}){let i=Yt[n],a=e.renderErrorPage(O({status:i.status,reason:n,title:i.title,message:i.message,locales:Ne(r.headers.get("accept-language")),...o.detail!==void 0?{detail:o.detail}:{},...o.policyReason!==void 0?{policyReason:o.policyReason}:{}}));return je(i.status,a,{setCookies:o.setCookies??[]})}}}s(Zt,"createContext");var on=/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}\p{Co}\p{Cs}\p{Cn}]/u;function ce(e){return on.test(e)}s(ce,"hasHiddenCharacters");var sn={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};function v(e){return e.replace(/[&<>"']/g,t=>sn[t]??t)}s(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}s(De,"isScopeToken");function de(e,t){let r=e.length;for(;r>0&&e[r-1]===t;)r-=1;return e.slice(0,r)}s(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>`}s(ut,"document");function an(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}}s(an,"provenance");function cn(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 d=`field-${a}`,c=Object.hasOwn(t,i)?t[i]:void 0,l=Object.hasOwn(r,i)?r[i]:void 0,h=c===void 0?"":`<span class="note" id="${d}-error">${v(c)}</span>`,f=c===void 0?"":` aria-invalid="true" aria-describedby="${d}-error"`;return`<p><label for="${d}">${v(i)}</label>
24
+ <input type="text" id="${d}" name="${v(i)}" value="${v(l??"")}"${f}>
25
+ ${h}</p>`}).join(`
26
+ `)}</section>`}s(cn,"correctionFields");function Qt(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(c=>{let l=Object.hasOwn(e.scopeDescriptions,c)?e.scopeDescriptions[c]:void 0,h=l===void 0?"":` \u2014 ${v(l)}`;return`<li><code>${v(c)}</code>${h}</li>`}).join(""),i=Object.entries(e.hiddenFields).map(([c,l])=>`<input type="hidden" name="${v(c)}" value="${v(l)}">`).join(`
27
+ `),a=v(e.decisionField),d=cn(e);return ut("Connect application",`<h1>Connect <strong>${v(t)}</strong>?</h1>
28
28
  ${n}
29
- ${Vr(e)}
29
+ ${an(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)}">
37
+ <form method="post" action="${v(e.formAction)}">
38
38
  ${i}
39
- ${c}
39
+ ${d}
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>`)}s(Qt,"defaultConsentPage");function er(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>`}`)}s(er,"defaultErrorPage");function ge(e){if(e.length>ve||!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(ge,"isMetadataDocumentClientId");function Z(e,t){if(typeof e!="string")return;let r=e.trim();if(!(r.length===0||r.length>t))return ce(r)?void 0:r}s(Z,"cleanClientName");function dn(e){return e==="authorization_code"||e==="refresh_token"}s(dn,"isSupportedGrantType");function Q(e,t,r=["authorization_code"]){if(e===void 0)return[...r];if(!z(e)||!e.includes("authorization_code"))return;let n=e.filter(dn);if(!(t&&n.length!==e.length))return[...new Set(n)]}s(Q,"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))],i=o.filter(a=>t.includes(a));if(i.length!==0&&!(r&&i.length<o.length))return i}s(He,"parseClientScopes");var un=2048,ln=["code","state","iss","error","error_description","error_uri"];function ye(e){try{return new URL(e)}catch{return}}s(ye,"tryParse");function Ae(e){return e.protocol==="http:"&&pe.has(e.hostname)}s(Ae,"isLoopbackHttp");function rr(e){let t=ye(e);return t!==void 0&&Ae(t)}s(rr,"isLoopbackRedirectUri");function Ee(e,t={redirectUriLength:un}){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)&&!Ae(r)?"disallowed_scheme":ln.some(o=>r.searchParams.has(o))?"reserved_query_parameter":void 0}s(Ee,"redirectUriProblem");function lt(e,t){return Ee(e,t)===void 0}s(lt,"isAcceptableRedirectUri");function pn(e){return e>=48&&e<=57}s(pn,"isDigit");function tr(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&&pn(n.charCodeAt(o));)o+=1;n=n.slice(o)}return r.toLowerCase()+n}s(tr,"portless");function fn(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||!Ae(n)||!Ae(o)?!1:tr(e,n)===tr(t,o)}s(fn,"redirectUriMatches");function nr(e,t,r){return e.some(n=>fn(n,t,r))}s(nr,"matchesAnyRedirectUri");function Ge(e){let t=ye(e);return t===void 0?"":Ae(t)?t.hostname:t.host}s(Ge,"redirectHostOf");function or(e){return ye(e)?.origin}s(or,"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()}s($e,"buildRedirect");function sr(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)}s(sr,"resolveScopeDescriptions");function ir(e=[],t,r,n){let o=new Map;for(let i of e){let a=i.clientId,d=`clients[${JSON.stringify(a)}]`;if(a.trim()===""||a.length>255||ce(a))throw new _(`${d}: clientId must be 1 to 255 visible characters`);if(ge(a)||/^https:/i.test(a))throw new _(`${d}: clientId must not be an https URL`);if(o.has(a))throw new _(`${d}: listed twice`);if(i.redirectUris.length===0||i.redirectUris.length>r.redirectUris)throw new _(`${d}: list 1 to ${r.redirectUris} redirectUris`);for(let h of i.redirectUris){let f=Ee(h,r);if(f!==void 0)throw new _(`${d}: redirect URI refused (${f})`)}let c=i.clientName===void 0?void 0:Z(i.clientName,r.clientNameLength);if(i.clientName!==void 0&&c===void 0)throw new _(`${d}: clientName is not a valid display name`);let l=Q(i.grantTypes??["authorization_code","refresh_token"],!0);if(l===void 0)throw new _(`${d}: grantTypes must include authorization_code`);if(i.scopes?.some(h=>!t.includes(h))===!0)throw new _(`${d}: scopes must be a subset of scopes`);if(i.scopes?.length===0)throw new _(`${d}: scopes must not be empty`);o.set(a,Kt({clientId:a,redirectUris:[...new Set(i.redirectUris)],kind:"static",createdAt:n(),grantTypes:l,...i.scopes!==void 0?{scopes:[...i.scopes]}:{},...c!==void 0?{clientName:c}:{}}))}return o}s(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}s(pt,"parseServerUrl");function ft(e){return de(e,"/")}s(ft,"trimPath");function ar(e,t,r,n,o){let i=t??r;if(!Number.isInteger(i)||i<n||i>o)throw new _(`lifetimes.${e} must be an integer from ${n} to ${o}`);return i*1e3}s(ar,"seconds");function mn(e,t,r){let n=t??r;if(!Number.isInteger(n)||n<1)throw new _(`limits.${e} must be a positive integer`);return n}s(mn,"positive");function cr(e={}){let t=s(r=>mn(r,e[r],Ct[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(cr,"resolveLimits");function hn(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}s(hn,"checkPath");function dr(e,t={}){let r=s(i=>hn(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 _("paths must be distinct");return n}s(dr,"resolvePaths");var gn=/^sha256-[A-Za-z0-9+/]{43}=$/,yn=/^__Host-[A-Za-z0-9_.-]{0,40}$/;function ur(e,t){let r=e.allowInsecureLocalhost===!0,n=pt("issuer",e.issuer,r),o=ft(n.pathname),i=`${n.origin}${o}`;if(e.issuer!==i&&!(o===""&&e.issuer===`${i}/`))throw new _(`issuer must be in normalized form, for example ${i}`);let a=pt("resource",e.resource,r),d=ft(a.pathname),c=e.scopes??At;if(c.length===0||!c.every(De))throw new _("scopes must be non-empty scope tokens");let l=e.defaultScopes??c;if(l.length===0||!l.every(x=>c.includes(x)))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 f=e.lifetimes??{},u=s(x=>ar(x,f[x],Tt[x],et[x].min,et[x].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 m=Q(e.defaultGrantTypes??["authorization_code"],!0);if(m===void 0)throw new _("defaultGrantTypes may only list authorization_code and refresh_token, and must include authorization_code");let g=dr(o,e.paths),w=e.cookiePrefix??xt;if(!yn.test(w))throw new _("cookiePrefix must start with __Host- and use only letters, digits, '.', '_' and '-'");let R=cr(e.limits),T=Oe(e.now??Date.now),I=[...e.scriptHashes??[]];for(let x of I)if(!gn.test(x))throw new _("scriptHashes entries must look like sha256-<base64 of 32 bytes>");let C=e.consentReplaySeconds??It;if(!Number.isInteger(C)||C<0||C>ot)throw new _(`consentReplaySeconds must be an integer from 0 to ${ot}`);let y=Mt,H=jt,G=d===""?[y]:[`${y}${d}`,y],N=o===""?[H]:[`${H}${o}`,H],q=new Set([...G,...N,a.pathname,d===""?"/":d]);for(let[x,le]of Object.entries(g))if(q.has(le))throw new _(`paths.${x} collides with a metadata path or the resource path`);return{issuer:i,issuerOrigin:n.origin,resource:e.resource,resourceMetadataUrl:`${a.origin}${y}${d}`,resourceMetadataPaths:G,authorizationServerMetadataPaths:N,scopes:[...c],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:m,codeTtlMs:u("authorizationCode"),pendingTtlMs:u("pendingAuthorization"),clientMetadataCacheMs:u("clientMetadataCache"),clientMetadataFailureMs:u("clientMetadataFailure"),limits:R,cookiePrefix:w,scriptHashes:I,consentReplayMs:C*1e3,refreshReuseGraceMs:h*1e3,clientIdMetadataDocuments:e.clientIdMetadataDocuments??!0,dynamicClientRegistration:e.dynamicClientRegistration??!0,strictTransportSecurity:e.strictTransportSecurity!==!1,paths:g,callbackUrl:`${n.origin}${g.callback}`,trustProxy:e.trustProxy??!1,now:T,scopeDescriptions:sr(c,e.scopeDescriptions),staticClients:ir(e.clients,c,R,T),...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(ur,"resolveOptions");import{safeFetch as wn}from"@gydr-ai/safe-fetch";var j=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 _n(e,t,r,n){if(!L(t))throw new j("not_an_object");if(t.client_id!==e)throw new j("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 j("confidential_client");let i=Q(t.grant_types,!1,n.defaultGrantTypes);if(i===void 0)throw new j("grant_types_unusable");if(t.response_types!==void 0&&(!z(t.response_types)||!t.response_types.includes("code")))throw new j("response_types_unusable");let a=He(t.scope,n.scopes,!1,n.limits.scopeLength);if(a===void 0)throw new j("scope_unusable");if(!z(t.redirect_uris))throw new j("redirect_uris_absent");let d=t.redirect_uris.filter(l=>lt(l,n.limits)).slice(0,n.limits.redirectUris);if(d.length===0)throw new j("redirect_uris_unusable");let c=Z(t.client_name,n.limits.clientNameLength);return{clientId:e,redirectUris:d,kind:"metadata_document",createdAt:r,grantTypes:i,...a!==null?{scopes:a}:{},...c!==void 0?{clientName:c}:{}}}s(_n,"validateClientMetadata");function kn(e){return(t,r)=>wn(t,{method:"GET",headers:{Accept:"application/json"},redirect:"error",signal:r.signal},{timeoutMs:e.limits.clientMetadataTimeoutMs,maxResponseBytes:e.limits.clientMetadataBytes,label:"client metadata"})}s(kn,"bundledFetcher");function lr(e,t){return t.aborted?Promise.reject(new j("timeout")):new Promise((r,n)=>{let o=s(()=>{n(new j("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 j(ze(i)))})})}s(lr,"beforeAbort");async function Rn(e,t,r){let n=Number(e.headers.get("content-length"));if(Number.isFinite(n)&&n>t)throw await e.body?.cancel().catch(()=>{}),new j("too_large");if(e.body===null)return"";let o=e.body.getReader(),i=[],a=0;try{for(;;){let d=await lr(o.read(),r);if(d.done)break;let c=d.value;if(!(c instanceof Uint8Array))throw new j("not_bytes");if(a+=c.byteLength,a>t)throw new j("too_large");i.push(c)}}catch(d){throw await o.cancel().catch(()=>{}),d}return Buffer.concat(i).toString("utf8")}s(Rn,"readLimited");function ze(e){return e instanceof j?e.reason:L(e)?typeof e.code=="string"?e.code:typeof e.reason=="string"?e.reason:"unreachable":"unreachable"}s(ze,"failureReason");function bn(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(bn,"cacheControlSeconds");async function pr(e,t,r){let n=r.fetchClientMetadata??kn(r),o=AbortSignal.timeout(r.limits.clientMetadataTimeoutMs),i,a;try{let c=await lr(n(e,{signal:o}),o);if(c.status!==200)throw await c.body?.cancel().catch(()=>{}),new j(`status_${c.status}`);a=bn(c.headers.get("cache-control")),i=await Rn(c,r.limits.clientMetadataBytes,o)}catch(c){throw c instanceof j?c:new j(ze(c))}let d;try{d=JSON.parse(i)}catch{throw new j("invalid_json")}return{client:_n(e,d,t,r),maxAgeSeconds:a}}s(pr,"fetchClientMetadata");function mt(e){try{return new URL(e).host}catch{return""}}s(mt,"hostOf");function fr(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}`}s(fr,"serverIdentity");function Tn(e,t){let r=fr(e);return r!==void 0&&r===fr(t)}s(Tn,"isIssuerUrl");async function Fe(e,t){let{options:r}=e;if(t.length>ve)return;if(!ge(t)){let h=r.staticClients.get(t);if(h!==void 0)return h;let f=await r.store.getClient(t);return f?.kind==="metadata_document"?void 0:f}if(!r.clientIdMetadataDocuments)return;if(Tn(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:i,inflight:a}=e.cimd,d=i.get(t);if(d!==void 0){if(d>r.now())return;i.delete(t)}let c=a.get(t);if(c!==void 0)return c;let l=Cn(e,t).finally(()=>{a.delete(t)});return a.set(t,l),l}s(Fe,"resolveClient");async function Cn(e,t){let{options:r}=e,n=r.now(),o;try{o=await pr(t,n,r)}catch(d){An(e,t),await e.emit({type:"client_metadata_refused",host:mt(t),reason:ze(d)});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(Cn,"downloadAndRemember");function An(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(An,"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()}}s(Be,"readCookie");function qe(e,t,r){return`${e}=${t}; Path=/; Max-Age=${r}; HttpOnly; Secure; SameSite=Lax`}s(qe,"hostCookie");function Ke(e){return`${e}=; Path=/; Max-Age=0; HttpOnly; Secure; SameSite=Lax`}s(Ke,"clearHostCookie");function ee(e,t){return e+E(`binding:${t}`).slice(0,20)}s(ee,"bindingCookieName");function te(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(te,"groupParams");function b(e,t){let r=e.get(t)?.[0];return r===void 0||r===""?void 0:r}s(b,"single");function re(e,t){return t.filter(r=>(e.get(r)?.length??0)>1)}s(re,"repeatedDefined");function mr(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(mr,"splitAuthority");function we(e,t){if(t===e)return!0;let r=mr(e),n=mr(t);return r!==void 0&&n!==void 0&&r.authority===n.authority&&r.rest===n.rest}s(we,"sameResource");function hr(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}s(hr,"resolveScopes");var En=["client_id","redirect_uri","response_type","code_challenge","code_challenge_method","resource","scope","state","prompt"];async function gr(e,t){let{options:r}=e,{limits:n}=r;if(!await e.allowed(t,"authorize"))return e.errorPage(t,"rate_limited");let o=te(new URL(t.url).searchParams),i=s(async(N,q,x={})=>(await e.emit({type:"authorization_refused",reason:N,...q!==void 0?{clientId:q}:{}}),e.errorPage(t,N,x)),"refuse");if(re(o,En).length>0)return i("repeated_parameter");let a=b(o,"client_id"),d=a===void 0?void 0:await Fe(e,a);if(a===void 0||d===void 0)return i("client_unknown");let c=b(o,"redirect_uri"),[l]=d.redirectUris.length===1?d.redirectUris:[],h=c??l;if(h===void 0||!nr(d.redirectUris,h,n))return i("redirect_uri_not_registered",a);let f=b(o,"state");if(f!==void 0&&f.length>n.stateLength)return i("invalid_request",a,{detail:`The state value exceeds ${n.stateLength} characters`});if(b(o,"response_type")!=="code")return i("unsupported_response_type",a,{detail:"Only the authorization code flow is offered"});let u=b(o,"code_challenge");if(u===void 0||!Bt(u))return i("invalid_request",a,{detail:"A 43-character S256 code_challenge must accompany the request"});if(b(o,"code_challenge_method")!=="S256")return i("invalid_request",a,{detail:"The only accepted code_challenge_method is S256"});let p=b(o,"resource");if(p===void 0||!we(r.resource,p))return i("invalid_target",a,{detail:`Tokens from this server are only for ${r.resource}`});let m=d.scopes??r.scopes,g=r.defaultScopes.filter(N=>m.includes(N)),w=hr(o.get("scope")?.[0],m,g.length>0?g:m,n.scopeLength);if(w===void 0)return i("invalid_scope",a);if(b(o,"prompt")?.split(" ").includes("none"))return i("consent_required",a);let R=r.authorizeClient;if(R!==void 0){let N=await ae(()=>R({client:O(d),redirectUri:h,scopes:O(w),request:t}));if(!N.allowed)return i("access_denied",a,N.reason===void 0?{}:{policyReason:N.reason})}let T=D(),I=D(),C=D(),y=D(),H={id:T,clientId:d.clientId,clientKind:d.kind,redirectUri:h,codeChallenge:u,resource:r.resource,scopes:w,upstreamCodeVerifier:C,upstreamNonce:y,bindingHash:E(I),allowRefresh:d.grantTypes?.includes("refresh_token")??!0,expiresAt:r.now()+r.pendingTtlMs,...d.clientName!==void 0?{clientName:d.clientName}:{},...f!==void 0?{state:f}:{}};await r.store.putPendingAuthorization(H);let G=await r.identityProvider.authorizationUrl({state:T,codeChallenge:st(C),redirectUri:r.callbackUrl,nonce:y});return await e.emit({type:"authorization_started",clientId:d.clientId,scopes:w}),ie(G,[qe(ee(r.cookiePrefix,T),I,Math.ceil(r.pendingTtlMs/1e3))])}s(gr,"handleAuthorize");import{randomUUID as In}from"node:crypto";function xn(e){try{return new URL(e).host}catch{return""}}s(xn,"documentHost");function Ve(e,t,r,n,o={}){let{options:i}=e,a=i.renderConsentPage(O({clientId:r.clientId,clientKind:r.clientKind,redirectUri:r.redirectUri,redirectHost:Ge(r.redirectUri),redirectIsLoopback:rr(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:Ne(t.headers.get("accept-language")),...r.clientName!==void 0?{clientName:r.clientName}:{},...r.clientKind==="metadata_document"?{clientHost:xn(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}:{}})),d=or(r.redirectUri),c=[...o.setCookies??[]];return o.binding!==void 0&&c.push(qe(ee(i.cookiePrefix,r.id),o.binding,Math.ceil(i.pendingTtlMs/1e3))),je(o.status??200,a,{formActionOrigins:d===void 0?[]:[d],setCookies:c,scriptHashes:i.scriptHashes})}s(Ve,"consentPageResponse");var Sn=512;function Pn(e){return typeof e=="string"&&e!==""&&e.length<=Sn&&e.trim()===e&&e.normalize("NFC")===e&&!ce(e)}s(Pn,"isUsableSubject");function vn(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(vn,"readMapped");async function yr(e,t,r){let{mapSubject:n,allowSubject:o,limits:i}=e.options,a=t.claims??{},d=t.subject,c=t.displayName;if(n!==void 0){let f;try{f=vn(await n(O({subject:t.subject,claims:a,...t.displayName!==void 0?{displayName:t.displayName}:{}})))}catch{return{ok:!1}}if(f===void 0)return{ok:!1};d=f.subject,c=f.displayName}if(!Pn(d))return{ok:!1};let l=c===void 0?void 0:Z(c,i.clientNameLength),h=l===void 0?{subject:d}:{subject:d,displayName:l};if(o!==void 0){let f=await ae(()=>o(O({...h,claims:a,client:r})));if(!f.allowed)return f.reason===void 0?{ok:!1}:{ok:!1,policyReason:f.reason}}return{ok:!0,person:h}}s(yr,"resolvePerson");var Mn=["state","code","error","error_description","error_uri","iss"];async function wr(e,t){let{options:r}=e;if(!await e.allowed(t,"callback"))return e.errorPage(t,"rate_limited");let n=te(new URL(t.url).searchParams);if(re(n,Mn).length>0)return e.errorPage(t,"malformed_response");let o=b(n,"state");if(o===void 0)return e.errorPage(t,"flow_ended");let i=ee(r.cookiePrefix,o),a=Ke(i),d=await r.store.getPendingAuthorization(o);if(d===void 0||S(d.expiresAt,r.now()))return e.errorPage(t,"flow_ended");let c=Be(t,i);if(c===void 0||!fe(E(c),d.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!==d.bindingHash)return e.errorPage(t,"flow_ended");let h=b(n,"error");if(h!==void 0){let x=h==="access_denied";return await e.emit({type:"identity_provider_error",clientId:l.clientId,reason:x?"person_cancelled":"provider_reported_error"}),ie($e(l.redirectUri,{error:x?"access_denied":"server_error",error_description:x?"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 f=b(n,"code");if(f===void 0)return e.errorPage(t,"malformed_response",{setCookies:[a]});let u=b(n,"iss"),p;try{p=await r.identityProvider.exchangeCode({code:f,codeVerifier:l.upstreamCodeVerifier,redirectUri:r.callbackUrl,nonce:l.upstreamNonce,...u!==void 0?{issuer:u}:{}})}catch(x){return await e.emit({type:"identity_provider_error",clientId:l.clientId,reason:x instanceof Error?x.name:"exchange_failed"}),e.errorPage(t,"sign_in_not_confirmed",{setCookies:[a]})}let m=s(async()=>{p.refreshToken!==void 0&&await at(e,p.refreshToken)},"releaseUpstream");if(typeof p.subject!="string"||p.subject.length===0)return await m(),await e.emit({type:"identity_provider_error",clientId:l.clientId,reason:"subject_missing"}),e.errorPage(t,"sign_in_not_confirmed",{setCookies:[a]});let g={clientId:l.clientId,kind:l.clientKind,...l.clientName!==void 0?{clientName:l.clientName}:{}},w=await yr(e,p,g);if(!w.ok)return await m(),await e.emit({type:"identity_provider_error",clientId:l.clientId,reason:"subject_not_permitted"}),e.errorPage(t,"subject_not_permitted",{setCookies:[a],...w.policyReason!==void 0?{policyReason:w.policyReason}:{}});let{person:R}=w,T;if(r.getConsentDetails!==void 0)try{T=J(await r.getConsentDetails(Object.freeze({...O({subject:R.subject,client:g,scopes:[...l.scopes]}),request:t})),r.limits.consentDetailsBytes,"getConsentDetails")}catch{return await m(),e.errorPage(t,"server_error",{setCookies:[a]})}let I=r.now(),C=In(),y=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:C,clientId:l.clientId,clientKind:l.clientKind,redirectUri:l.redirectUri,codeChallenge:l.codeChallenge,resource:l.resource,scopes:l.scopes,subject:R.subject,csrfHash:E(y),bindingHash:l.bindingHash,expiresAt:I+r.pendingTtlMs,...l.allowRefresh!==void 0?{allowRefresh:l.allowRefresh}:{},...l.clientName!==void 0?{clientName:l.clientName}:{},...l.state!==void 0?{state:l.state}:{},...R.displayName!==void 0?{displayName:R.displayName}:{},...T!==void 0?{details:T}:{},...p.refreshToken!==void 0?{sealedUpstreamRefreshToken:await H.seal(p.refreshToken,C)}:{},...p.accessToken!==void 0&&G!==void 0?{sealedUpstreamAccessToken:await H.seal(p.accessToken,`${C}#access`),upstreamAccessTokenExpiresAt:I+G*1e3}:{}},q;try{q=Ve(e,t,N,y,{binding:c,setCookies:[a]})}catch(x){throw await m(),x}return await r.store.putConsentRequest(N),q}s(wr,"handleCallback");function _r(e,t){let r=t+e.grantTtlMs;return e.grantIdleMs>0?Math.min(r,t+e.grantIdleMs):r}s(_r,"initialGrantExpiry");function kr(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}s(kr,"slidGrantExpiry");var F=class extends Error{static{s(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}s(_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=[],i=0;for(;;){let a=await n.read();if(a.done)break;let d=a.value;if(!(d instanceof Uint8Array))throw new TypeError("Body is not bytes");if(i+=d.byteLength,i>t)throw await n.cancel(),new F;o.push(d)}return Buffer.concat(o).toString("utf8")}s(ke,"readBody");import{setTimeout as jn}from"node:timers/promises";var Rr=200,Tr=Object.values(K),On=50,br=200;function Un(e){let t=[];for(let[r,n]of e){let[o]=n;!Tr.includes(r)&&o!==void 0&&t.push([r,o])}return Object.fromEntries(t)}s(Un,"extraFields");function Ln(e){if(!L(e))return;let t=Object.entries(e);if(t.length===0||t.length>On)return;let r=[];for(let[n,o]of t){if(typeof o!="string"||o===""||o.length>br||n.length>br)return;r.push([n,o])}return Object.fromEntries(r)}s(Ln,"readFieldErrors");function Cr(e){return{clientId:e.clientId,kind:e.clientKind,...e.clientName!==void 0?{clientName:e.clientName}:{}}}s(Cr,"hookClient");async function Nn(e,t,r){let n=e.options.readConsentFields;if(n===void 0)return{kind:"accepted",grantData:void 0};let o;try{o=await n(O({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 i=Ln(o.fieldErrors);return i===void 0?{kind:"failed"}:{kind:"correct",fieldErrors:i}}default:return{kind:"failed"}}}s(Nn,"readFields");async function Ar(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,Ie))return e.errorPage(t,"unsupported_submission");let o;try{o=te(new URLSearchParams(await ke(t,r.limits.formBytes)))}catch(M){if(M instanceof F)return e.errorPage(t,"consent_unavailable");throw M}if(re(o,Tr).length>0)return e.errorPage(t,"consent_unavailable");let i=b(o,K.id),a=b(o,K.csrf);if(i===void 0||a===void 0)return e.errorPage(t,"consent_unavailable");let{store:d,sealer:c}=r,l=ee(r.cookiePrefix,i),h=Ke(l),f=Be(t,l),u=s(()=>e.errorPage(t,"consent_unavailable",{setCookies:[h]}),"ended"),p=f===void 0?void 0:E(`${E(f)}:${E(a)}`),m=p!==void 0&&r.consentReplayMs>0&&d.putConsentOutcome!==void 0&&d.getConsentOutcome!==void 0,g=s(async M=>{if(m)try{let U=r.now()+r.consentReplayMs;await d.putConsentOutcome?.(p,await c.seal(JSON.stringify({...M,expiresAt:U}),p),U)}catch{}},"remember"),w,R,T=0,I=s(async()=>{if(!m)return;let M=await d.getConsentOutcome?.(p);if(M===void 0)return;if(M===w&&R!==void 0)return"pending"in R&&!S(T,r.now())?R:void 0;let U;try{U=JSON.parse(await c.open(M,p))}catch{return}if(!(!L(U)||typeof U.expiresAt!="number"||S(U.expiresAt,r.now())))return w=M,T=U.expiresAt,R=U.pending===!0?{pending:!0}:typeof U.location=="string"?{location:U.location}:void 0,R},"recall"),C=s(async M=>{if(!m)return u();let U=Math.ceil(r.consentReplayMs/Rr);for(let bt=0;;bt+=1){let Se=await I();if(Se!==void 0&&"location"in Se)return ie(Se.location,[h],303);if(Se===void 0&&!M||bt>=U||t.signal.aborted)return u();await jn(Rr)}},"replay"),y=await d.getConsentRequest(i);if(y===void 0)return C(!1);let H=s(()=>ct(e,y.sealedUpstreamRefreshToken,y.grantId),"releaseUpstream"),G=s(async()=>{await d.consumeConsentRequest(i),await H()},"abandon");if(S(y.expiresAt,r.now()))return await G(),u();let N=fe(E(a),y.csrfHash),q=f!==void 0&&fe(E(f),y.bindingHash);if(!N||!q)return await e.emit({type:"flow_binding_mismatch",step:"consent"}),await G(),u();let x=b(o,K.decision)===Ot,le;if(x){let M=Un(o),U=await Nn(e,y,M);switch(U.kind){case"correct":return Ve(e,t,y,a,{status:400,fieldErrors:U.fieldErrors,submitted:{...M}});case"failed":return await G(),e.errorPage(t,"server_error",{setCookies:[h]});case"accepted":le=U.grantData;break}}if((await d.consumeConsentRequest(i))?.csrfHash!==y.csrfHash)return C(!0);await g({pending:!0});let xe=s(async M=>{let U=$e(y.redirectUri,{...M,state:y.state,iss:r.issuer});return await g({location:U}),ie(U,[h],303)},"answer");if(!x)return await H(),await e.emit({type:"consent_declined",clientId:y.clientId,subject:y.subject}),xe({error:"access_denied",error_description:"The person declined to grant access"});let _t=r.beforeGrant;if(_t!==void 0){let M=await ae(()=>_t(Object.freeze({...O({subject:y.subject,client:Cr(y),scopes:[...y.scopes],grantData:le}),request:t})));if(!M.allowed)return await H(),await e.emit({type:"authorization_refused",clientId:y.clientId,reason:M.reason??"before_grant"}),xe({error:"access_denied",error_description:"Access was not granted"})}let Qe=r.now(),W={grantId:y.grantId,clientId:y.clientId,subject:y.subject,scopes:y.scopes,resource:y.resource,createdAt:Qe,expiresAt:_r(r,Qe),redirectUri:y.redirectUri,...le!==void 0?{data:le}:{},...y.allowRefresh!==void 0?{allowRefresh:y.allowRefresh}:{},...y.clientName!==void 0?{clientName:y.clientName}:{},...y.displayName!==void 0?{displayName:y.displayName}:{},...y.sealedUpstreamRefreshToken!==void 0?{sealedUpstreamRefreshToken:y.sealedUpstreamRefreshToken}:{},...y.sealedUpstreamAccessToken!==void 0&&y.upstreamAccessTokenExpiresAt!==void 0?{sealedUpstreamAccessToken:y.sealedUpstreamAccessToken,upstreamAccessTokenExpiresAt:y.upstreamAccessTokenExpiresAt}:{}};await d.putGrant(W);let kt=D();await d.putAuthorizationCode({codeHash:E(kt),grantId:W.grantId,clientId:y.clientId,redirectUri:y.redirectUri,codeChallenge:y.codeChallenge,resource:y.resource,scopes:y.scopes,expiresAt:Qe+r.codeTtlMs});let Rt=r.afterGrant;if(Rt!==void 0)try{await Rt(Object.freeze({grant:me(W)}))}catch(M){return await d.deleteGrant(W.grantId),await H(),await e.emit({type:"unexpected_failure",where:"afterGrant",errorName:M instanceof Error?M.name:typeof M}),xe({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}),xe({code:kt})}s(Ar,"handleConsent");function ne(e){return $(400,"invalid_client_metadata",e)}s(ne,"badMetadata");function ht(e){return $(400,"invalid_redirect_uri",e)}s(ht,"badRedirect");async function Er(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 ne("Send the client metadata as application/json");let o;try{o=JSON.parse(await ke(t,n.registrationBytes))}catch(g){return ne(g instanceof F?`The metadata exceeds ${n.registrationBytes} bytes`:"The body is not a JSON object")}if(!L(o))return ne("The body is not a JSON object");let i=o.redirect_uris;if(!z(i)||i.length===0)return ht("List at least one redirect URI in redirect_uris");if(i.length>n.redirectUris)return ht(`Register at most ${n.redirectUris} redirect URIs`);for(let g of i){let w=Ee(g,n);if(w!==void 0)return ht(`Redirect URI refused (${w}). 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 ne('This server registers public clients only; token_endpoint_auth_method must be "none"');let d=Q(o.grant_types,!0,r.defaultGrantTypes);if(d===void 0)return ne('grant_types must include "authorization_code" and may add "refresh_token"; nothing else is offered');let c=o.response_types??["code"];if(!z(c)||c.length!==1||c[0]!=="code")return ne('The only response type offered is "code"');let l=He(o.scope,r.scopes,!0,n.scopeLength);if(l===void 0)return ne(`Available scopes: ${r.scopes.join(" ")}`);let h;if(o.client_name!==void 0&&(h=Z(o.client_name,n.clientNameLength),h===void 0))return ne(`client_name needs 1 to ${n.clientNameLength} visible characters`);let f=r.allowRegistration;if(f!==void 0&&!await he(()=>f({metadata:O(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)],m={clientId:`client-${D()}`,redirectUris:p,kind:"dynamic",createdAt:u,grantTypes:d,...l!==null?{scopes:l}:{},...h!==void 0?{clientName:h}:{}};return await r.store.putClient(m),await e.emit({type:"client_registered",clientId:m.clientId,redirectHosts:[...new Set(p.map(Ge))],...h!==void 0?{clientName:h}:{}}),se(201,{client_id:m.clientId,client_id_issued_at:Math.floor(u/1e3),redirect_uris:p,grant_types:d,response_types:["code"],token_endpoint_auth_method:"none",...l!==null?{scope:l.join(" ")}:{},...h!==void 0?{client_name:h}:{}},{cors:!0})}s(Er,"handleRegister");var k=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 Dn=/^[!#$%&'*+.^_`|~0-9A-Za-z-]{1,32}$/,Hn=["client_id","client_secret","client_assertion","client_assertion_type"];function Gn(e){let t=e.trim().split(" ")[0]??"";return Dn.test(t)?t:"Basic"}s(Gn,"schemeOf");async function We(e,t,r){if(!_e(e,Ie))throw new k("invalid_request","Send the parameters as an application/x-www-form-urlencoded body");let n;try{n=te(new URLSearchParams(await ke(e,t)))}catch(d){throw d instanceof F?new k("invalid_request",`The body exceeds ${t} bytes`):d}let o=re(n,[...Hn,...r]);if(o.length>0)throw new k("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 k("invalid_client",a,401,Gn(i));if(n.has("client_secret")||n.has("client_assertion"))throw new k("invalid_client",a);return{form:n,clientId:b(n,"client_id")}}s(We,"readPublicClientForm");function Je(e,t){let r=b(t,"resource");if(r!==void 0&&!we(e.options.resource,r))throw new k("invalid_target",`Tokens from this server are only for ${e.options.resource}`)}s(Je,"requireOwnResource");var $n={"Cache-Control":"no-store",Pragma:"no-cache","Access-Control-Allow-Origin":"*"},zn=["token","token_type_hint"];async function xr(e,t,r){let{store:n,limits:o}=e.options,i=s(()=>new Response(null,{status:200,headers:$n}),"done");try{if(!await e.allowed(t,"revoke"))return $(429,"temporarily_unavailable","Request rate exceeded; retry later");let{form:a,clientId:d}=await We(t,o.formBytes,zn),c=b(a,"token");if(c===void 0)throw new k("invalid_request","Missing parameter: token");if(!Y(c))return i();let l=E(c),h=s(m=>d===void 0||d===m,"callerMayAct"),f=s(async()=>{let m=await n.getRefreshToken(l);return m===void 0||!h(m.clientId)?!1:(await r(m.grantId,"revocation_request"),!0)},"asRefreshToken"),u=s(async()=>{let m=await n.getAccessToken(l);return m===void 0||!h(m.clientId)?!1:(await n.deleteAccessToken(l),!0)},"asAccessToken"),p=b(a,"token_type_hint")==="access_token"?[u,f]:[f,u];for(let m of p)if(await m())break;return i()}catch(a){if(!(a instanceof k))throw a;return $(a.status,a.error,a.description,a.challenge)}}s(xr,"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 k("temporarily_unavailable","Tokens cannot be issued right now; retry later",503)}if(!dt(o).allowed)throw new k("invalid_grant","Tokens are not issued for this grant")}s(Ye,"requireTokenIssue");async function Sr(e,t,r,n){let{options:o}=e,i=b(t,"code"),a=b(t,"code_verifier"),d=b(t,"redirect_uri"),c=[i===void 0?"code":void 0,a===void 0?"code_verifier":void 0].filter(C=>C!==void 0);if(i===void 0||a===void 0)throw new k("invalid_request",`Missing parameter: ${c.join(", ")}`);Je(e,t);let l=s(C=>new k("invalid_grant","This authorization code cannot be exchanged",400,void 0,C),"unusable");if(!Y(i))throw l("code_malformed");let h=E(i),f=await o.store.getAuthorizationCode(h);if(f===void 0)throw l("code_unknown");let u=f.record,p=b(t,"resource"),g=[["client_id",u.clientId!==r],["redirect_uri",d!==void 0&&u.redirectUri!==d],["resource",p!==void 0&&!we(u.resource,p)],["code_verifier",!qt(a,u.codeChallenge)]].find(([,C])=>C)?.[0];if(g!==void 0)throw l(`${g}_mismatch`);let w=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(f.consumed)throw await w();if(S(u.expiresAt,o.now()))throw await n(u.grantId,"authorization_code_expired"),l("code_expired");let R=await X(e,u.grantId,r);if(R===void 0)throw new k("invalid_grant","Access has been withdrawn");await Ye(e,R,"authorization_code");let T=await o.store.consumeAuthorizationCode(h);if(T===void 0)throw l("code_unknown");if(!T.firstUse)throw await w();let I=await Ce(e,R,u.scopes);return await e.emit({type:"token_issued",grantId:R.grantId,clientId:r,subject:R.subject,grantType:"authorization_code"}),I}s(Sr,"exchangeCode");async function Pr(e,t,r,n){let{options:o}=e,i=b(t,"refresh_token");if(i===void 0)throw new k("invalid_request","Missing parameter: refresh_token");Je(e,t);let a=s(()=>new k("invalid_grant","This refresh token cannot be used"),"unusable");if(!Y(i))throw a();let d=E(i),c=o.now(),l=await o.store.getRefreshToken(d);if(l===void 0||l.clientId!==r||S(l.expiresAt,c))throw a();let h=l.scopes,f=b(t,"scope");if(f!==void 0){let I=[...new Set(f.split(" ").filter(C=>C.length>0))];if(I.length===0||I.some(C=>!l.scopes.includes(C)))throw new k("invalid_scope","A refreshed token can only carry scopes already granted");h=I}let u=await X(e,l.grantId,r);if(u===void 0||u.allowRefresh===!1)throw new k("invalid_grant","Access has been withdrawn");await Ye(e,u,"refresh_token");let p=await o.store.useRefreshToken(d,c);if(p===void 0)throw a();let m=p.previousUsedAt;if(m!==void 0){if(!(o.refreshReuseGraceMs>0&&c-m<=o.refreshReuseGraceMs))throw await Ir(e,p.record.grantId,r,n),a();return qn(e,p.record,h,r,n)}let g=await X(e,p.record.grantId,r);if(g===void 0||g.allowRefresh===!1)throw new k("invalid_grant","Access has been withdrawn");let w=kr(o,g,c),R=w!==void 0&&await o.store.updateGrant(g.grantId,{expiresAt:w})?{...g,expiresAt:w}:g,T=await Ce(e,R,h,l.scopes);return await Bn(e,p.record,T,c),await e.emit({type:"token_issued",grantId:g.grantId,clientId:r,subject:g.subject,grantType:"refresh_token"}),T}s(Pr,"exchangeRefreshToken");function vr(e){return`${e.grantId}#refresh-replacement#${e.tokenHash}`}s(vr,"replacementAad");function Fn(e){let t;try{t=JSON.parse(e)}catch{return}if(!(!L(t)||typeof t.accessToken!="string"||typeof t.refreshToken!="string"||typeof t.scope!="string"||typeof t.accessExpiresAt!="number"))return{accessToken:t.accessToken,refreshToken:t.refreshToken,scope:t.scope,accessExpiresAt:t.accessExpiresAt}}s(Fn,"parseReplacement");async function Bn(e,t,r,n){let{store:o,sealer:i}=e.options;if(o.putRefreshTokenReplacement===void 0||r.refresh_token===void 0)return;let a={accessToken:r.access_token,refreshToken:r.refresh_token,scope:r.scope,accessExpiresAt:n+r.expires_in*1e3};await o.putRefreshTokenReplacement(t.tokenHash,await i.seal(JSON.stringify(a),vr(t)))}s(Bn,"keepReplacement");async function Ir(e,t,r,n){await e.emit({type:"refresh_token_replayed",grantId:t,clientId:r}),await n(t,"refresh_token_replay")}s(Ir,"endReplayedGrant");async function qn(e,t,r,n,o){let{options:i}=e,a=s(()=>new k("invalid_grant","This refresh token cannot be used"),"unusable");if(i.store.putRefreshTokenReplacement===void 0){let l=await X(e,t.grantId,n);if(l===void 0)throw new k("invalid_grant","Access has been withdrawn");let h=await Ce(e,{...l,allowRefresh:!1},r);return await e.emit({type:"token_issued",grantId:l.grantId,clientId:n,subject:l.subject,grantType:"refresh_token"}),h}if(t.sealedReplacement===void 0)throw new k("temporarily_unavailable","This refresh token is being exchanged; retry shortly",503);let d=Fn(await i.sealer.open(t.sealedReplacement,vr(t)));if(d===void 0)throw a();let c=await i.store.getRefreshToken(E(d.refreshToken));if(c?.usedAt!==void 0)throw await Ir(e,t.grantId,n,o),a();if(c===void 0)throw a();return{access_token:d.accessToken,token_type:"Bearer",expires_in:Math.max(0,Math.floor((d.accessExpiresAt-i.now())/1e3)),scope:d.scope,refresh_token:d.refreshToken}}s(qn,"answerRetry");var Kn=["grant_type","code","redirect_uri","code_verifier","refresh_token","scope","resource"];async function Mr(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,Kn);if(n=o.clientId,n===void 0)throw new k("invalid_client","Missing parameter: client_id");let i=ge(n),a=i?void 0:await Fe(e,n);if(!i&&a===void 0)throw new k("invalid_client","No client is registered under this client_id");let d=b(o.form,"grant_type");if(d==="refresh_token"&&a?.grantTypes!==void 0&&!a.grantTypes.includes("refresh_token"))throw new k("unauthorized_client","refresh_token is not among this client's registered grant_types");let c;switch(d){case"authorization_code":c=await Sr(e,o.form,n,r);break;case"refresh_token":c=await Pr(e,o.form,n,r);break;case void 0:throw new k("invalid_request","Missing parameter: grant_type");default:throw new k("unsupported_grant_type","This server only exchanges authorization codes and refresh tokens")}return se(200,c,{cors:!0})}catch(o){if(!(o instanceof k))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(Mr,"handleToken");function jr(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(jr,"authorizationServerMetadata");function Or(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(Or,"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()}}s(Re,"guarded");function Ur(e,t){let{options:r}=e,n=s(()=>$(500,"server_error","An unexpected condition stopped the request"),"serverError"),o=s(c=>e.errorPage(c,"server_error"),"pageError"),i=new Map,a=s((c,l)=>{i.has(c)||i.set(c,l)},"add"),d=s(c=>({methods:["GET"],cors:!0,run:s(()=>Promise.resolve(se(200,c,{cors:!0,cacheable:!0})),"run")}),"document");for(let c of r.resourceMetadataPaths)a(c,d(Or(r)));for(let c of r.authorizationServerMetadataPaths)a(c,d(jr(r)));return r.dynamicClientRegistration&&a(r.paths.register,{methods:["POST"],cors:!0,run:s(c=>Re(e,"register",()=>Er(e,c),n),"run")}),a(r.paths.authorize,{methods:["GET"],cors:!1,run:s(c=>Re(e,"authorize",()=>gr(e,c),()=>o(c)),"run")}),a(r.paths.callback,{methods:["GET"],cors:!1,run:s(c=>Re(e,"callback",()=>wr(e,c),()=>o(c)),"run")}),a(r.paths.consent,{methods:["POST"],cors:!1,run:s(c=>Re(e,"consent",()=>Ar(e,c),()=>o(c)),"run")}),a(r.paths.token,{methods:["POST"],cors:!0,run:s(c=>Re(e,"token",()=>Mr(e,c,t),n),"run")}),a(r.paths.revoke,{methods:["POST"],cors:!0,run:s(c=>Re(e,"revoke",()=>xr(e,c,t),n),"run")}),i}s(Ur,"buildRoutes");var ue=class extends Error{static{s(this,"GrantInactiveError")}constructor(){super("The grant this token belonged to has been removed"),this.name="GrantInactiveError"}};var be=class extends Error{static{s(this,"UpstreamTokenError")}constructor(t,r){super(t,r),this.name="UpstreamTokenError"}};var Xe=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>=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 i=this.#e.options.now(),a=this.#t.get(t);return a!==void 0&&!S(a.expiresAt-rt,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 ue;return n.sealedUpstreamAccessToken!==void 0&&await r.store.updateGrant(t,{upstreamAccessTokenExpiresAt:0}),this.#a(n)}#i(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||S(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||S(t.upstreamAccessTokenExpiresAt-rt,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 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 i=r.now(),a=Math.max(0,Math.min(Number.isFinite(o.expiresIn)?o.expiresIn:0,Pe)),d=i+a*1e3;if(!await r.store.updateGrant(n,{sealedUpstreamAccessToken:await r.sealer.seal(o.accessToken,`${n}#access`),upstreamAccessTokenExpiresAt:d,...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.#i(n,{token:o.accessToken,expiresAt:d}),o.accessToken}};function Vn(e){let t=ur(e,{consent:Qt,error:er}),r=Zt(t),n=new Xe(r),o=s((c,l)=>Wt(r,c,l,h=>{n.forget(h)}),"revoke"),i=Ur(r,o),a=s(c=>Ht(c,t.strictTransportSecurity),"secured"),d=s(async c=>{let l=i.get(new URL(c.url).pathname);if(l!==void 0)return c.method==="OPTIONS"&&l.cors?Nt([...l.methods,"OPTIONS"].join(", ")):l.methods.includes(c.method)?l.run(c):Dt(l.methods.join(", "))},"route");return{async handle(c){let l=await d(c);return l===void 0?void 0:a(l)},async authenticate(c){let l=await Jt(r,c,(h,f)=>n.get(h,f));return l.ok||a(l.response),l},unauthorized(c,l){return a(Le(r,l))},revokeGrant(c){return o(c,"revoke_grant_call")},renewUpstream(c){return n.get(c,!0)},async updateGrantData(c,l){let h=J(l,t.limits.grantDataBytes,"updateGrantData");return t.store.updateGrant(c,{data:h})},async revokeGrantsForSubject(c){let{store:l}=t;if(l.listGrantsBySubject===void 0)throw new _("revokeGrantsForSubject needs a store with listGrantsBySubject");let h=await l.listGrantsBySubject(c),f=0;for(let u of h)u.subject===c&&(await o(u.grantId,"revoke_subject_call"),f+=1);return f}}}s(Vn,"createMcpAuth");import{createCipheriv as Wn,createDecipheriv as Jn,randomBytes as Yn}from"node:crypto";var V=class extends Error{static{s(this,"SealerError")}constructor(t){super(t),this.name="SealerError"}};var Lr=12,gt=16,Xn=/^[A-Za-z0-9_-]{1,32}$/,yt="v1";function Nr(e){try{return Promise.resolve(e())}catch(t){return Promise.reject(t instanceof Error?t:new V("Sealing failed"))}}s(Nr,"attempt");function Dr(e,t){return Buffer.from(`${yt}\0${e}\0${t}`,"utf8")}s(Dr,"additionalData");function Zn(e){let t=new Map;for(let[o,i]of Object.entries(e.keys)){if(!Xn.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 Nr(()=>{let a=Yn(Lr),d=Wn("aes-256-gcm",r,a,{authTagLength:gt});d.setAAD(Dr(n,i));let c=Buffer.concat([d.update(o,"utf8"),d.final()]);return[yt,n,a.toString("base64url"),c.toString("base64url"),d.getAuthTag().toString("base64url")].join(".")})},open(o,i){return Nr(()=>{let a=o.split(".");if(a.length!==5||a[0]!==yt)throw new V("Value is not in sealed format");let[,d="",c="",l="",h=""]=a,f=t.get(d);if(f===void 0)throw new V("Value was sealed with a key that is not configured");let u=Buffer.from(c,"base64url"),p=Buffer.from(h,"base64url");if(u.byteLength!==Lr||p.byteLength!==gt)throw new V("Value is not in sealed format");try{let m=Jn("aes-256-gcm",f,u,{authTagLength:gt});return m.setAAD(Dr(d,i)),m.setAuthTag(p),Buffer.concat([m.update(Buffer.from(l,"base64url")),m.final()]).toString("utf8")}catch{throw new V("Value was altered or belongs to a different owner")}})}}}s(Zn,"createAesGcmSealer");var P=class extends Error{static{s(this,"IdentityProviderError")}code;constructor(t,r,n){super(t,n),this.name="IdentityProviderError",this.code=r}};import{createRemoteJWKSet as Qn,customFetch as eo,jwtVerify as to}from"jose";var Hr=["RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512","EdDSA"],Gr=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"}s(wt,"optionalString");function $r(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))}s($r,"isDiscovery");function zr(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))}s(zr,"isTokenResponse");function Te(e,t,r){let n;try{n=new URL(t)}catch{throw new P(`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 P(`Identity provider ${e} is not an https URL`);return n}s(Te,"checkEndpoint");function ro(e){let t=e.allowInsecureLocalhost===!0,r=e.timeoutMs??1e4,n=e.fetch??fetch,o=[...e.algorithms??Hr];if(!e.scopes.includes("openid"))throw new TypeError("OIDC scopes need to contain openid");if(o.length===0||o.some(f=>f.toLowerCase()==="none"||f.toUpperCase().startsWith("HS")))throw new TypeError("Only asymmetric signature algorithms are allowed (no none, no HS*)");for(let f of Object.keys(e.extraAuthorizationParams??{}))if(Gr.has(f))throw new TypeError(`extraAuthorizationParams may not override ${f}`);try{Te("issuer",e.issuer,t)}catch(f){throw new TypeError(f instanceof Error?f.message:"Identity provider issuer is not usable")}let i=s((f,u={})=>n(f,{...u,redirect:"error",signal:AbortSignal.timeout(r)}),"timedFetch"),a=null,d=s(()=>{if(a!==null)return a;let f=(async()=>{let u=de(e.issuer,"/"),p;try{p=await i(`${u}/.well-known/openid-configuration`,{headers:{Accept:"application/json"}})}catch(R){throw new P("Could not reach the identity provider's discovery document",void 0,{cause:R})}if(!p.ok)throw new P(`Discovery document request returned HTTP ${p.status}`);let m=await p.json().catch(()=>{});if(!$r(m))throw new P("Discovery document lacks required fields");if(m.issuer!==e.issuer)throw new P("Discovery document names a different issuer than configured");if(m.code_challenge_methods_supported!==void 0&&!m.code_challenge_methods_supported.includes("S256"))throw new P("Identity provider does not offer S256 code challenges");Te("authorization_endpoint",m.authorization_endpoint,t),Te("token_endpoint",m.token_endpoint,t);let g=Te("jwks_uri",m.jwks_uri,t);m.revocation_endpoint!==void 0&&Te("revocation_endpoint",m.revocation_endpoint,t);let w=Qn(g,{timeoutDuration:r,[eo]:(R,T)=>n(R,{...T,redirect:"error"})});return{document:m,jwks:w}})();return a=f,f.catch(()=>{a===f&&(a=null)}),f},"discover"),c=s((f,u)=>{if(u.set("client_id",e.clientId),e.clientSecret===void 0)return{};let p=f.token_endpoint_auth_methods_supported??["client_secret_basic"];if(p.includes("client_secret_basic")){let m=encodeURIComponent(e.clientId),g=encodeURIComponent(e.clientSecret);return{Authorization:`Basic ${Buffer.from(`${m}:${g}`).toString("base64")}`}}if(p.includes("client_secret_post"))return u.set("client_secret",e.clientSecret),{};throw new P("Identity provider accepts no client-secret method this library implements")},"clientAuth"),l=s(async(f,u)=>{let p={"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json",...c(f,u)},m;try{m=await i(f.token_endpoint,{method:"POST",headers:p,body:u.toString()})}catch(w){throw new P("Could not reach the identity provider's token endpoint",void 0,{cause:w})}let g=await m.json().catch(()=>{});if(!m.ok){let w=L(g)&&typeof g.error=="string"?g.error.slice(0,64):void 0;throw new P(`Token endpoint returned HTTP ${m.status}`,w)}if(!zr(g))throw new P("Token endpoint reply lacks an access_token");return g},"postToken"),h=s(async(f,u,p,m)=>{let g;try{({payload:g}=await to(p,u,{issuer:f.issuer,audience:e.clientId,algorithms:o,clockTolerance:e.clockToleranceSeconds??60,requiredClaims:["sub","exp","iat"]}))}catch(R){throw new P("ID token signature or claims did not verify",void 0,{cause:R})}if(g.nonce!==m)throw new P("ID token nonce differs from the one sent");if(((Array.isArray(g.aud)?g.aud:[g.aud]).length>1||g.azp!==void 0)&&g.azp!==e.clientId)throw new P("ID token azp names some other client");return g},"verifyIdToken");return{async authorizationUrl({state:f,codeChallenge:u,redirectUri:p,nonce:m}){if(p!==e.redirectUri)throw new P("Callback URL differs from the redirectUri this provider was configured with");let{document:g}=await d(),w=new URL(g.authorization_endpoint);for(let[R,T]of Object.entries(e.extraAuthorizationParams??{}))w.searchParams.set(R,T);return w.searchParams.set("response_type","code"),w.searchParams.set("client_id",e.clientId),w.searchParams.set("redirect_uri",p),w.searchParams.set("scope",e.scopes.join(" ")),w.searchParams.set("state",f),w.searchParams.set("nonce",m),w.searchParams.set("code_challenge",u),w.searchParams.set("code_challenge_method","S256"),w.toString()},async exchangeCode({code:f,codeVerifier:u,redirectUri:p,nonce:m,issuer:g}){let{document:w,jwks:R}=await d();if(g!==void 0&&g!==w.issuer)throw new P("Authorization response iss names another issuer");if(g===void 0&&w.authorization_response_iss_parameter_supported===!0)throw new P("Authorization response omits the promised iss");let T=await l(w,new URLSearchParams({grant_type:"authorization_code",code:f,redirect_uri:p,code_verifier:u}));if(T.id_token===void 0)throw new P("Token endpoint reply has no id_token");let I=await h(w,R,T.id_token,m),C=I.sub;if(typeof C!="string"||C==="")throw new P("ID token carries no sub claim");let y=[I.name,I.email,I.preferred_username].find(G=>typeof G=="string"&&G!=="");return{subject:C,claims:{...I},accessToken:T.access_token,expiresIn:T.expires_in??300,...y!==void 0?{displayName:y}:{},...T.refresh_token!==void 0?{refreshToken:T.refresh_token}:{}}},async refresh(f){let{document:u}=await d(),p=await l(u,new URLSearchParams({grant_type:"refresh_token",refresh_token:f}));return{accessToken:p.access_token,expiresIn:p.expires_in??300,...p.refresh_token!==void 0?{refreshToken:p.refresh_token}:{}}},async revoke(f){let{document:u}=await d();if(u.revocation_endpoint===void 0)return;let p=new URLSearchParams({token:f,token_type_hint:"refresh_token"}),m={"Content-Type":"application/x-www-form-urlencoded",...c(u,p)};try{await i(u.revocation_endpoint,{method:"POST",headers:m,body:p.toString()})}catch(g){throw new P("Could not reach the identity provider's revocation endpoint",void 0,{cause:g})}}}}s(ro,"createOidcProvider");var Ze=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 oe=s(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"))}}s(A,"settle");function no(e={}){let t=e.maxEntriesPerCollection??St,r=Oe(e.now??Date.now),n=new Ze(t,(e.dynamicClientIdleSeconds??Pt)*1e3,r),o=new B(t,r,oe),i=new B(t,r,oe),a=new B(t,r,oe),d=new B(t,r,oe),c=new B(t,r,oe),l=new B(t,r,oe,u=>{n.grantRemoved(u.clientId)}),h=new B(t,r,oe),f=new B(t,r,oe);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,m){return A(()=>{o.set(u,{client:p,expiresAt:m})})},putPendingAuthorization(u){return A(()=>{i.set(u.id,u)})},getPendingAuthorization(u){return A(()=>i.get(u))},consumePendingAuthorization(u){return A(()=>i.take(u))},putConsentRequest(u){return A(()=>{a.set(u.id,u)})},getConsentRequest(u){return A(()=>a.peek(u))},putConsentOutcome(u,p,m){return A(()=>{d.set(u,{sealedLocation:p,expiresAt:m})})},getConsentOutcome(u){return A(()=>d.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(()=>{c.set(u.codeHash,{record:u,consumed:!1,expiresAt:u.expiresAt})})},getAuthorizationCode(u){return A(()=>{let p=c.get(u);return p===void 0?void 0:{record:p.record,consumed:p.consumed}})},consumeAuthorizationCode(u){return A(()=>{let p=c.get(u);if(p===void 0)return;let m={record:p.record,firstUse:!p.consumed};return c.set(u,{...p,consumed:!0}),m})},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 m=l.get(u);return m===void 0?!1:(n.grantAdded(m.clientId),l.set(u,{...m,...p}),!0)})},deleteGrant(u){return A(()=>{let p=l.take(u,!0);return h.deleteWhere(m=>m.grantId===u),f.deleteWhere(m=>m.grantId===u),c.deleteWhere(m=>m.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(()=>{f.set(u.tokenHash,u)})},getRefreshToken(u){return A(()=>f.get(u))},useRefreshToken(u,p){return A(()=>{let m=f.get(u);if(m===void 0)return;if(m.usedAt!==void 0)return{record:m,previousUsedAt:m.usedAt};let g={...m,usedAt:p};return f.set(u,g),{record:g}})},putRefreshTokenReplacement(u,p){return A(()=>{let m=f.get(u);m!==void 0&&f.set(u,{...m,sealedReplacement:p})})}}}s(no,"createMemoryStore");export{ue as GrantInactiveError,P as IdentityProviderError,_ as McpAuthConfigError,V as SealerError,be as UpstreamTokenError,Zn as createAesGcmSealer,Vn as createMcpAuth,no as createMemoryStore,ro as createOidcProvider,v as escapeHtml};
47
47
  //# sourceMappingURL=index.js.map