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