"use strict";(()=>{var a={};a.id=19019,a.ids=[19019],a.modules={8422:(a,b,c)=>{c.r(b),c.d(b,{handler:()=>Q,patchFetch:()=>P,routeModule:()=>L,serverHooks:()=>O,workAsyncStorage:()=>M,workUnitAsyncStorage:()=>N});var d={};c.r(d),c.d(d,{GET:()=>K,dynamic:()=>D,runtime:()=>E});var e=c(940527),f=c(41752),g=c(633335),h=c(573615),i=c(301769),j=c(200261),k=c(405563),l=c(439285),m=c(443399),n=c(295860),o=c(161730),p=c(728392),q=c(976618),r=c(406527),s=c(986439),t=c(975973),u=c(973024),v=c(176760),w=c(693349),x=c(969172),y=c(783254),z=c(609644),A=c(701821),B=c(837311),C=c(43182);let D="force-dynamic",E="nodejs";function F(a){let b,c=(0,v.join)((0,w.We)(),".mcp-secrets.json");if(!(0,u.existsSync)(c))return null;try{b=JSON.parse((0,u.readFileSync)(c,"utf-8"))}catch{return null}for(let[c,d]of Object.entries(b))if(d&&"string"==typeof d.oauthState&&d.oauthState===a)return c;return null}function G(a){return a.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function H(a){return JSON.stringify(a).replace(/</g,"\\u003c")}function I(a,b){let c="success"===a.kind?{source:"denchclaw.mcp.connect",type:"mcp-connected",serverKey:a.serverKey}:{source:"denchclaw.mcp.connect",type:"mcp-connect-failed",serverKey:a.serverKey,reason:a.reason,description:a.description},d="success"===a.kind?`Connected ${G(a.serverKey)}`:"Connection failed",e="success"===a.kind?"You can close this window.":G(a.description),f="success"===a.kind?"#10b981":"#ef4444";return new Response(`<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>${d}</title>
  <style>
    body {
      margin: 0;
      font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif;
      background: #0b0d12;
      color: #e7e9ee;
      display: flex;
      align-items: center;
      justify-content: center;
      min-height: 100vh;
    }
    .card {
      max-width: 360px;
      padding: 32px;
      border-radius: 16px;
      background: #1a1d24;
      border: 1px solid #2a2e38;
      text-align: center;
    }
    .card h1 {
      margin: 0 0 8px;
      font-size: 18px;
      color: ${f};
    }
    .card p {
      margin: 0;
      font-size: 13px;
      line-height: 1.6;
      color: #9aa1ad;
    }
  </style>
</head>
<body>
  <div class="card">
    <h1>${d}</h1>
    <p>${e}</p>
  </div>
  <script>
    (function () {
      var msg = ${H(c)};
      try {
        if (window.opener) {
          window.opener.postMessage(msg, ${H(b)});
        }
      } catch (err) {
        // ignore — opener might be cross-origin in unusual setups
      }
      setTimeout(function () { window.close(); }, 800);
    }());
  </script>
</body>
</html>`,{status:200,headers:{"content-type":"text/html; charset=utf-8","cache-control":"no-store"}})}async function J(a,b,c){(0,x.ZO)(a,`${c.tokenType} ${c.accessToken}`),(0,A.aF)(a,{refreshToken:c.refreshToken??b.refreshToken,tokenExpiresAt:(0,z.sl)(c.expiresIn),scope:c.scope??b.scope}),(0,A.A_)(a)}async function K(a){let b,c,d=(0,B.F)(a),e=new URL(a.url),f=e.searchParams.get("code"),g=e.searchParams.get("state"),h=e.searchParams.get("error"),i=e.searchParams.get("error_description");if(h){let a=g?F(g):null;return a&&((0,x.MF)(a,{state:"needs_auth",detail:i??h}),(0,A.A_)(a),(0,C.Hk)("mcp_connect_failed",{key:a,reason:h})),I({kind:"error",serverKey:a,reason:h,description:i??h},d)}if(!f||!g)return I({kind:"error",serverKey:null,reason:"missing_code_or_state",description:"The authorization server did not return a code and state."},d);let j=F(g);if(!j)return I({kind:"error",serverKey:null,reason:"unknown_state",description:"Unknown state value. The Connect flow may have timed out — try again."},d);let k=(0,A.wG)(j);if(!k||!k.codeVerifier||!k.redirectUri)return I({kind:"error",serverKey:j,reason:"missing_pkce",description:"Could not find the PKCE verifier saved at /connect/start time."},d);try{b=await (0,z.Ge)(k.asMetadataUrl)}catch(c){let a=c instanceof z.i_?c.reason:"discovery_failed",b=c instanceof Error?c.message:"Discovery failed.";return(0,x.MF)(j,{state:"needs_auth",detail:b}),(0,C.Hk)("mcp_connect_failed",{key:j,reason:a}),I({kind:"error",serverKey:j,reason:a,description:b},d)}let l={clientId:k.clientId,clientSecret:k.clientSecret,registrationAccessToken:null,registrationClientUri:null};try{c=await (0,z.J6)({asMetadata:b.authServer,client:l,code:f,codeVerifier:k.codeVerifier,redirectUri:k.redirectUri,resource:b.resource.resource})}catch(c){let a=c instanceof z.i_?c.reason:"token_exchange_failed",b=c instanceof Error?c.message:"Token exchange failed.";return(0,x.MF)(j,{state:"needs_auth",detail:b}),(0,A.A_)(j),(0,C.Hk)("mcp_connect_failed",{key:j,reason:a}),I({kind:"error",serverKey:j,reason:a,description:b},d)}await J(j,k,c);let m=(0,x.CS)(j);if(m){let a=await (0,y.w)({url:m.url,headers:m.headers});(0,x.MF)(j,{state:a.status,toolCount:a.toolCount,detail:a.detail,checkedAt:a.checkedAt})}return(0,C.Hk)("mcp_connect_completed",{key:j}),I({kind:"success",serverKey:j},d)}let L=new e.AppRouteRouteModule({definition:{kind:f.RouteKind.APP_ROUTE,page:"/api/settings/mcp/connect/callback/route",pathname:"/api/settings/mcp/connect/callback",filename:"route",bundlePath:"app/api/settings/mcp/connect/callback/route"},distDir:".next",relativeProjectDir:"",resolvedPagePath:"/home/runner/work/DenchClaw/DenchClaw/apps/web/app/api/settings/mcp/connect/callback/route.ts",nextConfigOutput:"standalone",userland:d}),{workAsyncStorage:M,workUnitAsyncStorage:N,serverHooks:O}=L;function P(){return(0,g.patchFetch)({workAsyncStorage:M,workUnitAsyncStorage:N})}async function Q(a,b,c){var d;let e="/api/settings/mcp/connect/callback/route";"/index"===e&&(e="/");let g=await L.prepare(a,b,{srcPage:e,multiZoneDraftMode:!1});if(!g)return b.statusCode=400,b.end("Bad Request"),null==c.waitUntil||c.waitUntil.call(c,Promise.resolve()),null;let{buildId:u,params:v,nextConfig:w,isDraftMode:x,prerenderManifest:y,routerServerContext:z,isOnDemandRevalidate:A,revalidateOnlyGenerated:B,resolvedPathname:C}=g,D=(0,j.normalizeAppPath)(e),E=!!(y.dynamicRoutes[D]||y.routes[C]);if(E&&!x){let a=!!y.routes[C],b=y.dynamicRoutes[D];if(b&&!1===b.fallback&&!a)throw new s.NoFallbackError}let F=null;!E||L.isDev||x||(F="/index"===(F=C)?"/":F);let G=!0===L.isDev||!E,H=E&&!G,I=a.method||"GET",J=(0,i.getTracer)(),K=J.getActiveScopeSpan(),M={params:v,prerenderManifest:y,renderOpts:{experimental:{cacheComponents:!!w.experimental.cacheComponents,authInterrupts:!!w.experimental.authInterrupts},supportsDynamicResponse:G,incrementalCache:(0,h.getRequestMeta)(a,"incrementalCache"),cacheLifeProfiles:null==(d=w.experimental)?void 0:d.cacheLife,isRevalidate:H,waitUntil:c.waitUntil,onClose:a=>{b.on("close",a)},onAfterTaskError:void 0,onInstrumentationRequestError:(b,c,d)=>L.onRequestError(a,b,d,z)},sharedContext:{buildId:u}},N=new k.NodeNextRequest(a),O=new k.NodeNextResponse(b),P=l.NextRequestAdapter.fromNodeNextRequest(N,(0,l.signalFromNodeResponse)(b));try{let d=async c=>L.handle(P,M).finally(()=>{if(!c)return;c.setAttributes({"http.status_code":b.statusCode,"next.rsc":!1});let d=J.getRootSpanAttributes();if(!d)return;if(d.get("next.span_type")!==m.BaseServerSpan.handleRequest)return void console.warn(`Unexpected root span type '${d.get("next.span_type")}'. Please report this Next.js issue https://github.com/vercel/next.js`);let e=d.get("next.route");if(e){let a=`${I} ${e}`;c.setAttributes({"next.route":e,"http.route":e,"next.span_name":a}),c.updateName(a)}else c.updateName(`${I} ${a.url}`)}),g=async g=>{var i,j;let k=async({previousCacheEntry:f})=>{try{if(!(0,h.getRequestMeta)(a,"minimalMode")&&A&&B&&!f)return b.statusCode=404,b.setHeader("x-nextjs-cache","REVALIDATED"),b.end("This page could not be found"),null;let e=await d(g);a.fetchMetrics=M.renderOpts.fetchMetrics;let i=M.renderOpts.pendingWaitUntil;i&&c.waitUntil&&(c.waitUntil(i),i=void 0);let j=M.renderOpts.collectedTags;if(!E)return await (0,o.I)(N,O,e,M.renderOpts.pendingWaitUntil),null;{let a=await e.blob(),b=(0,p.toNodeOutgoingHttpHeaders)(e.headers);j&&(b[r.NEXT_CACHE_TAGS_HEADER]=j),!b["content-type"]&&a.type&&(b["content-type"]=a.type);let c=void 0!==M.renderOpts.collectedRevalidate&&!(M.renderOpts.collectedRevalidate>=r.INFINITE_CACHE)&&M.renderOpts.collectedRevalidate,d=void 0===M.renderOpts.collectedExpire||M.renderOpts.collectedExpire>=r.INFINITE_CACHE?void 0:M.renderOpts.collectedExpire;return{value:{kind:t.CachedRouteKind.APP_ROUTE,status:e.status,body:Buffer.from(await a.arrayBuffer()),headers:b},cacheControl:{revalidate:c,expire:d}}}}catch(b){throw(null==f?void 0:f.isStale)&&await L.onRequestError(a,b,{routerKind:"App Router",routePath:e,routeType:"route",revalidateReason:(0,n.c)({isRevalidate:H,isOnDemandRevalidate:A})},z),b}},l=await L.handleResponse({req:a,nextConfig:w,cacheKey:F,routeKind:f.RouteKind.APP_ROUTE,isFallback:!1,prerenderManifest:y,isRoutePPREnabled:!1,isOnDemandRevalidate:A,revalidateOnlyGenerated:B,responseGenerator:k,waitUntil:c.waitUntil});if(!E)return null;if((null==l||null==(i=l.value)?void 0:i.kind)!==t.CachedRouteKind.APP_ROUTE)throw Object.defineProperty(Error(`Invariant: app-route received invalid cache entry ${null==l||null==(j=l.value)?void 0:j.kind}`),"__NEXT_ERROR_CODE",{value:"E701",enumerable:!1,configurable:!0});(0,h.getRequestMeta)(a,"minimalMode")||b.setHeader("x-nextjs-cache",A?"REVALIDATED":l.isMiss?"MISS":l.isStale?"STALE":"HIT"),x&&b.setHeader("Cache-Control","private, no-cache, no-store, max-age=0, must-revalidate");let m=(0,p.fromNodeOutgoingHttpHeaders)(l.value.headers);return(0,h.getRequestMeta)(a,"minimalMode")&&E||m.delete(r.NEXT_CACHE_TAGS_HEADER),!l.cacheControl||b.getHeader("Cache-Control")||m.get("Cache-Control")||m.set("Cache-Control",(0,q.getCacheControlHeader)(l.cacheControl)),await (0,o.I)(N,O,new Response(l.value.body,{headers:m,status:l.value.status||200})),null};K?await g(K):await J.withPropagatedContext(a.headers,()=>J.trace(m.BaseServerSpan.handleRequest,{spanName:`${I} ${a.url}`,kind:i.SpanKind.SERVER,attributes:{"http.method":I,"http.target":a.url}},g))}catch(b){if(b instanceof s.NoFallbackError||await L.onRequestError(a,b,{routerKind:"App Router",routePath:D,routeType:"route",revalidateReason:(0,n.c)({isRevalidate:H,isOnDemandRevalidate:A})}),E)throw b;return await (0,o.I)(N,O,new Response(null,{status:500})),null}}},16698:a=>{a.exports=require("node:async_hooks")},51455:a=>{a.exports=require("node:fs/promises")},176760:a=>{a.exports=require("node:path")},200261:a=>{a.exports=require("next/dist/shared/lib/router/utils/app-paths")},257975:a=>{a.exports=require("node:util")},333873:a=>{a.exports=require("path")},380481:a=>{a.exports=require("node:readline")},529294:a=>{a.exports=require("next/dist/server/app-render/work-async-storage.external.js")},609644:(a,b,c)=>{c.d(b,{i_:()=>i,Zw:()=>p,sl:()=>u,Ge:()=>k,J6:()=>s,J1:()=>t,UV:()=>n});let d=require("node:buffer");var e=c(977598);function f(a){return a&&"object"==typeof a&&!Array.isArray(a)?a:void 0}function g(a){return"string"==typeof a&&a.trim().length>0?a.trim():void 0}function h(a){if(!Array.isArray(a))return[];let b=[];for(let c of a){let a=g(c);a&&b.push(a)}return b}class i extends Error{constructor(a,b){super(b??a),this.name="McpOAuthError",this.reason=a}}async function j(a,b,c,d){let e;try{e=await c(a,b)}catch(b){throw new i("network_error",`${d} request to ${a} failed: ${b instanceof Error?b.message:"unknown error"}`)}if(!e.ok){let b=await e.text().catch(()=>"");throw new i("http_error",`${d} request to ${a} returned HTTP ${e.status}${b?`: ${b.slice(0,300)}`:""}`)}try{return await e.json()}catch(b){throw new i("invalid_json",`${d} response from ${a} was not valid JSON: ${b instanceof Error?b.message:"unknown error"}`)}}async function k(a,b){let c=b?.fetcher??fetch,d=f(await j(a,{method:"GET",headers:{accept:"application/json"}},c,"Protected resource metadata"));if(!d)throw new i("invalid_resource_metadata",`Resource metadata at ${a} was not a JSON object.`);let e=h(d.authorization_servers);if(0===e.length)throw new i("no_authorization_servers",`Resource metadata at ${a} did not list any authorization_servers.`);let k={resource:g(d.resource)??null,authorizationServers:e,scopesSupported:h(d.scopes_supported),bearerMethodsSupported:h(d.bearer_methods_supported)},m=null;for(let a of e)try{let b=await l(a,c);return{resource:k,authServer:b}}catch(a){m=a instanceof i?a:new i("unknown_error",a instanceof Error?a.message:String(a))}throw m??new i("no_valid_authorization_server","Could not load metadata for any advertised authorization server.")}async function l(a,b){let c=function(a){let b=a.endsWith("/")?a.slice(0,-1):a,c=m(b,"oauth-authorization-server"),d=m(b,"openid-configuration");return[c,`${b}/.well-known/oauth-authorization-server`,d,`${b}/.well-known/openid-configuration`].filter((a,b,c)=>!!a&&c.indexOf(a)===b)}(a),d=null;for(let e of c)try{let c=await j(e,{method:"GET",headers:{accept:"application/json"}},b,"Authorization server metadata"),k=f(c);if(!k){d=new i("invalid_as_metadata",`Authorization server metadata at ${e} was not a JSON object.`);continue}let l=g(k.authorization_endpoint),m=g(k.token_endpoint);if(!l||!m){d=new i("incomplete_as_metadata",`Authorization server metadata at ${e} is missing authorization_endpoint or token_endpoint.`);continue}return{issuer:g(k.issuer)??a,authorizationEndpoint:l,tokenEndpoint:m,registrationEndpoint:g(k.registration_endpoint)??null,scopesSupported:h(k.scopes_supported),responseTypesSupported:h(k.response_types_supported),grantTypesSupported:h(k.grant_types_supported),codeChallengeMethodsSupported:h(k.code_challenge_methods_supported),tokenEndpointAuthMethodsSupported:h(k.token_endpoint_auth_methods_supported)}}catch(a){d=a instanceof i?a:new i("unknown_error",a instanceof Error?a.message:String(a))}throw d??new i("no_as_metadata",`Could not load authorization server metadata for issuer ${a}.`)}function m(a,b){try{let c=new URL(a),d="/"===c.pathname?"":c.pathname.replace(/\/$/u,"");return c.pathname=`/.well-known/${b}${d}`,c.search="",c.hash="",c.toString()}catch{return null}}async function n(a){let b,c,d=a.fetcher??fetch,e=a.asMetadata.registrationEndpoint;if(!e)throw new i("no_registration_endpoint",`Authorization server ${a.asMetadata.issuer} does not advertise a registration_endpoint.`);let h={redirect_uris:[a.redirectUri],token_endpoint_auth_method:a.asMetadata.tokenEndpointAuthMethodsSupported.includes("none")?"none":a.asMetadata.tokenEndpointAuthMethodsSupported[0]??"client_secret_post",grant_types:["authorization_code","refresh_token"],response_types:["code"],client_name:a.clientName,application_type:"web"};a.scope&&(h.scope=a.scope);try{b=await d(e,{method:"POST",headers:{"content-type":"application/json",accept:"application/json"},body:JSON.stringify(h)})}catch(a){throw new i("registration_network_error",`DCR request to ${e} failed: ${a instanceof Error?a.message:"unknown error"}`)}if(!b.ok){let a=await b.text().catch(()=>"");throw new i("registration_failed",`DCR request to ${e} returned HTTP ${b.status}${a?`: ${a.slice(0,300)}`:""}`)}try{c=await b.json()}catch(a){throw new i("registration_invalid_json",`DCR response was not valid JSON: ${a instanceof Error?a.message:"unknown error"}`)}let j=f(c),k=g(j?.client_id);if(!k)throw new i("registration_missing_client_id","DCR response did not include a client_id.");return{clientId:k,clientSecret:g(j?.client_secret)??null,registrationAccessToken:g(j?.registration_access_token)??null,registrationClientUri:g(j?.registration_client_uri)??null}}function o(a){return a.toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function p(a){let b=a.codeVerifier??o((0,e.randomBytes)(32)),c=o((0,e.createHash)("sha256").update(b).digest()),d=a.state??o((0,e.randomBytes)(24)),f=new URL(a.asMetadata.authorizationEndpoint);return f.searchParams.set("response_type","code"),f.searchParams.set("client_id",a.client.clientId),f.searchParams.set("redirect_uri",a.redirectUri),f.searchParams.set("state",d),f.searchParams.set("code_challenge",c),f.searchParams.set("code_challenge_method","S256"),a.scope&&f.searchParams.set("scope",a.scope),a.resource&&f.searchParams.set("resource",a.resource),{authorizationUrl:f.toString(),state:d,codeVerifier:b,redirectUri:a.redirectUri,scope:a.scope??null}}async function q(a){let b,c,e=new URLSearchParams(a.formBody),h={"content-type":"application/x-www-form-urlencoded",accept:"application/json"};if("client_secret_basic"===a.authMethod&&a.client.clientSecret){let b=d.Buffer.from(`${a.client.clientId}:${a.client.clientSecret}`).toString("base64");h.authorization=`Basic ${b}`}else e.set("client_id",a.client.clientId),a.client.clientSecret&&e.set("client_secret",a.client.clientSecret);try{b=await a.fetcher(a.endpoint,{method:"POST",headers:h,body:e})}catch(b){throw new i("token_network_error",`${a.context} request to ${a.endpoint} failed: ${b instanceof Error?b.message:"unknown error"}`)}if(!b.ok){let c=await b.text().catch(()=>"");throw new i("token_request_failed",`${a.context} request to ${a.endpoint} returned HTTP ${b.status}${c?`: ${c.slice(0,300)}`:""}`)}try{c=await b.json()}catch(b){throw new i("token_invalid_json",`${a.context} response was not valid JSON: ${b instanceof Error?b.message:"unknown error"}`)}let j=f(c);if(!j)throw new i("token_invalid_payload",`${a.context} response was not a JSON object.`);return function(a,b){let c=g(a.access_token);if(!c)throw new i("missing_access_token",`${b} response did not include an access_token.`);let d=g(a.token_type)??"Bearer",e=a.expires_in,f="number"==typeof e&&Number.isFinite(e)?e:null;return{accessToken:c,tokenType:d,refreshToken:g(a.refresh_token)??null,expiresIn:f,scope:g(a.scope)??null}}(j,a.context)}function r(a,b){let c=a.tokenEndpointAuthMethodsSupported;return b?c.includes("client_secret_basic")?"client_secret_basic":c.includes("client_secret_post")?"client_secret_post":c[0]??"client_secret_basic":0===c.length||c.includes("none")?"none":c.includes("client_secret_post")?"client_secret_post":c[0]}async function s(a){let b=a.fetcher??fetch,c=new URLSearchParams;return c.set("grant_type","authorization_code"),c.set("code",a.code),c.set("redirect_uri",a.redirectUri),c.set("code_verifier",a.codeVerifier),a.resource&&c.set("resource",a.resource),q({endpoint:a.asMetadata.tokenEndpoint,formBody:c,client:a.client,authMethod:r(a.asMetadata,!!a.client.clientSecret),fetcher:b,context:"Token exchange"})}async function t(a){let b=a.fetcher??fetch,c=new URLSearchParams;return c.set("grant_type","refresh_token"),c.set("refresh_token",a.refreshToken),a.scope&&c.set("scope",a.scope),a.resource&&c.set("resource",a.resource),q({endpoint:a.asMetadata.tokenEndpoint,formBody:c,client:a.client,authMethod:r(a.asMetadata,!!a.client.clientSecret),fetcher:b,context:"Token refresh"})}function u(a){return null===a?null:new Date(Date.now()+1e3*a).toISOString()}},663033:a=>{a.exports=require("next/dist/server/app-render/work-unit-async-storage.external.js")},710846:a=>{a.exports=require("next/dist/compiled/next-server/app-page.runtime.prod.js")},719771:a=>{a.exports=require("process")},731421:a=>{a.exports=require("node:child_process")},744870:a=>{a.exports=require("next/dist/compiled/next-server/app-route.runtime.prod.js")},837311:(a,b,c)=>{function d(a){let b=e(a,"x-forwarded-host");if(b){let c=e(a,"x-forwarded-proto");return`${"https"===c?"https":"http"}://${b}`}let c=process.env.DENCHCLAW_PUBLIC_URL?.trim();if(c)try{return new URL(c).origin}catch{}return new URL(a.url).origin}function e(a,b){let c=a.headers.get(b);if(!c)return null;let d=c.split(",")[0]?.trim();return d&&d.length>0?d:null}c.d(b,{F:()=>d})},848161:a=>{a.exports=require("node:os")},973024:a=>{a.exports=require("node:fs")},977598:a=>{a.exports=require("node:crypto")},979428:a=>{a.exports=require("buffer")},986439:a=>{a.exports=require("next/dist/shared/lib/no-fallback-error.external")}};var b=require("../../../../../../webpack-runtime.js");b.C(a);var c=b.X(0,[76973,22137,53536,93349,44877],()=>b(b.s=8422));module.exports=c})();