@onyxsecurity/mcp-gateway 1.0.60 → 1.0.62

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.
Files changed (35) hide show
  1. package/dist/bin/mcp-gateway.js +1 -1
  2. package/dist/bin/mcp-gateway.js.map +1 -1
  3. package/dist/cli-hUdtQZrM.js +3 -0
  4. package/dist/cli-hUdtQZrM.js.map +1 -0
  5. package/dist/env-B6g4xVm2.js +2 -0
  6. package/dist/env-B6g4xVm2.js.map +1 -0
  7. package/dist/env-C0qgM-0A.js +1 -0
  8. package/dist/{helpers-Cwd-UJrA.js → helpers-yvgumKoO.js} +1 -1
  9. package/dist/{helpers-Cwd-UJrA.js.map → helpers-yvgumKoO.js.map} +1 -1
  10. package/dist/index.d.ts +18 -2
  11. package/dist/index.js +1 -1
  12. package/dist/index.js.map +1 -1
  13. package/dist/logger-D1idc7UF.js +5 -0
  14. package/dist/logger-D1idc7UF.js.map +1 -0
  15. package/dist/main-CGwMY_Vy.js +8 -0
  16. package/dist/main-CGwMY_Vy.js.map +1 -0
  17. package/dist/normalizeUrl-u9rsNRmG.js +6 -0
  18. package/dist/normalizeUrl-u9rsNRmG.js.map +1 -0
  19. package/dist/oauthProvidersClient-B7g-tfMh.js +2 -0
  20. package/dist/oauthProvidersClient-B7g-tfMh.js.map +1 -0
  21. package/dist/oauthProvidersClient-CSW6qbrm.js +1 -0
  22. package/dist/pkce-CYE2WffE.js +1 -0
  23. package/dist/{pkce-ANRIC6ce.js → pkce-DKfQXsGm.js} +1 -1
  24. package/dist/{pkce-ANRIC6ce.js.map → pkce-DKfQXsGm.js.map} +1 -1
  25. package/dist/providers-fcvKJ-pI.js +2 -0
  26. package/dist/providers-fcvKJ-pI.js.map +1 -0
  27. package/dist/{normalizeUrl-Cni_Rjv3.js → stdio-tIae6Emm.js} +9 -16
  28. package/dist/stdio-tIae6Emm.js.map +1 -0
  29. package/dist/transportDetection-Dd6To20h.js +136 -0
  30. package/dist/transportDetection-Dd6To20h.js.map +1 -0
  31. package/package.json +1 -1
  32. package/dist/main-Ct3dHxDT.js +0 -142
  33. package/dist/main-Ct3dHxDT.js.map +0 -1
  34. package/dist/normalizeUrl-Cni_Rjv3.js.map +0 -1
  35. package/dist/pkce-dymop6yt.js +0 -1
@@ -0,0 +1,136 @@
1
+ import{SSEClientTransport as e,StreamableHTTPClientTransport as t,discoverAuthorizationServerMetadata as n,discoverOAuthProtectedResourceMetadata as r,exchangeAuthorization as i,normalizeUrl as a,refreshAuthorization as o,registerClient as s,startAuthorization as c}from"./normalizeUrl-u9rsNRmG.js";import{config as l}from"./env-B6g4xVm2.js";import{logger as u}from"./logger-D1idc7UF.js";import{findProviderForUrl as d}from"./providers-fcvKJ-pI.js";import{platform as f}from"node:os";import{createServer as p}from"node:http";import{execFile as m}from"node:child_process";import{URL as h}from"node:url";async function g(e){let t=e.toString(),n=f(),r=b(t);return new Promise((e,i)=>{let a,o;if(n===`win32`){let e=`Start-Process ${v(t)}`,n=_(e);a=y(),o=[`-NoProfile`,`-NonInteractive`,`-ExecutionPolicy`,`Bypass`,`-EncodedCommand`,n]}else n===`darwin`?(a=`open`,o=[t]):(a=`xdg-open`,o=[t]);m(a,o,(t,o,s)=>{if(t){let e={command:a,os:n,stderr:s,url:r};u.warn(`Failed to open browser automatically`,{...e,error:t.message});let o=Error(`Failed to open browser: ${t.message} (command: ${a}, os: ${n}, url: ${r})`);o.cause=t,i(o)}else u.debug(`Browser opened successfully`,{url:r}),e()})})}function _(e){return Buffer.from(e,`utf16le`).toString(`base64`)}function v(e){return`'${e.replaceAll(`'`,`''`)}'`}function y(){return`${process.env.SYSTEMROOT||process.env.windir||`C:\\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`}function b(e){try{let t=new URL(e);return t.search?`${t.protocol}//${t.host}${t.pathname}?[REDACTED]`:`${t.protocol}//${t.host}${t.pathname}`}catch{return`[INVALID_URL]`}}const x={CALLBACK_FAILED:`mcp_auth_callback_failed`,DCR_FAILED:`mcp_auth_dcr_failed`,REFRESH_FAILED:`mcp_auth_refresh_failed`,SERVER_METADATA_FAILED:`mcp_auth_server_metadata_failed`,STATE_MISMATCH:`mcp_auth_state_mismatch`,TOKEN_EXCHANGE_FAILED:`mcp_auth_token_exchange_failed`},S=49152;function C(){return Math.floor(Math.random()*(65535-S+1))+S}function w(e,t){return new Promise((n,r)=>{let i=t=>{e.removeListener(`listening`,a),r(t)},a=()=>{e.removeListener(`error`,i),n()};e.once(`error`,i),e.once(`listening`,a),e.listen(t,`127.0.0.1`)})}async function T(e={}){let{maxAttempts:t=5,preferredPort:n,serverUrl:r,timeoutMs:i=3e5}=e,a=r?O(r):void 0,o,s,c={},l=new Promise((e,t)=>{o=e,s=t}),d,f=p((e,t)=>{if(e.url===`/favicon.ico`){t.writeHead(404),t.end();return}if(!e.url?.startsWith(`/callback`)){t.writeHead(404),t.end(`Not Found`);return}try{let n=new h(e.url,`http://localhost:${d}`),r=n.searchParams.get(`code`),i=n.searchParams.get(`error`),l=n.searchParams.get(`error_description`),p=n.searchParams.get(`state`);if(i){u.error(`OAuth authorization error`,{error:i,errorDescription:l,eventType:x.CALLBACK_FAILED,...a?{serverUrl:a}:{}}),t.writeHead(400,{"Content-Type":`text/html`}),t.end(D(i,l||void 0)),clearTimeout(c.id),s(Error(`OAuth authorization failed: ${i}${l?` - ${l}`:``}`));return}if(!r){u.error(`OAuth callback missing authorization code`,{eventType:x.CALLBACK_FAILED,reason:`missing_code`,...a?{serverUrl:a}:{}}),t.writeHead(400,{"Content-Type":`text/html`}),t.end(D(`missing_code`,`No authorization code was provided`)),clearTimeout(c.id),s(Error(`OAuth callback missing authorization code`));return}u.info(`OAuth authorization code received`,{codePrefix:`${r.substring(0,10)}...`,hasState:!!p}),t.writeHead(200,{"Content-Type":`text/html`}),t.end(`<!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>Authorization Successful</title>
7
+ <style>
8
+ body {
9
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
10
+ display: flex;
11
+ justify-content: center;
12
+ align-items: center;
13
+ min-height: 100vh;
14
+ margin: 0;
15
+ background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
16
+ color: #fff;
17
+ }
18
+ .container {
19
+ text-align: center;
20
+ padding: 2rem;
21
+ }
22
+ .checkmark {
23
+ width: 80px;
24
+ height: 80px;
25
+ border-radius: 50%;
26
+ background: #10b981;
27
+ display: flex;
28
+ align-items: center;
29
+ justify-content: center;
30
+ margin: 0 auto 1.5rem;
31
+ animation: pop 0.3s ease-out;
32
+ }
33
+ .checkmark svg {
34
+ width: 40px;
35
+ height: 40px;
36
+ stroke: white;
37
+ stroke-width: 3;
38
+ }
39
+ h1 {
40
+ margin: 0 0 0.5rem;
41
+ font-size: 1.75rem;
42
+ font-weight: 600;
43
+ }
44
+ p {
45
+ margin: 0;
46
+ color: #a0aec0;
47
+ font-size: 1rem;
48
+ }
49
+ @keyframes pop {
50
+ 0% { transform: scale(0); }
51
+ 50% { transform: scale(1.1); }
52
+ 100% { transform: scale(1); }
53
+ }
54
+ </style>
55
+ </head>
56
+ <body>
57
+ <div class="container">
58
+ <div class="checkmark">
59
+ <svg viewBox="0 0 24 24" fill="none">
60
+ <path d="M5 13l4 4L19 7" stroke-linecap="round" stroke-linejoin="round"/>
61
+ </svg>
62
+ </div>
63
+ <h1>Authorization Successful</h1>
64
+ <p>You can close this window and return to the terminal.</p>
65
+ </div>
66
+ <script>setTimeout(() => window.close(), 3000);<\/script>
67
+ </body>
68
+ </html>`),clearTimeout(c.id),o({code:r,state:p||void 0}),setTimeout(()=>f.close(),1e3)}catch(e){u.error(`Error processing OAuth callback`,{error:String(e),eventType:x.CALLBACK_FAILED,reason:`callback_processing_error`,...a?{serverUrl:a}:{}}),t.writeHead(500),t.end(`Internal Server Error`),clearTimeout(c.id),s(e instanceof Error?e:Error(String(e)))}});c.id=setTimeout(()=>{s(Error(`OAuth callback timeout after ${i}ms`)),f.close()},i);let m=[],g;for(;m.length<t;){let e;if(m.length===0&&n!==void 0)e=n;else for(e=C();m.includes(e);)e=C();m.push(e);try{await w(f,e),d=e;let t=`http://localhost:${d}/callback`;return u.info(`OAuth callback server started`,{attempt:m.length,callbackUrl:t,port:d}),{callbackUrl:t,close:()=>new Promise(e=>{clearTimeout(c.id),f.close(()=>e()),f.closeAllConnections()}),port:d,waitForCallback:()=>l}}catch(n){if(n.code===`EADDRINUSE`)u.debug(`Port in use, trying another port`,{attempt:m.length,maxAttempts:t,port:e}),g=Error(`Port ${e} is already in use`);else throw clearTimeout(c.id),f.close(),n}}throw clearTimeout(c.id),f.close(),Error(`Failed to start OAuth callback server after ${t} attempts. Tried ports: ${m.join(`, `)}. Last error: ${g?.message||`unknown`}`)}function E(e){return e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`).replace(/"/g,`&quot;`).replace(/'/g,`&#039;`)}function D(e,t){return`<!DOCTYPE html>
69
+ <html lang="en">
70
+ <head>
71
+ <meta charset="UTF-8">
72
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
73
+ <title>Authorization Failed</title>
74
+ <style>
75
+ body {
76
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
77
+ display: flex;
78
+ justify-content: center;
79
+ align-items: center;
80
+ min-height: 100vh;
81
+ margin: 0;
82
+ background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
83
+ color: #fff;
84
+ }
85
+ .container {
86
+ text-align: center;
87
+ padding: 2rem;
88
+ max-width: 400px;
89
+ }
90
+ .error-icon {
91
+ width: 80px;
92
+ height: 80px;
93
+ border-radius: 50%;
94
+ background: #ef4444;
95
+ display: flex;
96
+ align-items: center;
97
+ justify-content: center;
98
+ margin: 0 auto 1.5rem;
99
+ }
100
+ .error-icon svg {
101
+ width: 40px;
102
+ height: 40px;
103
+ stroke: white;
104
+ stroke-width: 3;
105
+ }
106
+ h1 {
107
+ margin: 0 0 0.5rem;
108
+ font-size: 1.75rem;
109
+ font-weight: 600;
110
+ }
111
+ .error-code {
112
+ color: #f87171;
113
+ font-family: monospace;
114
+ margin-bottom: 0.5rem;
115
+ }
116
+ p {
117
+ margin: 0;
118
+ color: #a0aec0;
119
+ font-size: 1rem;
120
+ }
121
+ </style>
122
+ </head>
123
+ <body>
124
+ <div class="container">
125
+ <div class="error-icon">
126
+ <svg viewBox="0 0 24 24" fill="none">
127
+ <path d="M6 18L18 6M6 6l12 12" stroke-linecap="round" stroke-linejoin="round"/>
128
+ </svg>
129
+ </div>
130
+ <h1>Authorization Failed</h1>
131
+ <p class="error-code">${E(e)}</p>
132
+ ${t?`<p>${E(t)}</p>`:``}
133
+ </div>
134
+ </body>
135
+ </html>`}function O(e){try{let t=new h(e);return t.username=``,t.password=``,t.search=``,t.hash=``,t.toString()}catch{return e}}var k=class extends Error{constructor(e,t){let n=t instanceof Error?t.message:String(t);super(`Auth server metadata discovery failed for ${e}: ${n}`),this.authServerUrl=e,this.cause=t,this.name=`AuthServerDiscoveryError`}};async function A(e,t={}){let{logger:i,signal:a}=t,o=a?j(a):void 0;i?.debug(`Discovering OAuth protected resource metadata...`);let s;try{s=o?await r(e,void 0,o):await r(e),i?.info(`Discovered protected resource metadata`,{authorizationServers:s?.authorization_servers,resource:s?.resource,scopesSupported:s?.scopes_supported})}catch(e){i?.warn(`Could not discover protected resource metadata, will try direct discovery`,{error:String(e)})}let c;s?.authorization_servers?.length?(c=new URL(s.authorization_servers[0]),i?.debug(`Using authorization server from resource metadata`,{authServerUrl:c.toString()})):(c=e,i?.debug(`Using server URL as authorization server`,{authServerUrl:c.toString()})),i?.debug(`Discovering authorization server metadata...`);let l;try{l=o?await n(c,{fetchFn:o}):await n(c)}catch(e){throw new k(c,e)}return l&&i?.info(`Discovered authorization server metadata`,{authorizationEndpoint:l.authorization_endpoint,issuer:l.issuer,registrationEndpoint:l.registration_endpoint,tokenEndpoint:l.token_endpoint}),{authMetadata:l,authServerUrl:c,resourceMetadata:s}}function j(e){return(t,n)=>{let r=n?.signal,i=r?AbortSignal.any([e,r]):e;return fetch(t,{...n,signal:i})}}const M={"claude-code":`Claude Code (mcp-gateway)`,codex:`Codex`,copilot:`Visual Studio Code`,cursor:`Cursor`,opencode:`OpenCode`};function N(){return F(l.clientAppName)}async function P(e,t={}){let{credentialStore:n,scope:r,timeoutMs:o}=t,l=a(e),f=new URL(l);if(u.info(`Starting OAuth flow`,{serverUrl:l}),n){let e=await R(f,n);if(e)return u.info(`Using existing OAuth credentials`,{clientId:e.clientInfo.client_id,serverUrl:l}),e}u.debug(`Starting OAuth callback server...`);let p=await T({serverUrl:l,timeoutMs:o}),m=p.callbackUrl;u.info(`OAuth callback server started`,{callbackUrl:m,port:p.port});try{let e=d(f);if(e)return u.info(`Using pre-configured OAuth provider`,{providerId:e.id,providerName:e.name}),await L(f,e,p,n,r);let a,o;try{({authMetadata:a,authServerUrl:o}=await A(f,{logger:u}))}catch(e){throw u.error(`Auth server metadata discovery failed`,{error:String(e),eventType:x.SERVER_METADATA_FAILED,serverUrl:l,...e instanceof k?{authServer:e.authServerUrl.toString()}:{}}),e}if(!a)throw u.error(`Auth server metadata absent (server may not support OAuth 2.0)`,{authServer:o.toString(),eventType:x.SERVER_METADATA_FAILED,reason:`metadata_absent`,serverUrl:l}),Error(`Could not discover OAuth metadata from ${o}. The server may not support OAuth 2.0 or the metadata endpoint is not accessible.`);let h,_=n?await n.load(l):void 0,v=_?.clientInfo?.redirect_uris||[];if(_?.clientInfo&&v.includes(m)&&_?.clientInfo)u.info(`Reusing existing DCR client registration`,{clientId:_.clientInfo.client_id,clientName:_.clientInfo.client_name,redirectUri:m}),h=_.clientInfo;else{_?.clientInfo&&u.info(`Existing DCR client has different redirect_uri, re-registering`,{existingRedirectUris:v,newRedirectUri:m});let e={client_name:t.clientMetadata?.client_name||N(),grant_types:t.clientMetadata?.grant_types||[`authorization_code`,`refresh_token`],redirect_uris:[m],response_types:t.clientMetadata?.response_types||[`code`],token_endpoint_auth_method:t.clientMetadata?.token_endpoint_auth_method||`none`,...r&&{scope:r}};if(u.debug(`Client metadata for DCR`,{clientMetadata:e}),!a.registration_endpoint)throw u.error(`DCR registration unsupported by auth server`,{authServer:o.toString(),eventType:x.DCR_FAILED,reason:`no_registration_endpoint`,serverUrl:l}),Error(`Authorization server does not support Dynamic Client Registration. No registration_endpoint found in metadata.`);u.info(`Registering client via DCR...`,{registrationEndpoint:a.registration_endpoint});try{h=await s(o,{clientMetadata:e,metadata:a})}catch(e){throw u.error(`DCR registration failed`,{authServer:o.toString(),error:String(e),eventType:x.DCR_FAILED,registrationEndpoint:a.registration_endpoint,serverUrl:l}),e}u.info(`Client registered successfully via DCR`,{clientId:h.client_id,clientName:h.client_name,clientSecretExpiresAt:h.client_secret_expires_at}),n&&await n.update(l,{clientInfo:h})}let y=crypto.randomUUID();u.debug(`Starting authorization flow...`);let{authorizationUrl:b,codeVerifier:S}=await c(o,{clientInformation:h,metadata:a,redirectUrl:m,scope:r,state:y});await g(b),u.debug(`Waiting for OAuth callback...`);let C=await p.waitForCallback();if(C.state!==y)throw u.error(`OAuth state mismatch — possible CSRF attack`,{authServer:o.toString(),eventType:x.STATE_MISMATCH,serverUrl:l}),Error(`OAuth state mismatch - possible CSRF attack`);u.info(`Authorization code received`,{codePrefix:`${C.code.substring(0,10)}...`}),u.debug(`Exchanging authorization code for tokens...`);let w;try{w=await i(o,{authorizationCode:C.code,clientInformation:h,codeVerifier:S,metadata:a,redirectUri:m})}catch(e){throw u.error(`Token exchange failed`,{authServer:o.toString(),clientId:h.client_id,error:String(e),eventType:x.TOKEN_EXCHANGE_FAILED,grantType:`authorization_code`,serverUrl:l}),e}if(u.info(`OAuth tokens obtained successfully`,{expiresIn:w.expires_in,hasRefreshToken:!!w.refresh_token,tokenType:w.token_type}),n){let e=new Date().toISOString();await n.update(l,{tokens:w,tokensObtainedAt:e}),u.info(`OAuth credentials persisted to disk`,{serverUrl:l})}return{clientInfo:h,fromCache:!1,tokens:w}}finally{await p.close()}}function F(e){let t=e?.trim().toLowerCase();return t?M[t]??`MCP Gateway`:`MCP Gateway`}async function I(e,t,n,r){let i=e.tokenEndpoint,a=e.tokenEndpointAuthMethod||(e.clientSecret?`client_secret_post`:`none`),o=new URLSearchParams;o.set(`grant_type`,`authorization_code`),o.set(`code`,t),o.set(`redirect_uri`,n),r&&o.set(`code_verifier`,r);let s={Accept:`application/json`,"Content-Type":`application/x-www-form-urlencoded`};a===`client_secret_basic`&&e.clientSecret?s.Authorization=`Basic ${Buffer.from(`${e.clientId}:${e.clientSecret}`).toString(`base64`)}`:a===`client_secret_post`&&e.clientSecret?(o.set(`client_id`,e.clientId),o.set(`client_secret`,e.clientSecret)):o.set(`client_id`,e.clientId),u.debug(`Sending token request`,{authMethod:a,providerId:e.id,tokenEndpoint:i});let c=await fetch(i,{body:o.toString(),headers:s,method:`POST`});if(!c.ok){let t=await c.text();throw u.error(`Token exchange failed`,{authMethod:a,error:t,eventType:x.TOKEN_EXCHANGE_FAILED,grantType:`authorization_code`,httpStatus:c.status,providerId:e.id,tokenEndpoint:i}),Error(`Token exchange failed: ${c.status} ${t}`)}let l=c.headers.get(`content-type`)||``,d;if(l.includes(`application/json`))d=await c.json();else if(l.includes(`application/x-www-form-urlencoded`)||l.includes(`text/plain`)){let e=await c.text(),t=new URLSearchParams(e);d=Object.fromEntries(t.entries())}else{let e=await c.text();try{d=JSON.parse(e)}catch{let t=new URLSearchParams(e);d=Object.fromEntries(t.entries())}}return typeof d.expires_in==`string`&&(d.expires_in=parseInt(d.expires_in,10)),{access_token:d.access_token,expires_in:d.expires_in,refresh_token:d.refresh_token,scope:d.scope,token_type:d.token_type||`bearer`}}async function L(e,t,n,r,i){let a=e.toString(),o=n.callbackUrl,s={client_id:t.clientId,client_name:t.name,client_secret:t.clientSecret,redirect_uris:[o],token_endpoint_auth_method:t.tokenEndpointAuthMethod||(t.clientSecret?`client_secret_post`:`none`)};u.info(`Using pre-configured OAuth client`,{clientId:t.clientId,hasClientSecret:!!t.clientSecret,providerId:t.id,tokenEndpointAuthMethod:s.token_endpoint_auth_method});let c=i||t.scopes?.join(` `),l=t.usePkce!==!1,d,f,p;if(l){let{generateCodeChallenge:e,generateCodeVerifier:t}=await import(`./pkce-CYE2WffE.js`);d=t(),f=await e(d),p=`S256`}let m=new URL(t.authorizationEndpoint);m.searchParams.set(`client_id`,t.clientId),m.searchParams.set(`redirect_uri`,o),m.searchParams.set(`response_type`,`code`),c&&m.searchParams.set(`scope`,c);let h=crypto.randomUUID();m.searchParams.set(`state`,h),f&&p&&(m.searchParams.set(`code_challenge`,f),m.searchParams.set(`code_challenge_method`,p)),await g(m),u.debug(`Waiting for OAuth callback...`);let _=await n.waitForCallback();if(_.state!==h)throw u.error(`OAuth state mismatch — possible CSRF attack`,{eventType:x.STATE_MISMATCH,providerId:t.id,serverUrl:a}),Error(`OAuth state mismatch - possible CSRF attack`);u.info(`Authorization code received`,{codePrefix:`${_.code.substring(0,10)}...`,providerId:t.id}),u.debug(`Exchanging authorization code for tokens...`);let v=await I(t,_.code,o,d);if(u.info(`OAuth tokens obtained successfully`,{expiresIn:v.expires_in,hasRefreshToken:!!v.refresh_token,providerId:t.id,tokenType:v.token_type}),r){let e=new Date().toISOString();await r.update(a,{clientInfo:s,tokens:v,tokensObtainedAt:e}),u.info(`OAuth credentials persisted to disk`,{providerId:t.id,serverUrl:a})}return{clientInfo:s,fromCache:!1,tokens:v}}async function R(e,t){let n=await t.load(e.toString());if(!n){u.debug(`No stored credentials found`,{serverUrl:e.toString()});return}if(!n.clientInfo){u.debug(`Stored credentials have no client info`,{serverUrl:e.toString()});return}if(t.hasValidAccessToken(n)&&n.tokens)return u.info(`Using cached OAuth credentials with valid access token`,{clientId:n.clientInfo.client_id,serverUrl:e.toString()}),{clientInfo:n.clientInfo,fromCache:!0,tokens:n.tokens};if(t.hasRefreshToken(n)){let r=await z(e,n,t);if(r)return r}u.debug(`Stored credentials are expired and no valid refresh token`,{serverUrl:e.toString()})}async function z(e,t,i){if(!(!t.clientInfo||!t.tokens?.refresh_token)){u.info(`Attempting to refresh expired access token`,{clientId:t.clientInfo.client_id,serverUrl:e.toString()});try{let a;try{a=await r(e)}catch{}let s;s=a?.authorization_servers?.length?new URL(a.authorization_servers[0]):e;let c=await n(s),l=await o(s,{clientInformation:t.clientInfo,metadata:c,refreshToken:t.tokens.refresh_token});u.info(`Successfully refreshed access token`,{clientId:t.clientInfo.client_id,expiresIn:l.expires_in,hasNewRefreshToken:!!l.refresh_token});let d=new Date().toISOString();return await i.update(e.toString(),{tokens:l,tokensObtainedAt:d}),{clientInfo:t.clientInfo,fromCache:!0,tokens:l}}catch(n){u.warn(`Failed to refresh access token, will require re-authorization`,{clientId:t.clientInfo.client_id,error:String(n),eventType:x.REFRESH_FAILED,serverUrl:e.toString()}),await i.update(e.toString(),{tokens:void 0,tokensObtainedAt:void 0});return}}}const B=[`streamable-http`,`sse`];async function V(e,t,n){let{result:r,transportType:i}=await W(async r=>{let i=e(),a=H(t,r,n);return await i.connect(a),i});return{client:r,transportType:i}}function H(n,r,i){let a=new URL(n);return r===`streamable-http`?new t(a,{requestInit:i}):new e(a,{requestInit:i})}function U(e){if(!e||typeof e!=`object`)return!1;let t=e.status,n=e.code,r=e.message;return!!(t===404||t===405||n===404||n===405||r&&/404|not found|405|method not allowed/i.test(String(r)))}async function W(e){let t=[];for(let n of B)try{return{result:await e(n),transportType:n}}catch(e){if(U(e)){u.info(`${n} not supported, trying next transport...`),t.push({err:e,transport:n});continue}throw e}let n=t.map(({err:e,transport:t})=>{let n=e?.status;if(n!==void 0)return`${t}: ${n}`;let r=e instanceof Error?e.message:String(e);return`${t}: ${r}`}).join(`, `),r=t.length>0?Error(`all transports returned not-supported (${n})`):Error(`No compatible transport found`);throw r.cause=t,r}export{k as AuthServerDiscoveryError,V as connectWithTransportFallback,A as discoverAuthServer,N as getDcrClientName,P as performOAuthFlow,W as walkTransports};
136
+ //# sourceMappingURL=transportDetection-Dd6To20h.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"transportDetection-Dd6To20h.js","names":["command: string","args: string[]","resolveCallback: (result: CallbackServerResult) => void","rejectCallback: (error: Error) => void","timeoutRef: { id?: ReturnType<typeof setTimeout> }","boundPort: number","URL","attemptedPorts: number[]","lastError: Error | undefined","portToTry: number","authServerUrl: URL","cause: unknown","resourceMetadata: OAuthProtectedResourceMetadata | undefined","authMetadata: Awaited<ReturnType<typeof discoverAuthorizationServerMetadata>>","DCR_CLIENT_NAME_BY_APP: Record<string, string>","authMetadata: Awaited<ReturnType<typeof discoverAuthServer>>[\"authMetadata\"]","authServerUrl: URL","clientInfo: OAuthClientInformationFull","clientMetadata: OAuthClientMetadata","headers: Record<string, string>","tokenData: Record<string, unknown>","codeVerifier: string | undefined","codeChallenge: string | undefined","codeChallengeMethod: string | undefined","resourceMetadata: OAuthProtectedResourceMetadata | undefined","TRANSPORT_PRIORITY: TransportType[]","client","transportType","failures: Array<{ err: unknown; transport: TransportType }>"],"sources":["../src/auth/browser.ts","../src/auth/events.ts","../src/auth/callbackServer.ts","../src/auth/discovery.ts","../src/auth/oauthFlow.ts","../src/lib/transportDetection.ts"],"sourcesContent":["import { execFile } from \"node:child_process\";\nimport { platform } from \"node:os\";\n\nimport { logger } from \"../lib/logger.js\";\n\n/**\n * Opens the given URL in the user's default browser.\n *\n * Cross-platform support:\n * - macOS: uses `open`\n * - Windows: uses PowerShell Start-Process with Base64-encoded command (injection-safe)\n * - Linux: uses `xdg-open`\n *\n * @param url The URL to open\n * @returns A promise that resolves when the browser command is executed\n */\nexport async function openBrowser(url: string | URL): Promise<void> {\n const urlString = url.toString();\n const os = platform();\n const redactedUrl = redactUrlForLogging(urlString);\n\n return new Promise((resolve, reject) => {\n let command: string;\n let args: string[];\n\n if (os === \"win32\") {\n // Windows - use PowerShell with Base64-encoded command to prevent injection\n // This is the same approach used by the popular 'open' npm package.\n // The command is Base64-encoded (UTF-16LE) so no shell metacharacters can escape.\n const psCommand = `Start-Process ${escapePowerShellArgument(urlString)}`;\n const encodedCommand = encodePowerShellCommand(psCommand);\n\n command = getPowerShellPath();\n args = [\"-NoProfile\", \"-NonInteractive\", \"-ExecutionPolicy\", \"Bypass\", \"-EncodedCommand\", encodedCommand];\n } else if (os === \"darwin\") {\n // macOS\n command = \"open\";\n args = [urlString];\n } else {\n // Linux and others - use xdg-open\n command = \"xdg-open\";\n args = [urlString];\n }\n\n execFile(command, args, (error, _stdout, stderr) => {\n if (error) {\n const errorContext = {\n command,\n os,\n stderr,\n url: redactedUrl,\n };\n\n logger.warn(\"Failed to open browser automatically\", {\n ...errorContext,\n error: error.message,\n });\n\n const launchError = new Error(\n `Failed to open browser: ${error.message} (command: ${command}, os: ${os}, url: ${redactedUrl})`\n );\n launchError.cause = error;\n reject(launchError);\n } else {\n logger.debug(\"Browser opened successfully\", { url: redactedUrl });\n resolve();\n }\n });\n });\n}\n\n/**\n * Encodes a PowerShell command as Base64 UTF-16LE for use with -EncodedCommand.\n * This is the safest way to pass commands to PowerShell as it prevents any\n * shell metacharacter interpretation.\n */\nfunction encodePowerShellCommand(command: string): string {\n // PowerShell's -EncodedCommand expects UTF-16LE encoded Base64\n const buffer = Buffer.from(command, \"utf16le\");\n return buffer.toString(\"base64\");\n}\n\n/**\n * Escapes a string for use as a PowerShell single-quoted string argument.\n * Single quotes inside the string are escaped by doubling them.\n */\nfunction escapePowerShellArgument(value: string): string {\n return `'${value.replaceAll(\"'\", \"''\")}'`;\n}\n\n/**\n * Gets the path to Windows PowerShell.\n * PowerShell is included by default since Windows 7 SP1 and Windows Server 2008 R2.\n */\nfunction getPowerShellPath(): string {\n const systemRoot = process.env.SYSTEMROOT || process.env.windir || \"C:\\\\Windows\";\n return `${systemRoot}\\\\System32\\\\WindowsPowerShell\\\\v1.0\\\\powershell.exe`;\n}\n\n/**\n * Redacts sensitive query parameters from a URL for safe logging.\n * Preserves the base URL structure while hiding potentially sensitive data.\n *\n * @param url The URL to redact\n * @returns A redacted version of the URL safe for logging\n */\nfunction redactUrlForLogging(url: string): string {\n try {\n const parsed = new URL(url);\n if (parsed.search) {\n return `${parsed.protocol}//${parsed.host}${parsed.pathname}?[REDACTED]`;\n }\n return `${parsed.protocol}//${parsed.host}${parsed.pathname}`;\n } catch {\n // If URL parsing fails, return a generic redacted string\n return \"[INVALID_URL]\";\n }\n}\n","/**\n * Structured `eventType` values emitted from the OAuth code paths in this\n * package. groundcover monitors filter on these strings, so renames here are\n * breaking changes for the monitoring pipeline — bump the monitor YAMLs in\n * the infrastructure repo when you change anything below.\n *\n * Naming convention: `mcp_auth_*_failed` for unrecoverable errors; the\n * `mcp_auth_performed` happy-path event lives in src/bin/main.ts because it\n * is emitted by the proxy boot code, not by this auth subpackage.\n */\nexport const AuthEventType = {\n /** OAuth callback server received error= or no code, or failed to parse. */\n CALLBACK_FAILED: \"mcp_auth_callback_failed\",\n /** registerClient threw or auth server has no registration_endpoint. */\n DCR_FAILED: \"mcp_auth_dcr_failed\",\n /** Refresh-token grant rejected by the auth server. */\n REFRESH_FAILED: \"mcp_auth_refresh_failed\",\n /**\n * `discoverAuthorizationServerMetadata` threw, or returned an empty\n * document. NOTE: resource-metadata soft-fails are NOT emitted as failed\n * events — the SDK silently falls back to using the server URL as the\n * auth server, which is expected for some MCP servers.\n */\n SERVER_METADATA_FAILED: \"mcp_auth_server_metadata_failed\",\n /** OAuth state parameter mismatch — possible CSRF, definitely a failure. */\n STATE_MISMATCH: \"mcp_auth_state_mismatch\",\n /** Authorization-code or refresh-token POST to /token failed (non-2xx). */\n TOKEN_EXCHANGE_FAILED: \"mcp_auth_token_exchange_failed\",\n} as const;\n\nexport type AuthEventType = (typeof AuthEventType)[keyof typeof AuthEventType];\n","import { createServer, type Server } from \"node:http\";\nimport { URL } from \"node:url\";\n\nimport { logger } from \"../lib/logger.js\";\nimport { AuthEventType } from \"./events.js\";\n\n/**\n * Port range for OAuth callback server (IANA dynamic/private ports)\n */\nconst MIN_PORT = 49152;\nconst MAX_PORT = 65535;\nconst MAX_PORT_ATTEMPTS = 5;\n\nexport interface CallbackServerOptions {\n /**\n * Maximum number of port binding attempts before giving up.\n * Default: 5\n */\n maxAttempts?: number;\n /**\n * Preferred port to use. If unavailable, random ports will be tried.\n */\n preferredPort?: number;\n /**\n * MCP server URL whose OAuth flow this callback is serving. Threaded\n * through to the callback's error logs so groundcover monitors can\n * attribute mcp_auth_callback_failed events to a specific remote.\n * Optional — when omitted, the field is simply absent from the logs.\n */\n serverUrl?: string;\n /**\n * Timeout in milliseconds to wait for the callback.\n * Default: 5 minutes (300000ms)\n */\n timeoutMs?: number;\n}\n\nexport interface CallbackServerResult {\n /**\n * The authorization code received from the OAuth server.\n */\n code: string;\n /**\n * The state parameter, if provided.\n */\n state?: string;\n}\n\n/**\n * Generates a random port number in the dynamic/private port range.\n */\nfunction getRandomPort(): number {\n return Math.floor(Math.random() * (MAX_PORT - MIN_PORT + 1)) + MIN_PORT;\n}\n\n/**\n * Attempts to start the HTTP server on the given port.\n * Returns a promise that resolves with the server if successful, or rejects if the port is in use.\n */\nfunction tryListenOnPort(server: Server, port: number): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n const onError = (err: NodeJS.ErrnoException) => {\n server.removeListener(\"listening\", onListening);\n reject(err);\n };\n\n const onListening = () => {\n server.removeListener(\"error\", onError);\n resolve();\n };\n\n server.once(\"error\", onError);\n server.once(\"listening\", onListening);\n server.listen(port, \"127.0.0.1\");\n });\n}\n\nconst DEFAULT_TIMEOUT_MS = 5 * 60 * 1000; // 5 minutes\n\n/**\n * HTML page shown to the user after successful authorization.\n */\nconst SUCCESS_HTML = `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Authorization Successful</title>\n <style>\n body {\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n display: flex;\n justify-content: center;\n align-items: center;\n min-height: 100vh;\n margin: 0;\n background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);\n color: #fff;\n }\n .container {\n text-align: center;\n padding: 2rem;\n }\n .checkmark {\n width: 80px;\n height: 80px;\n border-radius: 50%;\n background: #10b981;\n display: flex;\n align-items: center;\n justify-content: center;\n margin: 0 auto 1.5rem;\n animation: pop 0.3s ease-out;\n }\n .checkmark svg {\n width: 40px;\n height: 40px;\n stroke: white;\n stroke-width: 3;\n }\n h1 {\n margin: 0 0 0.5rem;\n font-size: 1.75rem;\n font-weight: 600;\n }\n p {\n margin: 0;\n color: #a0aec0;\n font-size: 1rem;\n }\n @keyframes pop {\n 0% { transform: scale(0); }\n 50% { transform: scale(1.1); }\n 100% { transform: scale(1); }\n }\n </style>\n</head>\n<body>\n <div class=\"container\">\n <div class=\"checkmark\">\n <svg viewBox=\"0 0 24 24\" fill=\"none\">\n <path d=\"M5 13l4 4L19 7\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/>\n </svg>\n </div>\n <h1>Authorization Successful</h1>\n <p>You can close this window and return to the terminal.</p>\n </div>\n <script>setTimeout(() => window.close(), 3000);</script>\n</body>\n</html>`;\n\n/**\n * Starts a local HTTP server to receive the OAuth callback.\n * Uses random port selection with retry logic to handle port conflicts.\n *\n * @returns A promise that resolves with the port number and a function to wait for the callback.\n */\nexport async function startCallbackServer(options: CallbackServerOptions = {}): Promise<{\n callbackUrl: string;\n close: () => Promise<void>;\n port: number;\n waitForCallback: () => Promise<CallbackServerResult>;\n}> {\n const { maxAttempts = MAX_PORT_ATTEMPTS, preferredPort, serverUrl, timeoutMs = DEFAULT_TIMEOUT_MS } = options;\n // Strip userinfo + query params before logging — a configured MCP URL\n // can carry tokens or basic-auth credentials, and these errors get\n // persisted to logs/alerts. Keep the protocol+host+path so the log is\n // still useful for triage.\n const safeServerUrl = serverUrl ? sanitizeServerUrl(serverUrl) : undefined;\n\n let resolveCallback: (result: CallbackServerResult) => void;\n let rejectCallback: (error: Error) => void;\n // Using an object to hold the timeout ID so it can be set after server creation\n // but still referenced in the close() function\n const timeoutRef: { id?: ReturnType<typeof setTimeout> } = {};\n\n const callbackPromise = new Promise<CallbackServerResult>((resolve, reject) => {\n resolveCallback = resolve;\n rejectCallback = reject;\n });\n\n // Track the actual bound port for use in request handler\n let boundPort: number;\n\n const server = createServer((req, res) => {\n // Ignore favicon requests\n if (req.url === \"/favicon.ico\") {\n res.writeHead(404);\n res.end();\n return;\n }\n\n // Only handle the callback path\n if (!req.url?.startsWith(\"/callback\")) {\n res.writeHead(404);\n res.end(\"Not Found\");\n return;\n }\n\n try {\n const parsedUrl = new URL(req.url, `http://localhost:${boundPort}`);\n const code = parsedUrl.searchParams.get(\"code\");\n const error = parsedUrl.searchParams.get(\"error\");\n const errorDescription = parsedUrl.searchParams.get(\"error_description\");\n const state = parsedUrl.searchParams.get(\"state\");\n\n if (error) {\n logger.error(\"OAuth authorization error\", {\n error,\n errorDescription,\n eventType: AuthEventType.CALLBACK_FAILED,\n ...(safeServerUrl ? { serverUrl: safeServerUrl } : {}),\n });\n res.writeHead(400, { \"Content-Type\": \"text/html\" });\n res.end(getErrorHtml(error, errorDescription || undefined));\n clearTimeout(timeoutRef.id);\n rejectCallback(\n new Error(`OAuth authorization failed: ${error}${errorDescription ? ` - ${errorDescription}` : \"\"}`)\n );\n return;\n }\n\n if (!code) {\n logger.error(\"OAuth callback missing authorization code\", {\n eventType: AuthEventType.CALLBACK_FAILED,\n reason: \"missing_code\",\n ...(safeServerUrl ? { serverUrl: safeServerUrl } : {}),\n });\n res.writeHead(400, { \"Content-Type\": \"text/html\" });\n res.end(getErrorHtml(\"missing_code\", \"No authorization code was provided\"));\n clearTimeout(timeoutRef.id);\n rejectCallback(new Error(\"OAuth callback missing authorization code\"));\n return;\n }\n\n logger.info(\"OAuth authorization code received\", {\n codePrefix: `${code.substring(0, 10)}...`,\n hasState: !!state,\n });\n\n res.writeHead(200, { \"Content-Type\": \"text/html\" });\n res.end(SUCCESS_HTML);\n\n clearTimeout(timeoutRef.id);\n resolveCallback({ code, state: state || undefined });\n\n // Close server after a short delay to ensure response is sent\n setTimeout(() => server.close(), 1000);\n } catch (err) {\n logger.error(\"Error processing OAuth callback\", {\n error: String(err),\n eventType: AuthEventType.CALLBACK_FAILED,\n reason: \"callback_processing_error\",\n ...(safeServerUrl ? { serverUrl: safeServerUrl } : {}),\n });\n res.writeHead(500);\n res.end(\"Internal Server Error\");\n clearTimeout(timeoutRef.id);\n rejectCallback(err instanceof Error ? err : new Error(String(err)));\n }\n });\n\n // Set up timeout (now that server exists)\n timeoutRef.id = setTimeout(() => {\n rejectCallback(new Error(`OAuth callback timeout after ${timeoutMs}ms`));\n server.close();\n }, timeoutMs);\n\n // Try to bind to a port with retry logic\n const attemptedPorts: number[] = [];\n let lastError: Error | undefined;\n\n while (attemptedPorts.length < maxAttempts) {\n // First attempt uses preferred port if provided, otherwise random\n let portToTry: number;\n if (attemptedPorts.length === 0 && preferredPort !== undefined) {\n portToTry = preferredPort;\n } else {\n // Generate a random port that hasn't been tried yet\n portToTry = getRandomPort();\n while (attemptedPorts.includes(portToTry)) {\n portToTry = getRandomPort();\n }\n }\n attemptedPorts.push(portToTry);\n\n try {\n await tryListenOnPort(server, portToTry);\n boundPort = portToTry;\n const callbackUrl = `http://localhost:${boundPort}/callback`;\n logger.info(\"OAuth callback server started\", { attempt: attemptedPorts.length, callbackUrl, port: boundPort });\n\n return {\n callbackUrl,\n close: () =>\n new Promise<void>((resolve) => {\n clearTimeout(timeoutRef.id);\n server.close(() => resolve());\n // Browsers hold the keep-alive socket open after the OAuth success\n // page loads. Without forcing existing connections closed, Node's\n // server.close() waits indefinitely for them to drain and the\n // OAuth flow hangs after persisting tokens.\n server.closeAllConnections();\n }),\n port: boundPort,\n waitForCallback: () => callbackPromise,\n };\n } catch (err) {\n const nodeErr = err as NodeJS.ErrnoException;\n if (nodeErr.code === \"EADDRINUSE\") {\n logger.debug(\"Port in use, trying another port\", {\n attempt: attemptedPorts.length,\n maxAttempts,\n port: portToTry,\n });\n lastError = new Error(`Port ${portToTry} is already in use`);\n } else {\n // For non-EADDRINUSE errors, clean up and throw immediately\n clearTimeout(timeoutRef.id);\n server.close();\n throw err;\n }\n }\n }\n\n // All attempts failed\n clearTimeout(timeoutRef.id);\n server.close();\n throw new Error(\n `Failed to start OAuth callback server after ${maxAttempts} attempts. ` +\n `Tried ports: ${attemptedPorts.join(\", \")}. Last error: ${lastError?.message || \"unknown\"}`\n );\n}\n\nfunction escapeHtml(text: string): string {\n return text\n .replace(/&/g, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\")\n .replace(/\"/g, \"&quot;\")\n .replace(/'/g, \"&#039;\");\n}\n\n/**\n * HTML page shown to the user when authorization fails.\n */\nfunction getErrorHtml(error: string, description?: string): string {\n return `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Authorization Failed</title>\n <style>\n body {\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n display: flex;\n justify-content: center;\n align-items: center;\n min-height: 100vh;\n margin: 0;\n background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);\n color: #fff;\n }\n .container {\n text-align: center;\n padding: 2rem;\n max-width: 400px;\n }\n .error-icon {\n width: 80px;\n height: 80px;\n border-radius: 50%;\n background: #ef4444;\n display: flex;\n align-items: center;\n justify-content: center;\n margin: 0 auto 1.5rem;\n }\n .error-icon svg {\n width: 40px;\n height: 40px;\n stroke: white;\n stroke-width: 3;\n }\n h1 {\n margin: 0 0 0.5rem;\n font-size: 1.75rem;\n font-weight: 600;\n }\n .error-code {\n color: #f87171;\n font-family: monospace;\n margin-bottom: 0.5rem;\n }\n p {\n margin: 0;\n color: #a0aec0;\n font-size: 1rem;\n }\n </style>\n</head>\n<body>\n <div class=\"container\">\n <div class=\"error-icon\">\n <svg viewBox=\"0 0 24 24\" fill=\"none\">\n <path d=\"M6 18L18 6M6 6l12 12\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/>\n </svg>\n </div>\n <h1>Authorization Failed</h1>\n <p class=\"error-code\">${escapeHtml(error)}</p>\n ${description ? `<p>${escapeHtml(description)}</p>` : \"\"}\n </div>\n</body>\n</html>`;\n}\n\n/**\n * Strip credentials and query params from a URL before logging. Keeps\n * protocol + host + path so the log is still useful for triage. Returns\n * the original string when parsing fails (better to over-log than to\n * silently drop the attribution field).\n */\nfunction sanitizeServerUrl(url: string): string {\n try {\n const u = new URL(url);\n u.username = \"\";\n u.password = \"\";\n u.search = \"\";\n u.hash = \"\";\n return u.toString();\n } catch {\n return url;\n }\n}\n","import {\n discoverAuthorizationServerMetadata,\n discoverOAuthProtectedResourceMetadata,\n} from \"@modelcontextprotocol/sdk/client/auth.js\";\nimport type { OAuthProtectedResourceMetadata } from \"@modelcontextprotocol/sdk/shared/auth.js\";\n\nexport interface DiscoverAuthServerOptions {\n /**\n * Optional logger. When provided, emits the same debug/info/warn lines that\n * `performOAuthFlow` used to emit inline. When omitted, discovery runs\n * silently.\n */\n logger?: DiscoveryLogger;\n /**\n * Optional AbortSignal, threaded into both SDK discovery calls via a fetch\n * wrapper. When omitted, the SDK calls are made with no fetch override —\n * preserving the existing `performOAuthFlow` call shape exactly.\n */\n signal?: AbortSignal;\n}\n\n/**\n * Minimal logging surface used by the discovery helper. Matches the shape of\n * `../lib/logger.ts`'s singleton so callers can pass it directly. Omit to run\n * discovery silently (the probe's call pattern).\n */\nexport interface DiscoveryLogger {\n debug(message: string, meta?: Record<string, unknown>): void;\n info(message: string, meta?: Record<string, unknown>): void;\n warn(message: string, meta?: Record<string, unknown>): void;\n}\n\nexport interface DiscoveryResult {\n /** Auth-server metadata. May be undefined — caller decides how to respond. */\n authMetadata: Awaited<ReturnType<typeof discoverAuthorizationServerMetadata>>;\n /**\n * The chosen auth server URL: the first entry of `resourceMetadata.authorization_servers`\n * when present, otherwise `serverUrl` itself.\n */\n authServerUrl: URL;\n /** Protected-resource metadata. Undefined when the document is missing or lookup soft-failed. */\n resourceMetadata: OAuthProtectedResourceMetadata | undefined;\n}\n\n/**\n * Thrown when `discoverAuthorizationServerMetadata` fails. Preserves the\n * computed `authServerUrl` so callers can include it in error messages /\n * probe results — the pre-refactor inline code had it in scope naturally.\n */\nexport class AuthServerDiscoveryError extends Error {\n constructor(\n public readonly authServerUrl: URL,\n public readonly cause: unknown\n ) {\n const msg = cause instanceof Error ? cause.message : String(cause);\n super(`Auth server metadata discovery failed for ${authServerUrl}: ${msg}`);\n this.name = \"AuthServerDiscoveryError\";\n }\n}\n\n/**\n * Runs the OAuth metadata discovery sequence shared by the full OAuth flow and\n * the install-time DCR probe:\n *\n * 1. Look up the protected-resource metadata (soft-fails on error).\n * 2. Pick the auth server URL — the first `authorization_servers` entry, or\n * `serverUrl` as a fallback.\n * 3. Look up the auth-server metadata. Throws iff the SDK call itself throws;\n * does NOT throw when the SDK returns undefined (caller decides).\n *\n * No policy decisions baked in — both callers (`performOAuthFlow` and `probeOne`)\n * apply their own handling to the result.\n */\nexport async function discoverAuthServer(\n serverUrl: URL,\n options: DiscoverAuthServerOptions = {}\n): Promise<DiscoveryResult> {\n const { logger, signal } = options;\n const fetchFn = signal ? signaledFetch(signal) : undefined;\n\n logger?.debug(\"Discovering OAuth protected resource metadata...\");\n let resourceMetadata: OAuthProtectedResourceMetadata | undefined;\n try {\n // Preserve the exact SDK call arity used by performOAuthFlow when no\n // signal is provided (single-arg form) — some SDKs treat an explicit\n // `undefined` differently from an omitted arg.\n resourceMetadata = fetchFn\n ? await discoverOAuthProtectedResourceMetadata(serverUrl, undefined, fetchFn)\n : await discoverOAuthProtectedResourceMetadata(serverUrl);\n logger?.info(\"Discovered protected resource metadata\", {\n authorizationServers: resourceMetadata?.authorization_servers,\n resource: resourceMetadata?.resource,\n scopesSupported: resourceMetadata?.scopes_supported,\n });\n } catch (err) {\n logger?.warn(\"Could not discover protected resource metadata, will try direct discovery\", {\n error: String(err),\n });\n }\n\n let authServerUrl: URL;\n if (resourceMetadata?.authorization_servers?.length) {\n authServerUrl = new URL(resourceMetadata.authorization_servers[0]);\n logger?.debug(\"Using authorization server from resource metadata\", {\n authServerUrl: authServerUrl.toString(),\n });\n } else {\n authServerUrl = serverUrl;\n logger?.debug(\"Using server URL as authorization server\", {\n authServerUrl: authServerUrl.toString(),\n });\n }\n\n logger?.debug(\"Discovering authorization server metadata...\");\n let authMetadata: Awaited<ReturnType<typeof discoverAuthorizationServerMetadata>>;\n try {\n authMetadata = fetchFn\n ? await discoverAuthorizationServerMetadata(authServerUrl, { fetchFn })\n : await discoverAuthorizationServerMetadata(authServerUrl);\n } catch (err) {\n throw new AuthServerDiscoveryError(authServerUrl, err);\n }\n\n if (authMetadata) {\n logger?.info(\"Discovered authorization server metadata\", {\n authorizationEndpoint: authMetadata.authorization_endpoint,\n issuer: authMetadata.issuer,\n registrationEndpoint: authMetadata.registration_endpoint,\n tokenEndpoint: authMetadata.token_endpoint,\n });\n }\n\n return { authMetadata, authServerUrl, resourceMetadata };\n}\n\n/** Wraps global fetch so the SDK inherits a caller-supplied AbortSignal. */\nfunction signaledFetch(probeSignal: AbortSignal): typeof fetch {\n return (input, init) => {\n const sdkSignal = init?.signal;\n const combined =\n sdkSignal ? AbortSignal.any([probeSignal, sdkSignal]) : probeSignal;\n return fetch(input, { ...init, signal: combined });\n };\n}\n","import {\n discoverAuthorizationServerMetadata,\n discoverOAuthProtectedResourceMetadata,\n exchangeAuthorization,\n extractResourceMetadataUrl,\n refreshAuthorization,\n registerClient,\n startAuthorization,\n} from \"@modelcontextprotocol/sdk/client/auth.js\";\nimport type {\n OAuthClientInformationFull,\n OAuthClientMetadata,\n OAuthProtectedResourceMetadata,\n OAuthTokens,\n} from \"@modelcontextprotocol/sdk/shared/auth.js\";\n\nimport type { OAuthProviderConfig } from \"../config/config.js\";\nimport { config } from \"../config/env.js\";\nimport { logger } from \"../lib/logger.js\";\nimport { normalizeUrl } from \"../utils/normalizeUrl.js\";\nimport { openBrowser } from \"./browser.js\";\nimport { startCallbackServer } from \"./callbackServer.js\";\nimport { AuthServerDiscoveryError, discoverAuthServer } from \"./discovery.js\";\nimport { AuthEventType } from \"./events.js\";\nimport type { OAuthCredentialStore, StoredCredentials } from \"./OAuthCredentialStore.js\";\nimport { findProviderForUrl } from \"./providers.js\";\n\n// Maps CLIENT_APP_NAME (set by the scanner installer per agent) to the\n// human-friendly client_name we present during Dynamic Client Registration.\nconst DCR_CLIENT_NAME_BY_APP: Record<string, string> = {\n \"claude-code\": \"Claude Code (mcp-gateway)\",\n codex: \"Codex\",\n copilot: \"Visual Studio Code\",\n cursor: \"Cursor\",\n opencode: \"OpenCode\",\n};\n\nexport interface OAuthFlowOptions {\n /**\n * Custom client metadata for DCR registration.\n * If not provided, default metadata will be used.\n */\n clientMetadata?: Partial<OAuthClientMetadata>;\n /**\n * Credential store for persisting OAuth credentials.\n * If provided, credentials will be loaded from and saved to disk.\n */\n credentialStore?: OAuthCredentialStore;\n /**\n * OAuth scope to request.\n */\n scope?: string;\n /**\n * Timeout in milliseconds for the OAuth callback.\n * Default: 5 minutes\n */\n timeoutMs?: number;\n}\n\nexport interface OAuthFlowResult {\n clientInfo: OAuthClientInformationFull;\n /**\n * Whether the result came from stored credentials (true) or a fresh OAuth flow (false).\n */\n fromCache?: boolean;\n tokens: OAuthTokens;\n}\n\n/**\n * Attempts to detect if a server requires OAuth by making a test request.\n * Returns the resource metadata URL from the WWW-Authenticate header if OAuth is required.\n *\n * @param serverUrl The MCP server URL to check\n * @returns The resource metadata URL if OAuth is required, undefined otherwise\n */\nexport async function detectOAuthRequirement(serverUrl: string | URL): Promise<undefined | URL> {\n // Normalize URL to avoid redirect issues on Windows\n const normalizedUrl = normalizeUrl(serverUrl);\n const serverUrlObj = new URL(normalizedUrl);\n\n try {\n const response = await fetch(serverUrlObj, {\n headers: {\n Accept: \"application/json\",\n },\n method: \"POST\",\n });\n\n if (response.status === 401) {\n // Check for resource metadata URL in response\n const resourceMetadataUrl = extractResourceMetadataUrl(response);\n if (resourceMetadataUrl) {\n logger.debug(\"OAuth required, found resource metadata URL\", {\n resourceMetadataUrl: resourceMetadataUrl.toString(),\n });\n return resourceMetadataUrl;\n }\n\n // Check WWW-Authenticate header for Bearer realm\n const wwwAuth = response.headers.get(\"WWW-Authenticate\");\n if (wwwAuth && wwwAuth.toLowerCase().includes(\"bearer\")) {\n logger.debug(\"OAuth required based on WWW-Authenticate header\", { wwwAuth });\n return undefined; // OAuth required but no metadata URL\n }\n }\n\n return undefined;\n } catch (err) {\n logger.debug(\"Error detecting OAuth requirement\", { error: String(err) });\n return undefined;\n }\n}\n\n/**\n * Returns the DCR `client_name` to advertise based on the current\n * `CLIENT_APP_NAME` env var. Exported so the probe (`src/probe/index.ts`)\n * can use the exact same value the runtime OAuth flow would send — this is\n * how allowlist-style DCR endpoints (e.g., Figma) get the same answer from\n * both paths, instead of probe seeing `\"MCP Gateway\"` (rejected) while the\n * runtime flow sees the agent-specific name (accepted).\n */\nexport function getDcrClientName(): string {\n return resolveDcrClientName(config.clientAppName);\n}\n\n/**\n * Performs the complete OAuth 2.0 Authorization Code flow with DCR.\n *\n * This function:\n * 1. Checks for existing valid credentials (if credentialStore provided)\n * 2. Attempts token refresh if access token expired (if credentialStore provided)\n * 3. Discovers OAuth protected resource metadata\n * 4. Discovers authorization server metadata\n * 5. Dynamically registers the client (DCR)\n * 6. Opens browser for user authorization\n * 7. Waits for the callback with authorization code\n * 8. Exchanges the code for tokens\n * 9. Persists credentials (if credentialStore provided)\n *\n * @param serverUrl The MCP server URL that requires OAuth\n * @param options Optional configuration\n * @returns The client info and tokens from successful authorization\n */\nexport async function performOAuthFlow(\n serverUrl: string | URL,\n options: OAuthFlowOptions = {}\n): Promise<OAuthFlowResult> {\n const { credentialStore, scope, timeoutMs } = options;\n // Normalize URL to avoid redirect issues on Windows (POST to GET conversion)\n const serverUrlString = normalizeUrl(serverUrl);\n const serverUrlObj = new URL(serverUrlString);\n\n logger.info(\"Starting OAuth flow\", { serverUrl: serverUrlString });\n\n // Step 0: Check for existing valid credentials\n if (credentialStore) {\n const existingCredentials = await tryLoadExistingCredentials(serverUrlObj, credentialStore);\n if (existingCredentials) {\n logger.info(\"Using existing OAuth credentials\", {\n clientId: existingCredentials.clientInfo.client_id,\n serverUrl: serverUrlString,\n });\n return existingCredentials;\n }\n }\n\n // Step 1: Start the callback server to get a dynamic port. Threading\n // serverUrl in lets the callback's error logs carry it for monitoring.\n logger.debug(\"Starting OAuth callback server...\");\n const callbackServer = await startCallbackServer({ serverUrl: serverUrlString, timeoutMs });\n const redirectUrl = callbackServer.callbackUrl;\n\n logger.info(\"OAuth callback server started\", {\n callbackUrl: redirectUrl,\n port: callbackServer.port,\n });\n\n try {\n // Step 2: Check for pre-configured OAuth provider (non-DCR servers)\n const preConfiguredProvider = findProviderForUrl(serverUrlObj);\n\n if (preConfiguredProvider) {\n logger.info(\"Using pre-configured OAuth provider\", {\n providerId: preConfiguredProvider.id,\n providerName: preConfiguredProvider.name,\n });\n\n // Use pre-configured provider flow - pass the callback server instance\n return await performPreConfiguredProviderFlow(\n serverUrlObj,\n preConfiguredProvider,\n callbackServer,\n credentialStore,\n scope\n );\n }\n\n // Steps 3-5: Discover OAuth protected-resource + authorization-server metadata.\n // The helper emits the same debug/info/warn log lines that used to live inline\n // here — passing `logger` preserves the existing observable log output.\n let authMetadata: Awaited<ReturnType<typeof discoverAuthServer>>[\"authMetadata\"];\n let authServerUrl: URL;\n try {\n ({ authMetadata, authServerUrl } = await discoverAuthServer(serverUrlObj, { logger }));\n } catch (err) {\n // AuthServerDiscoveryError carries the chosen authServerUrl. Other\n // errors (rare — only the resource-metadata fetch swallows its own\n // errors) won't have one to attribute, so omit the field.\n logger.error(\"Auth server metadata discovery failed\", {\n error: String(err),\n eventType: AuthEventType.SERVER_METADATA_FAILED,\n serverUrl: serverUrlString,\n ...(err instanceof AuthServerDiscoveryError ? { authServer: err.authServerUrl.toString() } : {}),\n });\n throw err;\n }\n\n if (!authMetadata) {\n logger.error(\"Auth server metadata absent (server may not support OAuth 2.0)\", {\n authServer: authServerUrl.toString(),\n eventType: AuthEventType.SERVER_METADATA_FAILED,\n reason: \"metadata_absent\",\n serverUrl: serverUrlString,\n });\n throw new Error(\n `Could not discover OAuth metadata from ${authServerUrl}. ` +\n `The server may not support OAuth 2.0 or the metadata endpoint is not accessible.`\n );\n }\n\n // Step 6: Check if we have existing client info that can be reused\n let clientInfo: OAuthClientInformationFull;\n const existingCredentials = credentialStore ? await credentialStore.load(serverUrlString) : undefined;\n\n // Check if existing client registration has a matching redirect_uri\n const existingRedirectUris = existingCredentials?.clientInfo?.redirect_uris || [];\n const canReuseClient = existingCredentials?.clientInfo && existingRedirectUris.includes(redirectUrl);\n\n if (canReuseClient && existingCredentials?.clientInfo) {\n // Reuse existing client registration - redirect_uri matches\n logger.info(\"Reusing existing DCR client registration\", {\n clientId: existingCredentials.clientInfo.client_id,\n clientName: existingCredentials.clientInfo.client_name,\n redirectUri: redirectUrl,\n });\n clientInfo = existingCredentials.clientInfo;\n } else {\n // Need to register new client (either no existing client, or redirect_uri doesn't match)\n if (existingCredentials?.clientInfo) {\n logger.info(\"Existing DCR client has different redirect_uri, re-registering\", {\n existingRedirectUris,\n newRedirectUri: redirectUrl,\n });\n }\n\n // Step 6b: Build client metadata for DCR\n const clientMetadata: OAuthClientMetadata = {\n client_name: options.clientMetadata?.client_name || getDcrClientName(),\n grant_types: options.clientMetadata?.grant_types || [\"authorization_code\", \"refresh_token\"],\n redirect_uris: [redirectUrl],\n response_types: options.clientMetadata?.response_types || [\"code\"],\n // Public client - no client secret\n token_endpoint_auth_method: options.clientMetadata?.token_endpoint_auth_method || \"none\",\n ...(scope && { scope }),\n };\n\n logger.debug(\"Client metadata for DCR\", { clientMetadata });\n\n // Step 7: Register client via DCR\n if (!authMetadata.registration_endpoint) {\n logger.error(\"DCR registration unsupported by auth server\", {\n authServer: authServerUrl.toString(),\n eventType: AuthEventType.DCR_FAILED,\n reason: \"no_registration_endpoint\",\n serverUrl: serverUrlString,\n });\n throw new Error(\n `Authorization server does not support Dynamic Client Registration. ` +\n `No registration_endpoint found in metadata.`\n );\n }\n\n logger.info(\"Registering client via DCR...\", {\n registrationEndpoint: authMetadata.registration_endpoint,\n });\n\n try {\n clientInfo = await registerClient(authServerUrl, {\n clientMetadata,\n metadata: authMetadata,\n });\n } catch (err) {\n logger.error(\"DCR registration failed\", {\n authServer: authServerUrl.toString(),\n error: String(err),\n eventType: AuthEventType.DCR_FAILED,\n registrationEndpoint: authMetadata.registration_endpoint,\n serverUrl: serverUrlString,\n });\n throw err;\n }\n\n logger.info(\"Client registered successfully via DCR\", {\n clientId: clientInfo.client_id,\n clientName: clientInfo.client_name,\n clientSecretExpiresAt: clientInfo.client_secret_expires_at,\n });\n\n // Persist the client info immediately\n if (credentialStore) {\n await credentialStore.update(serverUrlString, { clientInfo });\n }\n }\n\n // Step 8: RFC 8707 Resource Indicators\n // NOTE: We intentionally do NOT send the resource parameter. Some OAuth servers (e.g., Notion)\n // ignore the client's requested resource and always issue tokens with their configured default\n // audience. When we then present that token to a different path (e.g., /mcp), the resource\n // server rejects it with \"Token audience does not match resource server\".\n // By omitting the resource parameter entirely, we let the OAuth server use its default\n // behavior, which typically issues tokens that work with the resource server.\n // This matches how Linear works (no protected resource metadata = no resource param sent).\n\n // Step 9: Start authorization flow (generates PKCE challenge)\n // Generate state for CSRF protection — some OAuth servers (e.g., Okta) require it\n const state = crypto.randomUUID();\n logger.debug(\"Starting authorization flow...\");\n const { authorizationUrl, codeVerifier } = await startAuthorization(authServerUrl, {\n clientInformation: clientInfo,\n metadata: authMetadata,\n redirectUrl,\n scope,\n state,\n });\n\n await openBrowser(authorizationUrl);\n\n // Step 11: Wait for callback with authorization code\n logger.debug(\"Waiting for OAuth callback...\");\n const callbackResult = await callbackServer.waitForCallback();\n\n // Verify state matches to prevent CSRF attacks\n if (callbackResult.state !== state) {\n logger.error(\"OAuth state mismatch — possible CSRF attack\", {\n authServer: authServerUrl.toString(),\n eventType: AuthEventType.STATE_MISMATCH,\n serverUrl: serverUrlString,\n });\n throw new Error(\"OAuth state mismatch - possible CSRF attack\");\n }\n\n logger.info(\"Authorization code received\", {\n codePrefix: `${callbackResult.code.substring(0, 10)}...`,\n });\n\n // Step 12: Exchange authorization code for tokens\n logger.debug(\"Exchanging authorization code for tokens...\");\n let tokens;\n try {\n tokens = await exchangeAuthorization(authServerUrl, {\n authorizationCode: callbackResult.code,\n clientInformation: clientInfo,\n codeVerifier,\n metadata: authMetadata,\n redirectUri: redirectUrl,\n });\n } catch (err) {\n logger.error(\"Token exchange failed\", {\n authServer: authServerUrl.toString(),\n clientId: clientInfo.client_id,\n error: String(err),\n eventType: AuthEventType.TOKEN_EXCHANGE_FAILED,\n grantType: \"authorization_code\",\n serverUrl: serverUrlString,\n });\n throw err;\n }\n\n logger.info(\"OAuth tokens obtained successfully\", {\n expiresIn: tokens.expires_in,\n hasRefreshToken: !!tokens.refresh_token,\n tokenType: tokens.token_type,\n });\n\n // Step 13: Persist tokens\n if (credentialStore) {\n const tokensObtainedAt = new Date().toISOString();\n await credentialStore.update(serverUrlString, {\n tokens,\n tokensObtainedAt,\n });\n logger.info(\"OAuth credentials persisted to disk\", { serverUrl: serverUrlString });\n }\n\n return {\n clientInfo,\n fromCache: false,\n tokens,\n };\n } finally {\n // Always close the callback server\n await callbackServer.close();\n }\n}\n\nexport function resolveDcrClientName(rawAppName: null | string | undefined): string {\n const normalized = rawAppName?.trim().toLowerCase();\n if (!normalized) return \"MCP Gateway\";\n return DCR_CLIENT_NAME_BY_APP[normalized] ?? \"MCP Gateway\";\n}\n\n/**\n * Exchanges an authorization code for tokens using a pre-configured provider.\n * Handles different token endpoint authentication methods.\n */\nasync function exchangeCodeForTokens(\n provider: OAuthProviderConfig,\n code: string,\n redirectUri: string,\n codeVerifier?: string\n): Promise<OAuthTokens> {\n const tokenEndpoint = provider.tokenEndpoint;\n const authMethod = provider.tokenEndpointAuthMethod || (provider.clientSecret ? \"client_secret_post\" : \"none\");\n\n // Build token request body\n const body = new URLSearchParams();\n body.set(\"grant_type\", \"authorization_code\");\n body.set(\"code\", code);\n body.set(\"redirect_uri\", redirectUri);\n\n // Add PKCE verifier if present\n if (codeVerifier) {\n body.set(\"code_verifier\", codeVerifier);\n }\n\n // Build request headers\n const headers: Record<string, string> = {\n Accept: \"application/json\",\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n };\n\n // Add client authentication based on method\n if (authMethod === \"client_secret_basic\" && provider.clientSecret) {\n // HTTP Basic authentication\n const credentials = Buffer.from(`${provider.clientId}:${provider.clientSecret}`).toString(\"base64\");\n headers.Authorization = `Basic ${credentials}`;\n } else if (authMethod === \"client_secret_post\" && provider.clientSecret) {\n // Client credentials in POST body\n body.set(\"client_id\", provider.clientId);\n body.set(\"client_secret\", provider.clientSecret);\n } else {\n // Public client - just client_id\n body.set(\"client_id\", provider.clientId);\n }\n\n logger.debug(\"Sending token request\", {\n authMethod,\n providerId: provider.id,\n tokenEndpoint,\n });\n\n const response = await fetch(tokenEndpoint, {\n body: body.toString(),\n headers,\n method: \"POST\",\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n logger.error(\"Token exchange failed\", {\n authMethod,\n error: errorText,\n eventType: AuthEventType.TOKEN_EXCHANGE_FAILED,\n grantType: \"authorization_code\",\n httpStatus: response.status,\n providerId: provider.id,\n tokenEndpoint,\n });\n throw new Error(`Token exchange failed: ${response.status} ${errorText}`);\n }\n\n // GitHub returns tokens as application/x-www-form-urlencoded by default\n // unless Accept: application/json is set\n const contentType = response.headers.get(\"content-type\") || \"\";\n let tokenData: Record<string, unknown>;\n\n if (contentType.includes(\"application/json\")) {\n tokenData = (await response.json()) as Record<string, unknown>;\n } else if (contentType.includes(\"application/x-www-form-urlencoded\") || contentType.includes(\"text/plain\")) {\n // Parse URL-encoded response (GitHub's default format)\n const text = await response.text();\n const params = new URLSearchParams(text);\n tokenData = Object.fromEntries(params.entries()) as Record<string, unknown>;\n } else {\n // Try JSON first, fall back to URL-encoded\n const text = await response.text();\n try {\n tokenData = JSON.parse(text) as Record<string, unknown>;\n } catch {\n const params = new URLSearchParams(text);\n tokenData = Object.fromEntries(params.entries()) as Record<string, unknown>;\n }\n }\n\n // Convert expires_in to number if it's a string\n if (typeof tokenData.expires_in === \"string\") {\n tokenData.expires_in = parseInt(tokenData.expires_in, 10);\n }\n\n return {\n access_token: tokenData.access_token as string,\n expires_in: tokenData.expires_in as number | undefined,\n refresh_token: tokenData.refresh_token as string | undefined,\n scope: tokenData.scope as string | undefined,\n token_type: (tokenData.token_type as string) || \"bearer\",\n };\n}\n\n/**\n * Performs OAuth flow using a pre-configured provider (non-DCR).\n * This is used for OAuth servers that don't support Dynamic Client Registration.\n */\nasync function performPreConfiguredProviderFlow(\n serverUrl: URL,\n provider: OAuthProviderConfig,\n callbackServerInstance: {\n callbackUrl: string;\n close: () => Promise<void>;\n waitForCallback: () => Promise<{ code: string; state?: string }>;\n },\n credentialStore: OAuthCredentialStore | undefined,\n scope: string | undefined\n): Promise<OAuthFlowResult> {\n const serverUrlString = serverUrl.toString();\n const redirectUrl = callbackServerInstance.callbackUrl;\n\n // Build client info from pre-configured provider\n const clientInfo: OAuthClientInformationFull = {\n client_id: provider.clientId,\n client_name: provider.name,\n client_secret: provider.clientSecret,\n redirect_uris: [redirectUrl],\n token_endpoint_auth_method:\n provider.tokenEndpointAuthMethod || (provider.clientSecret ? \"client_secret_post\" : \"none\"),\n };\n\n logger.info(\"Using pre-configured OAuth client\", {\n clientId: provider.clientId,\n hasClientSecret: !!provider.clientSecret,\n providerId: provider.id,\n tokenEndpointAuthMethod: clientInfo.token_endpoint_auth_method,\n });\n\n // Determine scope to use\n const effectiveScope = scope || provider.scopes?.join(\" \");\n\n // Generate PKCE challenge if enabled for this provider\n const usePkce = provider.usePkce !== false; // Default to true unless explicitly disabled\n let codeVerifier: string | undefined;\n let codeChallenge: string | undefined;\n let codeChallengeMethod: string | undefined;\n\n if (usePkce) {\n // Generate PKCE code verifier and challenge\n const { generateCodeChallenge, generateCodeVerifier } = await import(\"./pkce.js\");\n codeVerifier = generateCodeVerifier();\n codeChallenge = await generateCodeChallenge(codeVerifier);\n codeChallengeMethod = \"S256\";\n }\n\n // Build authorization URL manually\n const authUrl = new URL(provider.authorizationEndpoint);\n authUrl.searchParams.set(\"client_id\", provider.clientId);\n authUrl.searchParams.set(\"redirect_uri\", redirectUrl);\n authUrl.searchParams.set(\"response_type\", \"code\");\n\n if (effectiveScope) {\n authUrl.searchParams.set(\"scope\", effectiveScope);\n }\n\n // Add state for security\n const state = crypto.randomUUID();\n authUrl.searchParams.set(\"state\", state);\n\n // Add PKCE challenge if enabled\n if (codeChallenge && codeChallengeMethod) {\n authUrl.searchParams.set(\"code_challenge\", codeChallenge);\n authUrl.searchParams.set(\"code_challenge_method\", codeChallengeMethod);\n }\n\n await openBrowser(authUrl);\n\n // Wait for callback on the existing callback server\n logger.debug(\"Waiting for OAuth callback...\");\n const callbackResult = await callbackServerInstance.waitForCallback();\n\n // Verify state matches\n if (callbackResult.state !== state) {\n logger.error(\"OAuth state mismatch — possible CSRF attack\", {\n eventType: AuthEventType.STATE_MISMATCH,\n providerId: provider.id,\n serverUrl: serverUrlString,\n });\n throw new Error(\"OAuth state mismatch - possible CSRF attack\");\n }\n\n logger.info(\"Authorization code received\", {\n codePrefix: `${callbackResult.code.substring(0, 10)}...`,\n providerId: provider.id,\n });\n\n // Exchange authorization code for tokens\n logger.debug(\"Exchanging authorization code for tokens...\");\n const tokens = await exchangeCodeForTokens(provider, callbackResult.code, redirectUrl, codeVerifier);\n\n logger.info(\"OAuth tokens obtained successfully\", {\n expiresIn: tokens.expires_in,\n hasRefreshToken: !!tokens.refresh_token,\n providerId: provider.id,\n tokenType: tokens.token_type,\n });\n\n // Persist credentials\n if (credentialStore) {\n const tokensObtainedAt = new Date().toISOString();\n await credentialStore.update(serverUrlString, {\n clientInfo,\n tokens,\n tokensObtainedAt,\n });\n logger.info(\"OAuth credentials persisted to disk\", {\n providerId: provider.id,\n serverUrl: serverUrlString,\n });\n }\n\n return {\n clientInfo,\n fromCache: false,\n tokens,\n };\n}\n\n/**\n * Checks for existing valid credentials and returns them if available.\n * Handles token refresh if the access token is expired but refresh token exists.\n */\nasync function tryLoadExistingCredentials(\n serverUrl: URL,\n credentialStore: OAuthCredentialStore\n): Promise<OAuthFlowResult | undefined> {\n const credentials = await credentialStore.load(serverUrl.toString());\n\n if (!credentials) {\n logger.debug(\"No stored credentials found\", { serverUrl: serverUrl.toString() });\n return undefined;\n }\n\n if (!credentials.clientInfo) {\n logger.debug(\"Stored credentials have no client info\", { serverUrl: serverUrl.toString() });\n return undefined;\n }\n\n // Check if we have a valid access token\n if (credentialStore.hasValidAccessToken(credentials) && credentials.tokens) {\n logger.info(\"Using cached OAuth credentials with valid access token\", {\n clientId: credentials.clientInfo.client_id,\n serverUrl: serverUrl.toString(),\n });\n\n return {\n clientInfo: credentials.clientInfo,\n fromCache: true,\n tokens: credentials.tokens,\n };\n }\n\n // Access token is expired or missing, try to refresh\n if (credentialStore.hasRefreshToken(credentials)) {\n const refreshResult = await tryRefreshToken(serverUrl, credentials, credentialStore);\n if (refreshResult) {\n return refreshResult;\n }\n }\n\n logger.debug(\"Stored credentials are expired and no valid refresh token\", {\n serverUrl: serverUrl.toString(),\n });\n\n return undefined;\n}\n\n/**\n * Attempts to refresh an expired access token using the refresh token.\n * Returns new tokens if successful, undefined if refresh fails.\n */\nasync function tryRefreshToken(\n serverUrl: URL,\n credentials: StoredCredentials,\n credentialStore: OAuthCredentialStore\n): Promise<OAuthFlowResult | undefined> {\n if (!credentials.clientInfo || !credentials.tokens?.refresh_token) {\n return undefined;\n }\n\n logger.info(\"Attempting to refresh expired access token\", {\n clientId: credentials.clientInfo.client_id,\n serverUrl: serverUrl.toString(),\n });\n\n try {\n // Discover authorization server metadata\n let resourceMetadata: OAuthProtectedResourceMetadata | undefined;\n try {\n resourceMetadata = await discoverOAuthProtectedResourceMetadata(serverUrl);\n } catch {\n // Continue without resource metadata\n }\n\n let authServerUrl: URL;\n if (resourceMetadata?.authorization_servers?.length) {\n authServerUrl = new URL(resourceMetadata.authorization_servers[0]);\n } else {\n authServerUrl = serverUrl;\n }\n\n const authMetadata = await discoverAuthorizationServerMetadata(authServerUrl);\n // NOTE: We don't send the resource parameter (same reasoning as in performOAuthFlow)\n\n // Attempt token refresh\n const newTokens = await refreshAuthorization(authServerUrl, {\n clientInformation: credentials.clientInfo,\n metadata: authMetadata,\n refreshToken: credentials.tokens.refresh_token,\n });\n\n logger.info(\"Successfully refreshed access token\", {\n clientId: credentials.clientInfo.client_id,\n expiresIn: newTokens.expires_in,\n hasNewRefreshToken: !!newTokens.refresh_token,\n });\n\n // Persist the new tokens\n const tokensObtainedAt = new Date().toISOString();\n await credentialStore.update(serverUrl.toString(), {\n tokens: newTokens,\n tokensObtainedAt,\n });\n\n return {\n clientInfo: credentials.clientInfo,\n fromCache: true,\n tokens: newTokens,\n };\n } catch (error) {\n logger.warn(\"Failed to refresh access token, will require re-authorization\", {\n clientId: credentials.clientInfo.client_id,\n error: String(error),\n eventType: AuthEventType.REFRESH_FAILED,\n serverUrl: serverUrl.toString(),\n });\n\n // Invalidate the tokens but keep the client info\n await credentialStore.update(serverUrl.toString(), {\n tokens: undefined,\n tokensObtainedAt: undefined,\n });\n\n return undefined;\n }\n}\n","/**\n * MCP Transport Utilities\n *\n * Simple transport creation for remote MCP servers.\n * Transport type is determined by trying Streamable HTTP first,\n * falling back to SSE if the endpoint doesn't support it.\n */\n\nimport type { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport { SSEClientTransport } from \"@modelcontextprotocol/sdk/client/sse.js\";\nimport { StreamableHTTPClientTransport } from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\n\nimport { logger } from \"./logger.js\";\n\nexport type TransportType = \"sse\" | \"streamable-http\";\n\n/** Order in which transports are tried (per MCP spec: Streamable HTTP first, SSE fallback) */\nconst TRANSPORT_PRIORITY: TransportType[] = [\"streamable-http\", \"sse\"];\n\n/** Result of a successful transport connection */\nexport interface TransportConnectionResult {\n /** The connected client instance */\n client: Client;\n /** The transport type that successfully connected */\n transportType: TransportType;\n}\n\n/**\n * Connects to a remote MCP server, trying transports in order.\n * Per MCP spec: tries Streamable HTTP first, falls back to SSE if not supported (404/405).\n *\n * Creates a fresh client for each transport attempt to avoid state issues.\n * The MCP SDK Client maintains internal connection state that does not properly\n * reset after a failed connect attempt, so reusing the same client instance\n * across transport fallbacks can cause \"already connected\" or similar errors.\n *\n * @param createClient - Factory function to create a new Client instance\n * @param url - The URL of the remote MCP server\n * @param requestInit - Optional request init for the transport (headers, etc.)\n * @returns The connected client and transport type\n * @throws The error from the last transport attempt if none succeed,\n * or immediately if an error is not a \"transport not supported\" error\n */\nexport async function connectWithTransportFallback(\n createClient: () => Client,\n url: string,\n requestInit?: RequestInit\n): Promise<TransportConnectionResult> {\n const { result: client, transportType } = await walkTransports(async (transportType) => {\n // Create a fresh client for each transport attempt to avoid state issues\n const client = createClient();\n const transport = createTransport(url, transportType, requestInit);\n await client.connect(transport);\n return client;\n });\n return { client, transportType };\n}\n\n/**\n * Creates a transport instance for the given type.\n */\nexport function createTransport(\n url: string,\n type: TransportType,\n requestInit?: RequestInit\n): SSEClientTransport | StreamableHTTPClientTransport {\n const parsedUrl = new URL(url);\n\n if (type === \"streamable-http\") {\n return new StreamableHTTPClientTransport(parsedUrl, { requestInit });\n }\n\n return new SSEClientTransport(parsedUrl, { requestInit });\n}\n\n/**\n * Checks if an error indicates the transport/endpoint is not supported (404/405).\n * This means we should try a different transport type.\n */\nexport function isTransportNotSupportedError(err: unknown): boolean {\n if (!err || typeof err !== \"object\") return false;\n\n const status = (err as { status?: number }).status;\n const code = (err as { code?: number }).code;\n const message = (err as { message?: string }).message;\n\n // Check status codes that indicate endpoint doesn't support this transport\n if (status === 404 || status === 405 || code === 404 || code === 405) {\n return true;\n }\n\n // Check error message for these status codes\n if (message && /404|not found|405|method not allowed/i.test(String(message))) {\n return true;\n }\n\n return false;\n}\n\n/**\n * Walks transports in priority order, calling `attempt` for each. Returns the\n * first successful result. Continues to the next transport on\n * `isTransportNotSupportedError` (404/405); propagates any other error.\n *\n * Shared primitive for both connect-style attempts (the runtime proxy via\n * `connectWithTransportFallback`) and probe-style attempts (the install-time\n * scan in `src/probe`). Callers supply the per-transport request shape; this\n * helper owns only the priority-order + fallback-on-404/405 logic.\n *\n * When every transport fails with a not-supported error, throws an aggregate\n * error whose message lists each transport's status — so callers can tell\n * \"URL is dead\" from \"URL only speaks one transport\". The original errors are\n * available via `error.cause` (an array of `{ transport, err }`).\n *\n * @param attempt - Per-transport function. Throw an error matching\n * `isTransportNotSupportedError` to trigger fallback; throw anything else\n * (or any one transport's non-fallback error) to propagate.\n * @returns The first transport that succeeded and its result.\n * @throws The propagated non-fallback error, or an aggregate of every\n * transport's not-supported error when all transports fail.\n */\nexport async function walkTransports<T>(\n attempt: (transportType: TransportType) => Promise<T>\n): Promise<{ result: T; transportType: TransportType }> {\n const failures: Array<{ err: unknown; transport: TransportType }> = [];\n\n for (const transportType of TRANSPORT_PRIORITY) {\n try {\n const result = await attempt(transportType);\n return { result, transportType };\n } catch (err) {\n if (isTransportNotSupportedError(err)) {\n logger.info(`${transportType} not supported, trying next transport...`);\n failures.push({ err, transport: transportType });\n continue;\n }\n\n // Non-transport error (e.g., 401, network error) - propagate immediately\n throw err;\n }\n }\n\n // All transports failed with \"not supported\" errors. Build a message that\n // lists every transport's status (or message), so callers don't see only\n // the last transport's failure and assume the others were never tried.\n const summary = failures\n .map(({ err, transport }) => {\n const status = (err as { status?: number } | null)?.status;\n if (status !== undefined) return `${transport}: ${status}`;\n const message = err instanceof Error ? err.message : String(err);\n return `${transport}: ${message}`;\n })\n .join(\", \");\n const aggregate =\n failures.length > 0\n ? new Error(`all transports returned not-supported (${summary})`)\n : new Error(\"No compatible transport found\");\n // Preserve original errors for callers that need to introspect them.\n (aggregate as { cause?: unknown } & Error).cause = failures;\n throw aggregate;\n}\n"],"mappings":"0lBAgBA,eAAsB,EAAY,EAAkC,CAClE,IAAM,EAAY,EAAI,UAAU,CAC1B,EAAK,GAAU,CACf,EAAc,EAAoB,EAAU,CAElD,OAAO,IAAI,SAAS,EAAS,IAAW,CACtC,IAAIA,EACAC,EAEJ,GAAI,IAAO,QAAS,CAIlB,IAAM,EAAY,iBAAiB,EAAyB,EAAU,GAChE,EAAiB,EAAwB,EAAU,CAEzD,EAAU,GAAmB,CAC7B,EAAO,CAAC,aAAc,kBAAmB,mBAAoB,SAAU,kBAAmB,EAAe,MAChG,IAAO,UAEhB,EAAU,OACV,EAAO,CAAC,EAAU,GAGlB,EAAU,WACV,EAAO,CAAC,EAAU,EAGpB,EAAS,EAAS,GAAO,EAAO,EAAS,IAAW,CAClD,GAAI,EAAO,CACT,IAAM,EAAe,CACnB,UACA,KACA,SACA,IAAK,EACN,CAED,EAAO,KAAK,uCAAwC,CAClD,GAAG,EACH,MAAO,EAAM,QACd,CAAC,CAEF,IAAM,EAAkB,MACtB,2BAA2B,EAAM,QAAQ,aAAa,EAAQ,QAAQ,EAAG,SAAS,EAAY,GAC/F,CACD,EAAY,MAAQ,EACpB,EAAO,EAAY,MAEnB,EAAO,MAAM,8BAA+B,CAAE,IAAK,EAAa,CAAC,CACjE,GAAS,EAEX,EACF,CAQJ,SAAS,EAAwB,EAAyB,CAGxD,OADe,OAAO,KAAK,EAAS,UAAU,CAChC,SAAS,SAAS,CAOlC,SAAS,EAAyB,EAAuB,CACvD,MAAO,IAAI,EAAM,WAAW,IAAK,KAAK,CAAC,GAOzC,SAAS,GAA4B,CAEnC,MAAO,GADY,QAAQ,IAAI,YAAc,QAAQ,IAAI,QAAU,cAC9C,qDAUvB,SAAS,EAAoB,EAAqB,CAChD,GAAI,CACF,IAAM,EAAS,IAAI,IAAI,EAAI,CAI3B,OAHI,EAAO,OACF,GAAG,EA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4
4
  "main": "dist/index.js",
5
5
  "scripts": {
6
6
  "prebuild": "npx tsx scripts/generate-config.ts",
@@ -1,142 +0,0 @@
1
- import{AccessControlBlockError as e,BUILD_TIME_CONFIG as t,Client as n,ConfigurationError as r,ProxyConnectionError as i,ReadBuffer as a,SSEClientTransport as o,Server as s,StdioServerTransport as c,StreamableHTTPClientTransport as l,UnauthorizedError as u,chownToRealUser as d,compressClientInfo as f,config as p,createParser as m,discoverAuthorizationServerMetadata as h,discoverOAuthProtectedResourceMetadata as g,exchangeAuthorization as _,extractTraceIdFromHeaders as ee,flushLogs as v,getSessionData as y,initializeTrafficMirror as b,logRequestCounts as te,logger as x,normalizeUrl as S,proxyServer as ne,refreshAuthorization as C,registerClient as w,serializeMessage as T,startAuthorization as re,startHTTPServer as ie}from"./normalizeUrl-Cni_Rjv3.js";import{emitProxySetupLog as ae,hideBin as oe,yargs_default as se}from"./helpers-Cwd-UJrA.js";import"./pkce-ANRIC6ce.js";import{createHash as E}from"node:crypto";import{join as D}from"node:path";import{platform as O}from"node:os";import{chmod as k,mkdir as ce,readFile as le,rm as ue,writeFile as de}from"node:fs/promises";import{createServer as fe}from"node:http";import{StringDecoder as pe}from"node:string_decoder";import{setTimeout as me}from"node:timers";import he from"node:util";import{execFile as ge,execSync as _e,spawn as ve,spawnSync as ye}from"node:child_process";import{URL as be}from"node:url";import{PassThrough as xe,Transform as Se}from"node:stream";var Ce=class extends Event{constructor(e,t){super(e),this.code=t?.code??void 0,this.message=t?.message??void 0}[Symbol.for(`nodejs.util.inspect.custom`)](e,t,n){return n(Te(this),t)}[Symbol.for(`Deno.customInspect`)](e,t){return e(Te(this),t)}};function we(e){let t=globalThis.DOMException;return typeof t==`function`?new t(e,`SyntaxError`):SyntaxError(e)}function A(e){return e instanceof Error?`errors`in e&&Array.isArray(e.errors)?e.errors.map(A).join(`, `):`cause`in e&&e.cause instanceof Error?`${e}: ${A(e.cause)}`:e.message:`${e}`}function Te(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}var Ee=e=>{throw TypeError(e)},j=(e,t,n)=>t.has(e)||Ee(`Cannot `+n),M=(e,t,n)=>(j(e,t,`read from private field`),n?n.call(e):t.get(e)),N=(e,t,n)=>t.has(e)?Ee(`Cannot add the same private member more than once`):t instanceof WeakSet?t.add(e):t.set(e,n),P=(e,t,n,r)=>(j(e,t,`write to private field`),t.set(e,n),n),F=(e,t,n)=>(j(e,t,`access private method`),n),I,L,R,z,B,V,H,U,W,G,K,q,J,Y,X,Z,De,Oe,ke,Ae,Q,je,Me,$=class extends EventTarget{constructor(e,t){super(),N(this,Y),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,N(this,I),N(this,L),N(this,R),N(this,z),N(this,B),N(this,V),N(this,H),N(this,U,null),N(this,W),N(this,G),N(this,K,null),N(this,q,null),N(this,J,null),N(this,Z,async e=>{var t;M(this,G).reset();let{body:n,redirected:r,status:i,headers:a}=e;if(i===204){F(this,Y,Q).call(this,`Server sent HTTP 204, not reconnecting`,204),this.close();return}if(r?P(this,R,new URL(e.url)):P(this,R,void 0),i!==200){F(this,Y,Q).call(this,`Non-200 status code (${i})`,i);return}if(!(a.get(`content-type`)||``).startsWith(`text/event-stream`)){F(this,Y,Q).call(this,`Invalid content type, expected "text/event-stream"`,i);return}if(M(this,I)===this.CLOSED)return;P(this,I,this.OPEN);let o=new Event(`open`);if((t=M(this,J))==null||t.call(this,o),this.dispatchEvent(o),typeof n!=`object`||!n||!(`getReader`in n)){F(this,Y,Q).call(this,`Invalid response body, expected a web ReadableStream`,i),this.close();return}let s=new TextDecoder,c=n.getReader(),l=!0;do{let{done:e,value:t}=await c.read();t&&M(this,G).feed(s.decode(t,{stream:!e})),e&&(l=!1,M(this,G).reset(),F(this,Y,je).call(this))}while(l)}),N(this,De,e=>{P(this,W,void 0),!(e.name===`AbortError`||e.type===`aborted`)&&F(this,Y,je).call(this,A(e))}),N(this,ke,e=>{typeof e.id==`string`&&P(this,U,e.id);let t=new MessageEvent(e.event||`message`,{data:e.data,origin:M(this,R)?M(this,R).origin:M(this,L).origin,lastEventId:e.id||``});M(this,q)&&(!e.event||e.event===`message`)&&M(this,q).call(this,t),this.dispatchEvent(t)}),N(this,Ae,e=>{P(this,V,e)}),N(this,Me,()=>{P(this,H,void 0),M(this,I)===this.CONNECTING&&F(this,Y,X).call(this)});try{if(e instanceof URL)P(this,L,e);else if(typeof e==`string`)P(this,L,new URL(e,Ne()));else throw Error(`Invalid URL`)}catch{throw we(`An invalid or illegal string was specified`)}P(this,G,m({onEvent:M(this,ke),onRetry:M(this,Ae)})),P(this,I,this.CONNECTING),P(this,V,3e3),P(this,B,t?.fetch??globalThis.fetch),P(this,z,t?.withCredentials??!1),F(this,Y,X).call(this)}get readyState(){return M(this,I)}get url(){return M(this,L).href}get withCredentials(){return M(this,z)}get onerror(){return M(this,K)}set onerror(e){P(this,K,e)}get onmessage(){return M(this,q)}set onmessage(e){P(this,q,e)}get onopen(){return M(this,J)}set onopen(e){P(this,J,e)}addEventListener(e,t,n){let r=t;super.addEventListener(e,r,n)}removeEventListener(e,t,n){let r=t;super.removeEventListener(e,r,n)}close(){M(this,H)&&clearTimeout(M(this,H)),M(this,I)!==this.CLOSED&&(M(this,W)&&M(this,W).abort(),P(this,I,this.CLOSED),P(this,W,void 0))}};I=new WeakMap,L=new WeakMap,R=new WeakMap,z=new WeakMap,B=new WeakMap,V=new WeakMap,H=new WeakMap,U=new WeakMap,W=new WeakMap,G=new WeakMap,K=new WeakMap,q=new WeakMap,J=new WeakMap,Y=new WeakSet,X=function(){P(this,I,this.CONNECTING),P(this,W,new AbortController),M(this,B)(M(this,L),F(this,Y,Oe).call(this)).then(M(this,Z)).catch(M(this,De))},Z=new WeakMap,De=new WeakMap,Oe=function(){let e={mode:`cors`,redirect:`follow`,headers:{Accept:`text/event-stream`,...M(this,U)?{"Last-Event-ID":M(this,U)}:void 0},cache:`no-store`,signal:M(this,W)?.signal};return`window`in globalThis&&(e.credentials=this.withCredentials?`include`:`same-origin`),e},ke=new WeakMap,Ae=new WeakMap,Q=function(e,t){var n;M(this,I)!==this.CLOSED&&P(this,I,this.CLOSED);let r=new Ce(`error`,{code:t,message:e});(n=M(this,K))==null||n.call(this,r),this.dispatchEvent(r)},je=function(e,t){var n;if(M(this,I)===this.CLOSED)return;P(this,I,this.CONNECTING);let r=new Ce(`error`,{code:t,message:e});(n=M(this,K))==null||n.call(this,r),this.dispatchEvent(r),P(this,H,setTimeout(M(this,Me),M(this,V)))},Me=new WeakMap,$.CONNECTING=0,$.OPEN=1,$.CLOSED=2;function Ne(){let e=`document`in globalThis?globalThis.document:void 0;return e&&typeof e==`object`&&`baseURI`in e&&typeof e.baseURI==`string`?e.baseURI:void 0}var Pe=class{client;enabled;lastBlockReason;serverName;constructor(e){this.enabled=e.enabled,this.client=e.client,this.serverName=e.serverName,x.info(`AccessControlAuthorizer initialized`,{enabled:this.enabled,hasClient:!!this.client,serverName:this.serverName})}getBlockReason(){return this.lastBlockReason?this.lastBlockReason:`MCP server${this.serverName?` '${this.serverName}'`:``} is not authorized for use in your organization and has been blocked by Onyx.`}async isAllowed(){if(!this.enabled)return!0;if(this.client)try{let e=await this.client.authorize();return e.action===`block`?(e.reason?this.lastBlockReason=e.reason:this.lastBlockReason=`MCP server${this.serverName?` '${this.serverName}'`:``} is not authorized for use in your organization and has been blocked by Onyx.`,!1):!0}catch(e){return x.error(`Access control authorization failed with unexpected error`,{error:String(e)}),!0}return x.warn(`No access control client configured, allowing by default`),!0}},Fe=class{clientInfoBase64;config;constructor(e){this.config=e,this.clientInfoBase64=this.getClientInfoBase64(),x.info(`AccessControlClient initialized`,{timeoutMs:e.timeoutMs,url:e.url})}async authorize(){try{let e=await this.sendAuthorizeRequest();return x.debug(`Access control check successful`,{action:e.action}),e}catch(e){return x.warn(`Access control check failed, failing open (allowing by default)`,{error:String(e)}),{action:`allow`}}}getClientInfoBase64(){return f(this.config.sessionData)}async sendAuthorizeRequest(){let e=new AbortController,t=setTimeout(()=>e.abort(),this.config.timeoutMs);try{let t=`${this.config.url}/${this.config.apiKey}/mcp/${this.clientInfoBase64}`,n=await fetch(t,{headers:{...this.config.headers},method:`POST`,signal:e.signal});if(!n.ok)throw Error(`Access control service returned ${n.status}: ${n.statusText}`);let r=await n.json();if(!r.action||![`allow`,`block`].includes(r.action))throw Error(`Invalid access control response format: action="${r.action}"`);return r}catch(e){throw e instanceof Error&&e.name===`AbortError`?Error(`Access control check timed out after ${this.config.timeoutMs}ms`):e}finally{clearTimeout(t)}}};async function Ie(e){let t=e.toString(),n=O(),r=Be(t);return new Promise((e,i)=>{let a,o;if(n===`win32`){let e=`Start-Process ${Re(t)}`,n=Le(e);a=ze(),o=[`-NoProfile`,`-NonInteractive`,`-ExecutionPolicy`,`Bypass`,`-EncodedCommand`,n]}else n===`darwin`?(a=`open`,o=[t]):(a=`xdg-open`,o=[t]);ge(a,o,(t,o,s)=>{if(t){let e={command:a,os:n,stderr:s,url:r};x.warn(`Failed to open browser automatically`,{...e,error:t.message});let o=Error(`Failed to open browser: ${t.message} (command: ${a}, os: ${n}, url: ${r})`);o.cause=t,i(o)}else x.debug(`Browser opened successfully`,{url:r}),e()})})}function Le(e){return Buffer.from(e,`utf16le`).toString(`base64`)}function Re(e){return`'${e.replaceAll(`'`,`''`)}'`}function ze(){return`${process.env.SYSTEMROOT||process.env.windir||`C:\\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`}function Be(e){try{let t=new URL(e);return t.search?`${t.protocol}//${t.host}${t.pathname}?[REDACTED]`:`${t.protocol}//${t.host}${t.pathname}`}catch{return`[INVALID_URL]`}}const Ve=49152;function He(){return Math.floor(Math.random()*(65535-Ve+1))+Ve}function Ue(e,t){return new Promise((n,r)=>{let i=t=>{e.removeListener(`listening`,a),r(t)},a=()=>{e.removeListener(`error`,i),n()};e.once(`error`,i),e.once(`listening`,a),e.listen(t,`127.0.0.1`)})}async function We(e={}){let{maxAttempts:t=5,preferredPort:n,timeoutMs:r=3e5}=e,i,a,o={},s=new Promise((e,t)=>{i=e,a=t}),c,l=fe((e,t)=>{if(e.url===`/favicon.ico`){t.writeHead(404),t.end();return}if(!e.url?.startsWith(`/callback`)){t.writeHead(404),t.end(`Not Found`);return}try{let n=new be(e.url,`http://localhost:${c}`),r=n.searchParams.get(`code`),s=n.searchParams.get(`error`),u=n.searchParams.get(`error_description`),d=n.searchParams.get(`state`);if(s){x.error(`OAuth authorization error`,{error:s,errorDescription:u}),t.writeHead(400,{"Content-Type":`text/html`}),t.end(Ke(s,u||void 0)),clearTimeout(o.id),a(Error(`OAuth authorization failed: ${s}${u?` - ${u}`:``}`));return}if(!r){x.error(`OAuth callback missing authorization code`),t.writeHead(400,{"Content-Type":`text/html`}),t.end(Ke(`missing_code`,`No authorization code was provided`)),clearTimeout(o.id),a(Error(`OAuth callback missing authorization code`));return}x.info(`OAuth authorization code received`,{codePrefix:`${r.substring(0,10)}...`,hasState:!!d}),t.writeHead(200,{"Content-Type":`text/html`}),t.end(`<!DOCTYPE html>
2
- <html lang="en">
3
- <head>
4
- <meta charset="UTF-8">
5
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
- <title>Authorization Successful</title>
7
- <style>
8
- body {
9
- font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
10
- display: flex;
11
- justify-content: center;
12
- align-items: center;
13
- min-height: 100vh;
14
- margin: 0;
15
- background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
16
- color: #fff;
17
- }
18
- .container {
19
- text-align: center;
20
- padding: 2rem;
21
- }
22
- .checkmark {
23
- width: 80px;
24
- height: 80px;
25
- border-radius: 50%;
26
- background: #10b981;
27
- display: flex;
28
- align-items: center;
29
- justify-content: center;
30
- margin: 0 auto 1.5rem;
31
- animation: pop 0.3s ease-out;
32
- }
33
- .checkmark svg {
34
- width: 40px;
35
- height: 40px;
36
- stroke: white;
37
- stroke-width: 3;
38
- }
39
- h1 {
40
- margin: 0 0 0.5rem;
41
- font-size: 1.75rem;
42
- font-weight: 600;
43
- }
44
- p {
45
- margin: 0;
46
- color: #a0aec0;
47
- font-size: 1rem;
48
- }
49
- @keyframes pop {
50
- 0% { transform: scale(0); }
51
- 50% { transform: scale(1.1); }
52
- 100% { transform: scale(1); }
53
- }
54
- </style>
55
- </head>
56
- <body>
57
- <div class="container">
58
- <div class="checkmark">
59
- <svg viewBox="0 0 24 24" fill="none">
60
- <path d="M5 13l4 4L19 7" stroke-linecap="round" stroke-linejoin="round"/>
61
- </svg>
62
- </div>
63
- <h1>Authorization Successful</h1>
64
- <p>You can close this window and return to the terminal.</p>
65
- </div>
66
- <script>setTimeout(() => window.close(), 3000);<\/script>
67
- </body>
68
- </html>`),clearTimeout(o.id),i({code:r,state:d||void 0}),setTimeout(()=>l.close(),1e3)}catch(e){x.error(`Error processing OAuth callback`,{error:String(e)}),t.writeHead(500),t.end(`Internal Server Error`),clearTimeout(o.id),a(e instanceof Error?e:Error(String(e)))}});o.id=setTimeout(()=>{a(Error(`OAuth callback timeout after ${r}ms`)),l.close()},r);let u=[],d;for(;u.length<t;){let e;if(u.length===0&&n!==void 0)e=n;else for(e=He();u.includes(e);)e=He();u.push(e);try{await Ue(l,e),c=e;let t=`http://localhost:${c}/callback`;return x.info(`OAuth callback server started`,{attempt:u.length,callbackUrl:t,port:c}),{callbackUrl:t,close:()=>new Promise(e=>{clearTimeout(o.id),l.close(()=>e())}),port:c,waitForCallback:()=>s}}catch(n){if(n.code===`EADDRINUSE`)x.debug(`Port in use, trying another port`,{attempt:u.length,maxAttempts:t,port:e}),d=Error(`Port ${e} is already in use`);else throw clearTimeout(o.id),l.close(),n}}throw clearTimeout(o.id),l.close(),Error(`Failed to start OAuth callback server after ${t} attempts. Tried ports: ${u.join(`, `)}. Last error: ${d?.message||`unknown`}`)}function Ge(e){return e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`).replace(/"/g,`&quot;`).replace(/'/g,`&#039;`)}function Ke(e,t){return`<!DOCTYPE html>
69
- <html lang="en">
70
- <head>
71
- <meta charset="UTF-8">
72
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
73
- <title>Authorization Failed</title>
74
- <style>
75
- body {
76
- font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
77
- display: flex;
78
- justify-content: center;
79
- align-items: center;
80
- min-height: 100vh;
81
- margin: 0;
82
- background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
83
- color: #fff;
84
- }
85
- .container {
86
- text-align: center;
87
- padding: 2rem;
88
- max-width: 400px;
89
- }
90
- .error-icon {
91
- width: 80px;
92
- height: 80px;
93
- border-radius: 50%;
94
- background: #ef4444;
95
- display: flex;
96
- align-items: center;
97
- justify-content: center;
98
- margin: 0 auto 1.5rem;
99
- }
100
- .error-icon svg {
101
- width: 40px;
102
- height: 40px;
103
- stroke: white;
104
- stroke-width: 3;
105
- }
106
- h1 {
107
- margin: 0 0 0.5rem;
108
- font-size: 1.75rem;
109
- font-weight: 600;
110
- }
111
- .error-code {
112
- color: #f87171;
113
- font-family: monospace;
114
- margin-bottom: 0.5rem;
115
- }
116
- p {
117
- margin: 0;
118
- color: #a0aec0;
119
- font-size: 1rem;
120
- }
121
- </style>
122
- </head>
123
- <body>
124
- <div class="container">
125
- <div class="error-icon">
126
- <svg viewBox="0 0 24 24" fill="none">
127
- <path d="M6 18L18 6M6 6l12 12" stroke-linecap="round" stroke-linejoin="round"/>
128
- </svg>
129
- </div>
130
- <h1>Authorization Failed</h1>
131
- <p class="error-code">${Ge(e)}</p>
132
- ${t?`<p>${Ge(t)}</p>`:``}
133
- </div>
134
- </body>
135
- </html>`}var qe=class{storageDir;constructor(e){this.storageDir=e.storageDir}async delete(e){let t=S(e),n=this.getFilePath(t);try{await ue(n),x.debug(`Deleted stored credentials`,{filePath:n,serverUrl:t})}catch(e){e.code!==`ENOENT`&&x.warn(`Failed to delete stored credentials`,{error:String(e),filePath:n,serverUrl:t})}}hasRefreshToken(e){return!!e.tokens?.refresh_token}hasValidAccessToken(e){return!!e.tokens?.access_token&&!this.isAccessTokenExpired(e)}isAccessTokenExpired(e){if(!e.tokens||!e.tokensObtainedAt)return!0;let{expires_in:t}=e.tokens;if(!t)return!1;let n=new Date(e.tokensObtainedAt).getTime()+t*1e3,r=Date.now(),i=r>=n-3e4;return x.debug(`Checked access token expiration`,{expiresAt:new Date(n).toISOString(),expiresIn:t,isExpired:i,now:new Date(r).toISOString(),obtainedAt:e.tokensObtainedAt}),i}async load(e){let t=S(e),n=this.getFilePath(t);try{let e=await le(n,`utf-8`),r=JSON.parse(e);if(S(r.serverUrl)!==t){x.warn(`Credential file server URL mismatch`,{expected:t,filePath:n,found:r.serverUrl});return}return x.debug(`Loaded stored credentials`,{clientId:r.clientInfo?.client_id,hasRefreshToken:!!r.tokens?.refresh_token,hasTokens:!!r.tokens,serverUrl:t}),r}catch(e){if(e.code===`ENOENT`){x.debug(`No stored credentials found`,{serverUrl:t});return}x.warn(`Failed to load stored credentials`,{error:String(e),filePath:n,serverUrl:t});return}}async save(e){await this.ensureStorageDir();let t=this.getFilePath(e.serverUrl),n=JSON.stringify(e,null,2);try{await de(t,n,{encoding:`utf-8`,mode:384}),await k(t,384),x.debug(`Saved credentials to disk`,{clientId:e.clientInfo?.client_id,filePath:t,hasTokens:!!e.tokens,serverUrl:e.serverUrl})}catch(n){throw x.error(`Failed to save credentials`,{error:String(n),filePath:t,serverUrl:e.serverUrl}),n}}async update(e,t){let n=S(e),r=await this.load(n),i=new Date().toISOString(),a=r?{...r,...t,serverUrl:n,updatedAt:i}:{createdAt:i,serverUrl:n,updatedAt:i,...t};return await this.save(a),a}async ensureStorageDir(){try{await ce(this.storageDir,{mode:448,recursive:!0})}catch(e){if(e.code!==`EEXIST`)throw e}try{await d(this.storageDir)}catch(e){x.warn(`Failed to fix OAuth storage directory ownership`,{error:String(e),storageDir:this.storageDir})}}generateKey(e){return E(`sha256`).update(e).digest(`hex`).substring(0,16)}getFilePath(e){let t=this.generateKey(e);return D(this.storageDir,`${t}.json`)}};const Je=t.OAUTH_PROVIDERS;function Ye(e){let t=typeof e==`string`?new URL(e):e,n=t.hostname.toLowerCase();for(let e of Je)for(let t of e.urlPatterns){let r=t.toLowerCase();if(Xe(n,r))return x.debug(`Found matching OAuth provider for URL`,{hostname:n,pattern:t,providerId:e.id,providerName:e.name}),e}x.debug(`No pre-configured OAuth provider found for URL`,{hostname:n,serverUrl:t.toString()})}function Xe(e,t){return!!(e===t||e.endsWith(`.${t}`))}async function Ze(e,t={}){let{credentialStore:n,scope:r,timeoutMs:i}=t,a=S(e),o=new URL(a);if(x.info(`Starting OAuth flow`,{serverUrl:a}),n){let e=await et(o,n);if(e)return x.info(`Using existing OAuth credentials`,{clientId:e.clientInfo.client_id,serverUrl:a}),e}x.debug(`Starting OAuth callback server...`);let s=await We({timeoutMs:i}),c=s.callbackUrl;x.info(`OAuth callback server started`,{callbackUrl:c,port:s.port});try{let e=Ye(o);if(e)return x.info(`Using pre-configured OAuth provider`,{providerId:e.id,providerName:e.name}),await $e(o,e,s,n,r);x.debug(`Discovering OAuth protected resource metadata...`);let i;try{i=await g(o),x.info(`Discovered protected resource metadata`,{authorizationServers:i?.authorization_servers,resource:i?.resource,scopesSupported:i?.scopes_supported})}catch(e){x.warn(`Could not discover protected resource metadata, will try direct discovery`,{error:String(e)})}let l;i?.authorization_servers?.length?(l=new URL(i.authorization_servers[0]),x.debug(`Using authorization server from resource metadata`,{authServerUrl:l.toString()})):(l=o,x.debug(`Using server URL as authorization server`,{authServerUrl:l.toString()})),x.debug(`Discovering authorization server metadata...`);let u=await h(l);if(!u)throw Error(`Could not discover OAuth metadata from ${l}. The server may not support OAuth 2.0 or the metadata endpoint is not accessible.`);x.info(`Discovered authorization server metadata`,{authorizationEndpoint:u.authorization_endpoint,issuer:u.issuer,registrationEndpoint:u.registration_endpoint,tokenEndpoint:u.token_endpoint});let d,f=n?await n.load(a):void 0,p=f?.clientInfo?.redirect_uris||[];if(f?.clientInfo&&p.includes(c)&&f?.clientInfo)x.info(`Reusing existing DCR client registration`,{clientId:f.clientInfo.client_id,clientName:f.clientInfo.client_name,redirectUri:c}),d=f.clientInfo;else{f?.clientInfo&&x.info(`Existing DCR client has different redirect_uri, re-registering`,{existingRedirectUris:p,newRedirectUri:c});let e={client_name:t.clientMetadata?.client_name||`MCP Gateway`,grant_types:t.clientMetadata?.grant_types||[`authorization_code`,`refresh_token`],redirect_uris:[c],response_types:t.clientMetadata?.response_types||[`code`],token_endpoint_auth_method:t.clientMetadata?.token_endpoint_auth_method||`none`,...r&&{scope:r}};if(x.debug(`Client metadata for DCR`,{clientMetadata:e}),!u.registration_endpoint)throw Error(`Authorization server does not support Dynamic Client Registration. No registration_endpoint found in metadata.`);x.info(`Registering client via DCR...`,{registrationEndpoint:u.registration_endpoint}),d=await w(l,{clientMetadata:e,metadata:u}),x.info(`Client registered successfully via DCR`,{clientId:d.client_id,clientName:d.client_name,clientSecretExpiresAt:d.client_secret_expires_at}),n&&await n.update(a,{clientInfo:d})}let m=crypto.randomUUID();x.debug(`Starting authorization flow...`);let{authorizationUrl:ee,codeVerifier:v}=await re(l,{clientInformation:d,metadata:u,redirectUrl:c,scope:r,state:m});await Ie(ee),x.debug(`Waiting for OAuth callback...`);let y=await s.waitForCallback();if(y.state!==m)throw Error(`OAuth state mismatch - possible CSRF attack`);x.info(`Authorization code received`,{codePrefix:`${y.code.substring(0,10)}...`}),x.debug(`Exchanging authorization code for tokens...`);let b=await _(l,{authorizationCode:y.code,clientInformation:d,codeVerifier:v,metadata:u,redirectUri:c});if(x.info(`OAuth tokens obtained successfully`,{expiresIn:b.expires_in,hasRefreshToken:!!b.refresh_token,tokenType:b.token_type}),n){let e=new Date().toISOString();await n.update(a,{tokens:b,tokensObtainedAt:e}),x.info(`OAuth credentials persisted to disk`,{serverUrl:a})}return{clientInfo:d,fromCache:!1,tokens:b}}finally{await s.close()}}async function Qe(e,t,n,r){let i=e.tokenEndpoint,a=e.tokenEndpointAuthMethod||(e.clientSecret?`client_secret_post`:`none`),o=new URLSearchParams;o.set(`grant_type`,`authorization_code`),o.set(`code`,t),o.set(`redirect_uri`,n),r&&o.set(`code_verifier`,r);let s={Accept:`application/json`,"Content-Type":`application/x-www-form-urlencoded`};a===`client_secret_basic`&&e.clientSecret?s.Authorization=`Basic ${Buffer.from(`${e.clientId}:${e.clientSecret}`).toString(`base64`)}`:a===`client_secret_post`&&e.clientSecret?(o.set(`client_id`,e.clientId),o.set(`client_secret`,e.clientSecret)):o.set(`client_id`,e.clientId),x.debug(`Sending token request`,{authMethod:a,providerId:e.id,tokenEndpoint:i});let c=await fetch(i,{body:o.toString(),headers:s,method:`POST`});if(!c.ok){let t=await c.text();throw x.error(`Token exchange failed`,{error:t,providerId:e.id,status:c.status}),Error(`Token exchange failed: ${c.status} ${t}`)}let l=c.headers.get(`content-type`)||``,u;if(l.includes(`application/json`))u=await c.json();else if(l.includes(`application/x-www-form-urlencoded`)||l.includes(`text/plain`)){let e=await c.text(),t=new URLSearchParams(e);u=Object.fromEntries(t.entries())}else{let e=await c.text();try{u=JSON.parse(e)}catch{let t=new URLSearchParams(e);u=Object.fromEntries(t.entries())}}return typeof u.expires_in==`string`&&(u.expires_in=parseInt(u.expires_in,10)),{access_token:u.access_token,expires_in:u.expires_in,refresh_token:u.refresh_token,scope:u.scope,token_type:u.token_type||`bearer`}}async function $e(e,t,n,r,i){let a=e.toString(),o=n.callbackUrl,s={client_id:t.clientId,client_name:t.name,client_secret:t.clientSecret,redirect_uris:[o],token_endpoint_auth_method:t.tokenEndpointAuthMethod||(t.clientSecret?`client_secret_post`:`none`)};x.info(`Using pre-configured OAuth client`,{clientId:t.clientId,hasClientSecret:!!t.clientSecret,providerId:t.id,tokenEndpointAuthMethod:s.token_endpoint_auth_method});let c=i||t.scopes?.join(` `),l=t.usePkce!==!1,u,d,f;if(l){let{generateCodeChallenge:e,generateCodeVerifier:t}=await import(`./pkce-dymop6yt.js`);u=t(),d=await e(u),f=`S256`}let p=new URL(t.authorizationEndpoint);p.searchParams.set(`client_id`,t.clientId),p.searchParams.set(`redirect_uri`,o),p.searchParams.set(`response_type`,`code`),c&&p.searchParams.set(`scope`,c);let m=crypto.randomUUID();p.searchParams.set(`state`,m),d&&f&&(p.searchParams.set(`code_challenge`,d),p.searchParams.set(`code_challenge_method`,f)),await Ie(p),x.debug(`Waiting for OAuth callback...`);let h=await n.waitForCallback();if(h.state!==m)throw Error(`OAuth state mismatch - possible CSRF attack`);x.info(`Authorization code received`,{codePrefix:`${h.code.substring(0,10)}...`,providerId:t.id}),x.debug(`Exchanging authorization code for tokens...`);let g=await Qe(t,h.code,o,u);if(x.info(`OAuth tokens obtained successfully`,{expiresIn:g.expires_in,hasRefreshToken:!!g.refresh_token,providerId:t.id,tokenType:g.token_type}),r){let e=new Date().toISOString();await r.update(a,{clientInfo:s,tokens:g,tokensObtainedAt:e}),x.info(`OAuth credentials persisted to disk`,{providerId:t.id,serverUrl:a})}return{clientInfo:s,fromCache:!1,tokens:g}}async function et(e,t){let n=await t.load(e.toString());if(!n){x.debug(`No stored credentials found`,{serverUrl:e.toString()});return}if(!n.clientInfo){x.debug(`Stored credentials have no client info`,{serverUrl:e.toString()});return}if(t.hasValidAccessToken(n)&&n.tokens)return x.info(`Using cached OAuth credentials with valid access token`,{clientId:n.clientInfo.client_id,serverUrl:e.toString()}),{clientInfo:n.clientInfo,fromCache:!0,tokens:n.tokens};if(t.hasRefreshToken(n)){let r=await tt(e,n,t);if(r)return r}x.debug(`Stored credentials are expired and no valid refresh token`,{serverUrl:e.toString()})}async function tt(e,t,n){if(!(!t.clientInfo||!t.tokens?.refresh_token)){x.info(`Attempting to refresh expired access token`,{clientId:t.clientInfo.client_id,serverUrl:e.toString()});try{let r;try{r=await g(e)}catch{}let i;i=r?.authorization_servers?.length?new URL(r.authorization_servers[0]):e;let a=await h(i),o=await C(i,{clientInformation:t.clientInfo,metadata:a,refreshToken:t.tokens.refresh_token});x.info(`Successfully refreshed access token`,{clientId:t.clientInfo.client_id,expiresIn:o.expires_in,hasNewRefreshToken:!!o.refresh_token});let s=new Date().toISOString();return await n.update(e.toString(),{tokens:o,tokensObtainedAt:s}),{clientInfo:t.clientInfo,fromCache:!0,tokens:o}}catch(t){x.warn(`Failed to refresh access token, will require re-authorization`,{error:String(t),serverUrl:e.toString()}),await n.update(e.toString(),{tokens:void 0,tokensObtainedAt:void 0});return}}}const nt=[`streamable-http`,`sse`];async function rt(e,t,n){let r;for(let i of nt){let a=e();try{let e=it(t,i,n);return await a.connect(e),{client:a,transportType:i}}catch(e){if(r=e,at(e)){x.info(`${i} not supported, trying next transport...`);continue}throw e}}throw r??Error(`No compatible transport found`)}function it(e,t,n){let r=new URL(e);return t===`streamable-http`?new l(r,{requestInit:n}):new o(r,{requestInit:n})}function at(e){if(!e||typeof e!=`object`)return!1;let t=e.status,n=e.code,r=e.message;return!!(t===404||t===405||n===404||n===405||r&&/404|not found|405|method not allowed/i.test(String(r)))}var ot=class extends Se{buffer=``;droppedLinesLogged=0;constructor(){super({objectMode:!1})}_flush(e){this.buffer.trim().startsWith(`{`)?e(null,Buffer.from(this.buffer)):(this.buffer.trim().length>0&&this.logDroppedLine(this.buffer),e(null,null))}_transform(e,t,n){this.buffer+=e.toString();let r=this.buffer.split(`
136
- `);this.buffer=r.pop()||``;let i=[];for(let e of r)e.trim().startsWith(`{`)?i.push(e):e.trim().length>0&&this.logDroppedLine(e);if(i.length>0){let e=`${i.join(`
137
- `)}\n`;n(null,Buffer.from(e))}else n(null,null)}logDroppedLine(e){if(!(this.droppedLinesLogged>50)){if(this.droppedLinesLogged===50){this.droppedLinesLogged+=1,x.info(`Suppressing further non-JSON stdout lines`,{eventType:`mcp_server_stdout_dropped_suppressed`,loggedSoFar:50});return}this.droppedLinesLogged+=1,x.info(`MCP server stdout (non-JSON, dropped)`,{eventType:`mcp_server_stdout_dropped`,line:e.length>1024?`${e.slice(0,1024)}…`:e})}}},st=class{onclose;onerror;onmessage;get pid(){return this._process?.pid??null}get stderr(){return this._stderrStream?this._stderrStream:this._process?.stderr??null}_abortController=new AbortController;_process;_readBuffer=new a;_serverParams;_stderrStream=null;onEvent;constructor(e){this._serverParams=e,(e.stderr===`pipe`||e.stderr===`overlapped`)&&(this._stderrStream=new xe),this.onEvent=e.onEvent}async close(){if(this.onEvent?.({type:`close`}),this._process?.pid)try{if(process.platform===`win32`){let e=ye(`taskkill`,[`/PID`,String(this._process.pid),`/T`,`/F`],{stdio:`ignore`});if(e.error)throw e.error;if(e.status!==0)throw Error(`taskkill exited with status ${e.status}`)}else process.kill(-this._process.pid,`SIGTERM`)}catch(e){x.debug(`Process tree cleanup failed (process may already be dead)`,{error:e.message,pid:this._process.pid})}this._abortController.abort(),this._process=void 0,this._readBuffer.clear()}send(e){return new Promise(t=>{if(!this._process?.stdin)throw Error(`Not connected`);let n=T(e);this._process.stdin.write(n)?t():this._process.stdin.once(`drain`,t)})}async start(){if(this._process)throw Error(`StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.`);return new Promise((e,t)=>{this._process=ve(this._serverParams.command,this._serverParams.args??[],{cwd:this._serverParams.cwd,detached:process.platform!==`win32`,env:this._serverParams.env,shell:this._serverParams.shell??!1,signal:this._abortController.signal,stdio:[`pipe`,`pipe`,this._serverParams.stderr??`inherit`]}),this._process.on(`error`,e=>{if(e.name===`AbortError`){this.onclose?.();return}x.error(`Process spawn error`,{args:this._serverParams.args,command:this._serverParams.command,cwd:this._serverParams.cwd,error:e.message,errorCode:e.code,errorErrno:e.errno,errorSyscall:e.syscall,operation:`spawn`,shell:this._serverParams.shell,transportType:`stdio`}),t(e),this.onerror?.(e)});let n,r;this._process.on(`spawn`,()=>{n=Date.now(),r=this._process?.pid,x.info(`MCP server process spawned`,{argCount:this._serverParams.args?.length,command:this._serverParams.command,eventType:`mcp_server_process_spawned`,pid:r}),e()}),this._process.on(`close`,(e,t)=>{let i=n===void 0?void 0:Date.now()-n;x[e===0&&t===null?`info`:`warn`](`MCP server process closed`,{argCount:this._serverParams.args?.length,code:e,command:this._serverParams.command,eventType:`mcp_server_process_closed`,pid:r,signal:t,uptimeMs:i}),this.onEvent?.({type:`close`}),this._process=void 0,this.onclose?.()}),this._process.stdin?.on(`error`,e=>{x.error(`Stdin error`,{command:this._serverParams.command,error:e.message,operation:`write`,pid:this._process?.pid,transportType:`stdio`}),this.onEvent?.({error:e,type:`error`}),this.onerror?.(e)});let i=new ot;this._process.stdout?.pipe(i),i.on(`data`,e=>{this.onEvent?.({chunk:e.toString(),type:`data`}),this._readBuffer.append(e),this.processReadBuffer()}),i.on(`error`,e=>{x.error(`JSON filter error`,{command:this._serverParams.command,error:e.message,operation:`parse`,pid:this._process?.pid,transportType:`stdio`}),this.onEvent?.({error:e,type:`error`}),this.onerror?.(e)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onEvent?.({message:e,type:`message`}),this.onmessage?.(e)}catch(e){let t=`unknown`;try{let e=this._readBuffer.readMessage();e&&(t=typeof e)}catch{}x.error(`Message processing error`,{command:this._serverParams.command,error:e.message,messageType:t,operation:`process`,pid:this._process?.pid,transportType:`stdio`}),this.onEvent?.({error:e,type:`error`}),this.onerror?.(e)}}};function ct(e){let t=e.toLowerCase().split(/[/\\]/).pop()||``;return t===`docker`||t===`docker.exe`?`docker`:t===`podman`||t===`podman.exe`?`podman`:t===`nerdctl`||t===`nerdctl.exe`?`nerdctl`:t===`finch`||t===`finch.exe`?`finch`:`unknown`}function lt(e){let t=e.indexOf(`run`);if(t===-1)return;let n=e.slice(t+1),r=new Set(`--add-host.--annotation.--arch.--attach.--blkio-weight.--blkio-weight-device.--cap-add.--cap-drop.--cgroup-parent.--cgroupns.--cidfile.--cosign-key.--cpu-period.--cpu-quota.--cpu-rt-period.--cpu-rt-runtime.--cpu-shares.--cpus.--cpuset-cpus.--cpuset-mems.--decryption-key.--device.--device-cgroup-rule.--device-read-bps.--device-read-iops.--device-write-bps.--device-write-iops.--dns.--dns-option.--dns-search.--domainname.--entrypoint.--env.--env-file.--env-host.--expose.--gidmap.--gpus.--group-add.--health-cmd.--health-interval.--health-retries.--health-start-period.--health-timeout.--hostname.--image-volume.--ip.--ip6.--ipc.--isolation.--kernel-memory.--label.--label-file.--link.--link-local-ip.--log-driver.--log-opt.--mac-address.--memory.--memory-reservation.--memory-swap.--memory-swappiness.--mount.--name.--network.--network-alias.--oom-kill-disable.--oom-score-adj.--os.--pid.--pidfile.--pids-limit.--platform.--pod.--privileged.--publish.--publish-all.--pull.--requires.--restart.--rootfs.--runtime.--secret.--security-opt.--shm-size.--stop-signal.--stop-timeout.--storage-opt.--subgidname.--subuidname.--sysctl.--systemd.--timeout.--tmpfs.--tz.--uidmap.--ulimit.--user.--userns.--uts.--variant.--volume.--volume-driver.--volumes-from.--workdir.-a.-c.-e.-h.-l.-m.-p.-P.-u.-v.-w`.split(`.`)),i=0;for(;i<n.length;){let e=n[i];if(e.startsWith(`-`)){if(e.includes(`=`)){i++;continue}if(r.has(e)){i+=2;continue}i++;continue}return e}}function ut(e,t){try{let n=_e(`${t===`unknown`?`docker`:t} image inspect --format "{{json .RepoDigests}}" ${JSON.stringify(e)}`,{encoding:`utf-8`,stdio:[`pipe`,`pipe`,`pipe`],timeout:5e3}).trim(),r;try{r=JSON.parse(n)}catch{return x.debug(`Could not parse RepoDigests JSON`,{imageName:e,result:n,runtime:t}),[]}let i=[];for(let e of r){let t=e.match(/sha256:[a-f0-9]{64}/i);t?i.push(t[0]):/^sha256:[a-f0-9]{64}$/i.test(e)&&i.push(e)}return i.length>0?(x.debug(`Container image digests retrieved`,{digests:i,imageName:e,runtime:t}),i):(x.debug(`No digests available for image (may be locally built)`,{imageName:e,runtime:t}),[])}catch(n){return x.debug(`Could not get container image digests`,{error:n instanceof Error?n.message:String(n),imageName:e,runtime:t}),[]}}function dt(e,t){let n=ct(e);if(n===`unknown`)return{imageDigests:[],imageName:``,isContainerMCP:!1,runtime:`unknown`};if(!t||!t.includes(`run`))return{imageDigests:[],imageName:``,isContainerMCP:!1,runtime:n};let r=lt(t);return r?{imageDigests:ut(r,n),imageName:r,isContainerMCP:!0,runtime:n}:(x.debug(`Container command detected but could not extract image name`,{args:t,command:e,runtime:n}),{imageDigests:[],imageName:``,isContainerMCP:!0,runtime:n})}he.inspect.defaultOptions.depth=8,`EventSource`in global||(global.EventSource=$);const ft=async()=>{ae(x);let t=await se(oe(process.argv)).scriptName(`mcp-gateway`).command(`stdio [command] [args...]`,`Run a local command with stdio transport (default)`,e=>e.positional(`command`,{describe:`The command to run`,type:`string`}).positional(`args`,{array:!0,describe:`The arguments to pass to the command`,type:`string`})).command(`remote`,`Connect to a remote MCP server`,e=>e.options({"bearer-token-env":{describe:`Environment variable name containing a bearer token for remote authentication`,type:`string`},"env-http-headers":{describe:`HTTP headers resolved from environment variables (format: HeaderName:ENV_VAR_NAME)`,string:!0,type:`array`},headers:{deprecated:`Use --env-http-headers with env var names instead. --headers exposes values in process listings.`,describe:`Legacy: headers with literal values (format: key:value)`,string:!0,type:`array`},"remote-transport":{choices:[`sse`,`stream`],deprecated:`Transport is now auto-detected per MCP spec. This option is ignored.`,describe:`(Deprecated) The transport type - now auto-detected`,type:`string`},url:{demandOption:!0,describe:`The URL of the remote MCP server`,type:`string`}})).command(`$0 [command] [args...]`,`Run a command with MCP arguments (backward compatible)`,e=>e.positional(`command`,{describe:`The command to run`,type:`string`}).positional(`args`,{array:!0,describe:`The arguments to pass to the command`,type:`string`})).env(`MCP_GATEWAY`).parserConfiguration({"populate--":!0,"unknown-options-as-args":!0}).options({"access-control-url":{describe:`URL of the access control service (overrides MCP_GATEWAY_ACCESS_CONTROL_URL)`,type:`string`},debug:{default:!1,describe:`Enable debug logging`,type:`boolean`},env:{describe:`Environment variables to pass to the command (format: KEY=value)`,string:!0,type:`array`},gracefulShutdownTimeout:{default:5e3,describe:`The timeout (in milliseconds) for graceful shutdown`,type:`number`},port:{describe:`Run as HTTP server on the specified port instead of stdio`,type:`number`},"scanner-api-key":{describe:`API key for scanner authentication (overrides MCP_GATEWAY_SCANNER_API_KEY)`,type:`string`},"scanner-fail-open":{describe:`Allow requests when scanner is unavailable (overrides MCP_GATEWAY_SCANNER_FAIL_OPEN)`,type:`boolean`},"scanner-timeout-ms":{describe:`Scanner request timeout in milliseconds (overrides MCP_GATEWAY_SCANNER_TIMEOUT_MS)`,type:`number`},"scanner-url":{describe:`URL of the scanner/evaluator service (overrides MCP_GATEWAY_SCANNER_URL)`,type:`string`},shell:{default:process.platform===`win32`,describe:`Spawn the server via the user's shell (defaults to true on Windows)`,type:`boolean`}}).help().parseAsync(),a,o,l,d,f,m={},h={};if(t.env)for(let e of t.env){let[t,...n]=e.split(`=`);t&&n.length>0&&(h[t.trim()]=n.join(`=`).trim())}let g=e=>{if(e.includes("${")){let t,n=e.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g,(e,n)=>process.env[n]||(t=n,``));return t?{missingVar:t,resolved:``}:{resolved:n}}let t=process.env[e];return t?{resolved:t}:{missingVar:e,resolved:``}};if(t.headers)for(let e of t.headers){let[t,...n]=e.split(`:`);t&&n.length>0&&(m[t.trim()]=n.join(`:`).trim())}if(t.bearerTokenEnv){let e=t.bearerTokenEnv,{missingVar:n,resolved:r}=g(e);n&&(x.error(`Bearer token env var specified but not set`,{envVar:n,eventType:`mcp_auth_bearer_env_missing`}),process.exit(1)),m.Authorization=`Bearer ${r}`,x.info(`Bearer token loaded from environment variable`,{authType:`bearer_token`,envVar:e,eventType:`mcp_auth_bearer_env`,remoteUrl:t.url})}if(t.envHttpHeaders)for(let e of t.envHttpHeaders){let[n,...r]=e.split(`:`),i=r.join(`:`).trim();if(n&&i){let e=n.trim(),{missingVar:r,resolved:a}=g(i);r&&(x.error(`Env var for HTTP header not set`,{envVar:r,eventType:`mcp_auth_env_header_missing`,header:e}),process.exit(1)),m[e]=a,x.info(`HTTP header loaded from environment`,{eventType:`mcp_auth_env_header`,header:e,remoteUrl:t.url})}}let _=ee(m);if(_&&x.setTraceId(_),m.Authorization){let e=m.Authorization.startsWith(`Bearer `)?`bearer_token`:m.Authorization.startsWith(`Basic `)?`basic`:`api_key`;x.info(`Authorization header provided`,{authType:e,eventType:`mcp_auth_header_provided`,remoteUrl:t.url})}let C={...p.scanner.headers};if(x.debug(`Initializing traffic scanner`,{failOpen:p.scanner.failOpen,hasApiKey:!!p.scanner.apiKey,scannerEnabled:p.scanner.enabled,scannerUrl:p.scanner.url,timeoutMs:p.scanner.timeoutMs}),t._[0]===`remote`){a=`remote`,t[`remote-transport`]&&x.warn(`The --remote-transport option is deprecated and will be ignored. Transport is now auto-detected per MCP spec (Streamable HTTP with SSE fallback).`,{providedTransport:t[`remote-transport`]});let e=t.url;if(!e)throw new r(`Remote URL is required for remote proxy type`,`url`);d=S(e),d!==e&&x.debug(`Normalized remote URL`,{normalizedUrl:d,originalUrl:e})}else{if(a=`stdio`,t[`--`]&&t[`--`].length>0){let e=t[`--`];o=e[0],l=e.slice(1).map(String)}else o=t.command,l=(t.args||[]).map(String);if(!o)throw new r(`No command specified for stdio proxy`,`command`)}let w;a===`stdio`&&o&&(w=dt(o,l),w.isContainerMCP&&x.info(`Container MCP detected`,{imageDigests:w.imageDigests,imageName:w.imageName,runtime:w.runtime}));let T;if(p.accessControl.url&&p.scanner.apiKey){let e=await y(),t=a===`stdio`?{...e,proxyType:`stdio`,stdioCliArgs:{args:l,command:o,dockerImageDigests:w?.imageDigests,dockerImageName:w?.imageName,proxyType:`stdio`}}:{...e,proxyType:`remote`,remoteCliArgs:{proxyType:`remote`,url:d}};T=new Fe({apiKey:p.scanner.apiKey,headers:p.accessControl.headers,sessionData:t,timeoutMs:p.accessControl.timeoutMs,url:p.accessControl.url})}let re=a===`remote`?d:o,E=new Pe({client:T,enabled:p.accessControl.enabled,serverName:re}),D=new qe({storageDir:p.oauthDir}),O=()=>new n({name:`mcp-gateway`,version:p.appVersion},{capabilities:{}}),k=async n=>{if(!await E.isAllowed()){let t=E.getBlockReason();throw x.warn(`MCP server blocked by access control`,{proxyType:a,reason:t}),new e(t,`policy_block`)}if(x.info(`MCP server allowed by access control`),a===`stdio`){let e={...process.env,...h},r=new st({args:l,command:o,env:e,onEvent:e=>{t.debug&&x.debug(`Transport event`,{event:e})},shell:t.shell,stderr:`pipe`}),s=1024;s*8;let c=e=>e.length>s?`${e.slice(0,s)}…`:e,u=``,d=[],f=e=>{let t=c(e);d.push(t),d.length>100&&d.shift(),x.info(`MCP server stderr`,{command:o,eventType:`mcp_server_stderr`,line:t})},p=()=>{u.length!==0&&(f(u),u=``)},m=new pe(`utf8`),g=!1,_=()=>{if(g)return;g=!0;let e=m.end();e&&(u+=e),p()};r.stderr?.on(`data`,e=>{process.stderr.write(e),u+=m.write(e);let t=u.split(`
138
- `);u=t.pop()??``;for(let e of t){if(e.length===0)continue;f(e)}u.length>8192&&p()}),r.stderr?.once(`end`,_),r.stderr?.once(`close`,_);try{return await n.connect(r),n}catch(e){throw _(),x.warn(`Failed original server access`,{command:o,error:e instanceof Error?e.message:String(e),eventType:`mcp_server_access_failed`,proxyType:a,stderrTail:d.slice(-20)}),new i(`Failed to connect to stdio process: ${e}`,void 0,`stdio`,{argCount:l?.length,command:o})}}else if(a===`remote`){let e=d,t=e=>{let t={...m};return e&&(t.Authorization=`Bearer ${e}`),Object.keys(t).length>0?{headers:t}:void 0},n=e=>{if(e instanceof u)return!0;if(e&&typeof e==`object`){let t=e.status,n=e.code,r=e.message;if(t===401||n===401||r&&/unauthorized|401/i.test(String(r)))return!0}return!1},r=async()=>{let t=await Ze(e,{credentialStore:D});return x.info(`Authentication performed`,{authType:`oauth`,eventType:`mcp_auth_performed`,fromCache:t.fromCache,remoteUrl:e}),t.tokens.access_token},o;try{let i=await D.load(e),a=i&&D.hasValidAccessToken(i)?i.tokens?.access_token:void 0,s=!1;try{let n=await rt(O,e,t(a));o=n.client,f=n.transportType,x.info(`Connected to remote server`,{hasAuth:!!a,transport:f})}catch(i){if(n(i)){if(s)throw i;a?(x.info(`Cached OAuth token rejected (possibly revoked), invalidating and re-authorizing...`),await D.update(e,{tokens:void 0,tokensObtainedAt:void 0})):x.info(`Server requires OAuth, starting authentication flow...`),a=await r(),s=!0;let n=await rt(O,e,t(a));o=n.client,f=n.transportType,x.info(`Connected to remote server with OAuth`,{transport:f})}else throw i}return o}catch(t){throw x.warn(`Failed original server access`,{error:t instanceof Error?t.message:String(t),eventType:`mcp_server_access_failed`,proxyType:a,remoteUrl:e}),t instanceof i?t:new i(`Failed to connect to remote server: ${t instanceof Error?t.message:String(t)}`,e,f,{headerCount:Object.keys(m).length})}}return n},ce=async()=>{if(t.port){let e=a===`stdio`?{args:l,command:o,dockerImageDigests:w?.imageDigests,dockerImageName:w?.imageName,proxyType:a}:{proxyType:a,url:d};await b({cliArgs:e,scanApiKey:p.scanner.apiKey,scanEnabled:p.scanner.enabled,scanFailOpen:p.scanner.failOpen,scanHeaders:C,scanTimeoutMs:p.scanner.timeoutMs,scanUrl:p.scanner.url||``});let n,r=await ie({createServer:async()=>{let e=O();n=await k(e);let t=n.getServerVersion(),r=n.getServerCapabilities(),i=new s(t,{capabilities:r});return ne({authorizer:E,client:n,server:i,serverCapabilities:r}),i},onClose:async e=>{n&&await n.close(),await e.close()},port:t.port});return x.info(`MCP gateway started`,{eventType:`mcp_gateway_started`,mode:`http`,port:t.port,proxyType:a}),a===`stdio`?x.info(`MCP server configuration`,{args:l?.join(` `)||``,command:o,eventType:`mcp_server_config`,proxyType:a}):x.info(`MCP server configuration`,{eventType:`mcp_server_config`,proxyType:a,remoteUrl:d}),{close:()=>r.close()}}let e=O(),n=await k(e),r=n.getServerVersion(),i=n.getServerCapabilities(),u=new s(r,{capabilities:i});ne({authorizer:E,client:n,server:u,serverCapabilities:i});let m=new c,h=a===`stdio`?{args:l,command:o,dockerImageDigests:w?.imageDigests,dockerImageName:w?.imageName,proxyType:a}:{proxyType:a,url:d};return await b({cliArgs:h,scanApiKey:p.scanner.apiKey,scanEnabled:p.scanner.enabled,scanFailOpen:p.scanner.failOpen,scanHeaders:C,scanTimeoutMs:p.scanner.timeoutMs,scanUrl:p.scanner.url||``}),await u.connect(m),x.info(`MCP gateway started`,{eventType:`mcp_gateway_started`,mode:`stdio`,proxyType:a}),x.info(`MCP server configuration`,{capabilities:Object.keys(i||{}),eventType:`mcp_server_config`,proxyType:a,serverName:r?.name,serverVersion:r?.version,...a===`stdio`?{args:l?.join(` `)||``,command:o}:{remoteUrl:d,transport:f}}),{close:()=>n.close()}},le=({server:e,timeout:t})=>{let n=!1,r=async r=>{if(!n){n=!0,x.info(`MCP gateway stopping`,{eventType:`mcp_gateway_stopping`,signal:r});try{await e.close(),te(),await v(2e3),process.exit(0)}catch(e){let n=`Error during shutdown: ${e}`;x.error(`Error during shutdown`,{error:n,eventType:`mcp_gateway_stopped`,shutdownTimeout:t}),await v(2e3),process.exit(1)}}},i=e=>async()=>{me(()=>{x.error(`Graceful shutdown timeout exceeded, forcing exit`),process.exit(1)},t).unref(),await r(e)};return process.once(`SIGTERM`,i(`SIGTERM`)),process.once(`SIGINT`,i(`SIGINT`)),process.stdin.once(`end`,i(`stdin-end`)),()=>e.close()};x.info(`MCP gateway starting`,{command:o,eventType:`mcp_gateway_starting`,proxyType:a,transport:a===`remote`?`auto-detect`:`stdio`,url:d});try{let e=await ce();le({server:e,timeout:t.gracefulShutdownTimeout})}catch(t){t instanceof e&&(console.error(`
139
- ❌ ACCESS DENIED`),console.error(`━`.repeat(60)),console.error(`
140
- This MCP server has been blocked by Onyx because it is not authorized by your organization's access control policy. Please contact your administrator if you believe this is an error.
141
- `),x.error(`MCP server blocked by access control policy`,{error:t.message,reason:t.reason}),await v(2e3),process.exit(1));let n=`Could not start the proxy: ${t}`;x.error(`MCP server failed to start`,{args:l,command:o,error:n,eventType:`mcp_server_start_failed`,proxyType:a,remoteUrl:d,transport:f}),await v(2e3),process.exit(1)}};export{ft as main};
142
- //# sourceMappingURL=main-Ct3dHxDT.js.map