@redocly/realm 0.137.0-next.0 → 0.137.0-next.2

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 (56) hide show
  1. package/CHANGELOG.md +74 -0
  2. package/dist/cli/stats/collectors/page-slugs/index.d.ts +9 -0
  3. package/dist/cli/stats/collectors/page-slugs/index.js +1 -0
  4. package/dist/cli/stats/index.js +1 -1
  5. package/dist/constants/l10n/langs/ar.js +1 -1
  6. package/dist/constants/l10n/langs/de.js +1 -1
  7. package/dist/constants/l10n/langs/en.js +1 -1
  8. package/dist/constants/l10n/langs/es.js +1 -1
  9. package/dist/constants/l10n/langs/fr.js +1 -1
  10. package/dist/constants/l10n/langs/hi.js +1 -1
  11. package/dist/constants/l10n/langs/it.js +1 -1
  12. package/dist/constants/l10n/langs/ja.js +1 -1
  13. package/dist/constants/l10n/langs/ko.js +1 -1
  14. package/dist/constants/l10n/langs/pl.js +1 -1
  15. package/dist/constants/l10n/langs/pt-BR.js +1 -1
  16. package/dist/constants/l10n/langs/pt.js +1 -1
  17. package/dist/constants/l10n/langs/ru.js +1 -1
  18. package/dist/constants/l10n/langs/uk.js +1 -1
  19. package/dist/constants/l10n/langs/zh.js +1 -1
  20. package/dist/server/config/env-config.d.ts +2 -0
  21. package/dist/server/config/env-schema.d.ts +5 -0
  22. package/dist/server/config/env-schemas/feature-flags.d.ts +4 -0
  23. package/dist/server/config/env-schemas/feature-flags.js +1 -1
  24. package/dist/server/plugins/config-parser/loaders/content-slugs-loader.d.ts +5 -0
  25. package/dist/server/plugins/config-parser/loaders/content-slugs-loader.js +1 -1
  26. package/dist/server/plugins/markdown/html/html-jsx-attribute-mapping.js +1 -1
  27. package/dist/server/plugins/mcp/auth/auth-handlers.js +1 -1
  28. package/dist/server/plugins/mcp/auth/token-audience-telemetry.d.ts +7 -0
  29. package/dist/server/plugins/mcp/auth/token-audience-telemetry.js +1 -0
  30. package/dist/server/plugins/mcp/auth/token-audience.d.ts +6 -0
  31. package/dist/server/plugins/mcp/auth/token-audience.js +1 -0
  32. package/dist/server/plugins/mcp/codemode/tools/execute.js +1 -1
  33. package/dist/server/plugins/mcp/codemode/tools/manage-credentials.d.ts +1 -0
  34. package/dist/server/plugins/mcp/codemode/tools/manage-credentials.js +2 -2
  35. package/dist/server/plugins/mcp/docs-mcp/tools/openapi/utils.js +1 -1
  36. package/dist/server/plugins/mcp/gateway-mcp/credential-validation.d.ts +4 -0
  37. package/dist/server/plugins/mcp/gateway-mcp/credential-validation.js +1 -0
  38. package/dist/server/plugins/mcp/gateway-mcp/elicitation.d.ts +11 -3
  39. package/dist/server/plugins/mcp/gateway-mcp/elicitation.js +4 -3
  40. package/dist/server/plugins/mcp/gateway-mcp/fetch/fetch-bridge.d.ts +10 -1
  41. package/dist/server/plugins/mcp/gateway-mcp/fetch/fetch-bridge.js +1 -1
  42. package/dist/server/plugins/mcp/gateway-mcp/fetch-capability.d.ts +1 -1
  43. package/dist/server/plugins/mcp/gateway-mcp/fetch-capability.js +1 -1
  44. package/dist/server/plugins/mcp/gateway-mcp/secret-store.d.ts +8 -4
  45. package/dist/server/plugins/mcp/gateway-mcp/secret-store.js +1 -1
  46. package/dist/server/plugins/mcp/gateway-mcp/upstream-auth-scheme.d.ts +24 -1
  47. package/dist/server/plugins/mcp/gateway-mcp/upstream-auth-scheme.js +2 -1
  48. package/dist/server/plugins/mcp/gateway-mcp/upstream-auth.d.ts +6 -0
  49. package/dist/server/plugins/mcp/gateway-mcp/upstream-auth.js +1 -1
  50. package/dist/server/plugins/mcp/handlers/docs-mcp-handler.js +1 -1
  51. package/dist/server/plugins/mcp/handlers/mcp-credentials-handler.js +53 -33
  52. package/dist/server/plugins/mcp/servers/mcp-server.js +4 -2
  53. package/dist/server/plugins/mcp/types.d.ts +2 -2
  54. package/dist/server/web-server/utils/prepare-list-response.d.ts +2 -0
  55. package/dist/server/web-server/utils/prepare-list-response.js +1 -1
  56. package/package.json +8 -8
@@ -1 +1 @@
1
- import f from"path";import{combineUrls as p}from"@redocly/theme/core/utils";import{VERSION_SEPARATOR as S}from"../../../constants/common.js";import{removeTrailingSlash as d}from"../../../../utils/url/remove-trailing-slash.js";import{slash as b}from"../../../../utils/path/slash.js";import{logger as c}from"../../../tools/notifiers/logger.js";import{getDefaultVersionByPath as v}from"./versions-config-loader.js";import{GithubSlugger as D,slug as E}from"../../../utils/index.js";import{parseBaseName as F}from"../../utils.js";const I=new Set([".jpg",".jpeg",".png",".gif",".webp",".svg",".ico",".avif",".mp3",".wav",".ogg",".m4a",".mp4",".avi",".mov",".webm",".pdf",".doc",".docx",".zip",".rar",".gz",".ttf",".woff",".woff2"]),A=async(i,{fs:e,cache:s})=>{const g=c.startTiming(),o=(await s.load("versions-config","versions-config")).data,t=new Map,n=new Map,r=new Set,l=new D;n.set(".","/"),n.set("/","/");const u=e.scan().sort((a,m)=>m.relativePath.localeCompare(a.relativePath));for(const{relativePath:a}of u){if(I.has(f.posix.extname(a)))continue;const{data:m}=await s.load(a,"is-ignored");if(m)continue;const h=b(a).replace(new RegExp("^(@i18n|@l10n)\\/"),""),w=v(a,o);N(h,{defaultVersion:w,fileSlugs:t,dirSlugs:n,allFileSlugsList:r,githubSlugger:l})}return c.verboseTime(g,"Calculated slugs. Number of file paths processed: "+u.length),{fileSlugs:t,dirSlugs:n}};function N(i,e){const s=e.fileSlugs.get(i);if(s)return s;let g=f.posix.dirname(i);const o=z(g,e)||"",{baseName:t,isIndexFile:n}=F(i),r=e.dirSlugs.has(f.posix.join(g,t));let l;if(!n&&r){const u=E(p(o,t));e.allFileSlugsList.has(u)||(l=u)}l||(l=n&&e.dirSlugs.get(g)||e.githubSlugger.slug(p(o,t))),l=d(l),e.fileSlugs.set(i,l),e.allFileSlugsList.add(l)}function z(i,e){if(e.dirSlugs.has(i))return e.dirSlugs.get(i);const s=d(f.posix.normalize(i)).split("/");let g="/",o="";for(const t of s){o=f.posix.join(o,t);const n=T(t,e.defaultVersion);let r=e.dirSlugs.get(o)||e.githubSlugger.slug(p("/",g,n));r.endsWith("/")||(r=r+"/"),e.dirSlugs.set(o,r),g=r}return e.dirSlugs.get(i)}function T(i,e){if(!i.startsWith(S))return i;const s=i.substring(S.length);return s===e?"":s}export{I as IGNORED_EXTS,A as contentSlugsLoader};
1
+ import d from"path";import{combineUrls as c}from"@redocly/theme/core/utils";import{VERSION_SEPARATOR as p}from"../../../constants/common.js";import{removeTrailingSlash as h}from"../../../../utils/url/remove-trailing-slash.js";import{slash as V}from"../../../../utils/path/slash.js";import{logger as w}from"../../../tools/notifiers/logger.js";import{getDefaultVersionByPath as D}from"./versions-config-loader.js";import{GithubSlugger as E,slug as S}from"../../../utils/index.js";import{parseBaseName as F}from"../../utils.js";const I=new Set([".jpg",".jpeg",".png",".gif",".webp",".svg",".ico",".avif",".mp3",".wav",".ogg",".m4a",".mp4",".avi",".mov",".webm",".pdf",".doc",".docx",".zip",".rar",".gz",".ttf",".woff",".woff2"]),A=async(i,{fs:e,cache:n})=>{const a=w.startTiming(),r=(await n.load("versions-config","versions-config")).data,t=new Map,l=new Map,o=new Set,s={pageVsPage:0,dirVsDir:0},g=new E;l.set(".","/"),l.set("/","/");const f=e.scan().sort((u,m)=>m.relativePath.localeCompare(u.relativePath));for(const{relativePath:u}of f){if(I.has(d.posix.extname(u)))continue;const{data:m}=await n.load(u,"is-ignored");if(m)continue;const b=V(u).replace(new RegExp("^(@i18n|@l10n)\\/"),""),v=D(u,r);N(b,{defaultVersion:v,fileSlugs:t,dirSlugs:l,allFileSlugsList:o,githubSlugger:g,collisions:s})}return w.verboseTime(a,"Calculated slugs. Number of file paths processed: "+f.length),{fileSlugs:t,dirSlugs:l,collisions:s}};function N(i,e){const n=e.fileSlugs.get(i);if(n)return n;let a=d.posix.dirname(i);const r=z(a,e)||"",{baseName:t,isIndexFile:l}=F(i),o=e.dirSlugs.has(d.posix.join(a,t));let s;if(!l&&o){const g=S(c(r,t));e.allFileSlugsList.has(g)||(s=g)}if(!s){const g=l?e.dirSlugs.get(a):void 0;if(g)s=g;else{const f=c(r,t),u=S(f);s=e.githubSlugger.slug(f),s!==u&&e.collisions.pageVsPage++}}s=h(s),e.fileSlugs.set(i,s),e.allFileSlugsList.add(s)}function z(i,e){if(e.dirSlugs.has(i))return e.dirSlugs.get(i);const n=h(d.posix.normalize(i)).split("/");let a="/",r="";for(const t of n){r=d.posix.join(r,t);const l=T(t,e.defaultVersion);let o=e.dirSlugs.get(r);if(!o){const s=c("/",a,l),g=S(s);o=e.githubSlugger.slug(s),o!==g&&e.collisions.dirVsDir++}o.endsWith("/")||(o=o+"/"),e.dirSlugs.set(r,o),a=o}return e.dirSlugs.get(i)}function T(i,e){if(!i.startsWith(p))return i;const n=i.substring(p.length);return n===e?"":n}export{I as IGNORED_EXTS,A as contentSlugsLoader};
@@ -1 +1 @@
1
- const o={for:"htmlFor",class:"className","accept-charset":"acceptCharset",accesskey:"accessKey",allowfullscreen:"allowFullScreen",allowtransparency:"allowTransparency",autocomplete:"autoComplete",autoplay:"autoPlay",cellpadding:"cellPadding",cellspacing:"cellSpacing",charset:"charSet",classid:"classID",colspan:"colSpan",contenteditable:"contentEditable",contextmenu:"contextMenu",crossorigin:"crossOrigin",datetime:"dateTime",enctype:"encType",formaction:"formAction",formenctype:"formEncType",formmethod:"formMethod",formnovalidate:"formNoValidate",formtarget:"formTarget",frameborder:"frameBorder",hreflang:"hrefLang","http-equiv":"httpEquiv",inputmode:"inputMode",keyparams:"keyParams",keytype:"keyType",marginheight:"marginHeight",marginwidth:"marginWidth",maxlength:"maxLength",mediagroup:"mediaGroup",minlength:"minLength",novalidate:"noValidate",playsinline:"playsInline",radiogroup:"radioGroup",readonly:"readOnly",referrerpolicy:"referrerPolicy",rowspan:"rowSpan",spellcheck:"spellCheck",srcdoc:"srcDoc",srclang:"srcLang",srcset:"srcSet",tabindex:"tabIndex",usemap:"useMap",autocapitalize:"autoCapitalize",autocorrect:"autoCorrect",autosave:"autoSave",itemprop:"itemProp",itemscope:"itemScope",itemtype:"itemType",itemid:"itemID",itemref:"itemRef","accent-height":"accentHeight","alignment-baseline":"alignmentBaseline","arabic-form":"arabicForm","baseline-shift":"baselineShift","cap-height":"capHeight","clip-path":"clipPath","clip-rule":"clipRule","color-interpolation":"colorInterpolation","color-interpolation-filters":"colorInterpolationFilters","color-profile":"colorProfile","color-rendering":"colorRendering","dominant-baseline":"dominantBaseline","enable-background":"enableBackground","fill-opacity":"fillOpacity","fill-rule":"fillRule","flood-color":"floodColor","flood-opacity":"floodOpacity","font-family":"fontFamily","font-size":"fontSize","font-size-adjust":"fontSizeAdjust","font-stretch":"fontStretch","font-style":"fontStyle","font-variant":"fontVariant","font-weight":"fontWeight","glyph-name":"glyphName","glyph-orientation-horizontal":"glyphOrientationHorizontal","glyph-orientation-vertical":"glyphOrientationVertical","horiz-adv-x":"horizAdvX","horiz-origin-x":"horizOriginX","image-rendering":"imageRendering","letter-spacing":"letterSpacing","lighting-color":"lightingColor","marker-end":"markerEnd","marker-mid":"markerMid","marker-start":"markerStart","overline-position":"overlinePosition","overline-thickness":"overlineThickness","paint-order":"paintOrder","panose-1":"panose1","pointer-events":"pointerEvents","rendering-intent":"renderingIntent","shape-rendering":"shapeRendering","stop-color":"stopColor","stop-opacity":"stopOpacity","strikethrough-position":"strikethroughPosition","strikethrough-thickness":"strikethroughThickness","stroke-dasharray":"strokeDasharray","stroke-dashoffset":"strokeDashoffset","stroke-linecap":"strokeLinecap","stroke-linejoin":"strokeLinejoin","stroke-miterlimit":"strokeMiterlimit","stroke-opacity":"strokeOpacity","stroke-width":"strokeWidth","text-anchor":"textAnchor","text-decoration":"textDecoration","text-rendering":"textRendering","underline-position":"underlinePosition","underline-thickness":"underlineThickness","unicode-bidi":"unicodeBidi","unicode-range":"unicodeRange","units-per-em":"unitsPerEm","v-alphabetic":"vAlphabetic","v-hanging":"vHanging","v-ideographic":"vIdeographic","v-mathematical":"vMathematical","vector-effect":"vectorEffect","vert-adv-y":"vertAdvY","vert-origin-x":"vertOriginX","vert-origin-y":"vertOriginY","word-spacing":"wordSpacing","writing-mode":"writingMode","x-height":"xHeight","xlink:actuate":"xlinkActuate","xlink:arcrole":"xlinkArcrole","xlink:href":"xlinkHref","xlink:role":"xlinkRole","xlink:show":"xlinkShow","xlink:title":"xlinkTitle","xlink:type":"xlinkType","xml:base":"xmlBase","xmlns:xlink":"xmlnsXlink","xml:lang":"xmlLang","xml:space":"xmlSpace"};function c(i,e){const t={};for(const[n,r]of Object.entries(i))switch(n){case"value":e==="input"||e==="textarea"?t.defaultValue=r:t.value=r;break;case"checked":e==="input"?t.defaultChecked=!0:t.checked=r;break;case"style":t.style=l(r);break;default:t[o[n]||n]=r}return t}function a(i){return i.match(/^--/)?i:i.replace(/-[a-z]/g,e=>e[1].toUpperCase())}function l(i){return i.split(";").filter(e=>e.trim().length).reduce((e,t)=>{const[n,r=""]=t.split(":");return e[a(n.trim())]=r.trim(),e},{})}export{c as getJsxConvertedAttributes};
1
+ const a={for:"htmlFor",class:"className","accept-charset":"acceptCharset",accesskey:"accessKey",allowfullscreen:"allowFullScreen",allowtransparency:"allowTransparency",autocomplete:"autoComplete",autoplay:"autoPlay",cellpadding:"cellPadding",cellspacing:"cellSpacing",charset:"charSet",classid:"classID",colspan:"colSpan",contenteditable:"contentEditable",contextmenu:"contextMenu",crossorigin:"crossOrigin",datetime:"dateTime",enctype:"encType",formaction:"formAction",formenctype:"formEncType",formmethod:"formMethod",formnovalidate:"formNoValidate",formtarget:"formTarget",frameborder:"frameBorder",hreflang:"hrefLang","http-equiv":"httpEquiv",inputmode:"inputMode",keyparams:"keyParams",keytype:"keyType",marginheight:"marginHeight",marginwidth:"marginWidth",maxlength:"maxLength",mediagroup:"mediaGroup",minlength:"minLength",novalidate:"noValidate",playsinline:"playsInline",radiogroup:"radioGroup",readonly:"readOnly",referrerpolicy:"referrerPolicy",rowspan:"rowSpan",spellcheck:"spellCheck",srcdoc:"srcDoc",srclang:"srcLang",srcset:"srcSet",tabindex:"tabIndex",usemap:"useMap",autocapitalize:"autoCapitalize",autocorrect:"autoCorrect",autosave:"autoSave",itemprop:"itemProp",itemscope:"itemScope",itemtype:"itemType",itemid:"itemID",itemref:"itemRef","accent-height":"accentHeight","alignment-baseline":"alignmentBaseline","arabic-form":"arabicForm","baseline-shift":"baselineShift","cap-height":"capHeight","clip-path":"clipPath","clip-rule":"clipRule","color-interpolation":"colorInterpolation","color-interpolation-filters":"colorInterpolationFilters","color-profile":"colorProfile","color-rendering":"colorRendering","dominant-baseline":"dominantBaseline","enable-background":"enableBackground","fill-opacity":"fillOpacity","fill-rule":"fillRule","flood-color":"floodColor","flood-opacity":"floodOpacity","font-family":"fontFamily","font-size":"fontSize","font-size-adjust":"fontSizeAdjust","font-stretch":"fontStretch","font-style":"fontStyle","font-variant":"fontVariant","font-weight":"fontWeight","glyph-name":"glyphName","glyph-orientation-horizontal":"glyphOrientationHorizontal","glyph-orientation-vertical":"glyphOrientationVertical","horiz-adv-x":"horizAdvX","horiz-origin-x":"horizOriginX","image-rendering":"imageRendering","letter-spacing":"letterSpacing","lighting-color":"lightingColor","marker-end":"markerEnd","marker-mid":"markerMid","marker-start":"markerStart","overline-position":"overlinePosition","overline-thickness":"overlineThickness","paint-order":"paintOrder","panose-1":"panose1","pointer-events":"pointerEvents","rendering-intent":"renderingIntent","shape-rendering":"shapeRendering","stop-color":"stopColor","stop-opacity":"stopOpacity","strikethrough-position":"strikethroughPosition","strikethrough-thickness":"strikethroughThickness","stroke-dasharray":"strokeDasharray","stroke-dashoffset":"strokeDashoffset","stroke-linecap":"strokeLinecap","stroke-linejoin":"strokeLinejoin","stroke-miterlimit":"strokeMiterlimit","stroke-opacity":"strokeOpacity","stroke-width":"strokeWidth","text-anchor":"textAnchor","text-decoration":"textDecoration","text-rendering":"textRendering","underline-position":"underlinePosition","underline-thickness":"underlineThickness","unicode-bidi":"unicodeBidi","unicode-range":"unicodeRange","units-per-em":"unitsPerEm","v-alphabetic":"vAlphabetic","v-hanging":"vHanging","v-ideographic":"vIdeographic","v-mathematical":"vMathematical","vector-effect":"vectorEffect","vert-adv-y":"vertAdvY","vert-origin-x":"vertOriginX","vert-origin-y":"vertOriginY","word-spacing":"wordSpacing","writing-mode":"writingMode","x-height":"xHeight","xlink:actuate":"xlinkActuate","xlink:arcrole":"xlinkArcrole","xlink:href":"xlinkHref","xlink:role":"xlinkRole","xlink:show":"xlinkShow","xlink:title":"xlinkTitle","xlink:type":"xlinkType","xml:base":"xmlBase","xmlns:xlink":"xmlnsXlink","xml:lang":"xmlLang","xml:space":"xmlSpace"};function s(r,t){const e={};for(const[i,n]of Object.entries(r))switch(i){case"value":t==="input"||t==="textarea"?e.defaultValue=n:e.value=n;break;case"checked":t==="input"?e.defaultChecked=!0:e.checked=n;break;case"style":e.style=c(n);break;default:e[a[i]||i]=n}return e}function l(r){return r.match(/^--/)?r:r.replace(/-[a-z]/g,t=>t[1].toUpperCase())}function c(r){return r.split(";").filter(t=>t.trim().length).reduce((t,e)=>{const i=e.indexOf(":"),n=i===-1?e:e.slice(0,i),o=i===-1?"":e.slice(i+1);return t[l(n.trim())]=o.trim(),t},{})}export{s as getJsxConvertedAttributes};
@@ -1 +1 @@
1
- import{extractTokenFromAuthHeader as l}from"../../../plugins/mcp/utils/jwt.js";import{SUPPORTED_MCP_SCOPES as p}from"../constants.js";import{getUserParamsFromCookies as f}from"../../../web-server/auth.js";import{ServerRoutes as a}from"../../../../constants/api.js";import{DEFAULT_ANONYMOUS_VISITOR_TEAM as c,RBAC_ALL_OTHER_TEAMS as u,RbacFeatures as h}from"../../../../constants/common.js";import{withPathPrefix as A}from"@redocly/theme/core/utils";function i(e){return!e||typeof e!="object"||Object.keys(e).length===0?!1:!(e[c]&&e[c]!=="none"||e[u]&&e[u]!=="none")}function m(e,t){if(!t||Object.keys(t).length===0)return e;const n=t.content;if(n&&Object.keys(n).length>0&&Object.values(n).some(i))return!0;const r=t.teamFoldersBaseRoles;if(i(r))return!0;const s=t.features;return i(s?.[h.MCP])?!0:e}function P(e){const t=e.getConfig().access;return m(!!t?.requiresLogin,t?.rbac||{})}async function M(e,t){const n=e.headers.get("Authorization");if(!n)return{isAuthenticated:!1};const r=l(n),s=t?.config?.ssoDirect||{},o=r?await f(s,{authorization:r}):{};return r&&o&&o.isAuthenticated?{isAuthenticated:!0,isTokenValid:!0,currentUser:{teams:o.teams||[],email:o.email||"",claims:o,isAuthenticated:!0,idpAccessToken:o.idpAccessToken||void 0,idpId:o.idpId||void 0},accessToken:r}:{isAuthenticated:!1,isTokenValid:!1}}function d(e,t){const n=`${e}${a.MCP_OAUTH_PROTECTED_RESOURCE}${A("/mcp")}`,r=`${e}${a.MCP_OAUTH_AUTHORIZATION_SERVER}`,s=t?[`error="${t.code}"`,`error_description="${t.description}"`]:[];return s.push(`resource_metadata="${n}"`,`scope="${p.join(" ")}"`,`authorization_uri="${r}"`),`Bearer ${s.join(", ")}`}function E(e){return new Response(JSON.stringify({error:"unauthorized",message:"Authentication required"}),{status:401,headers:{"Content-Type":"application/json","WWW-Authenticate":d(e),"Access-Control-Allow-Origin":"*"}})}function S(){return new Response(JSON.stringify({error:"forbidden",message:"You do not have access to this MCP server"}),{status:403,headers:{"Content-Type":"application/json","Access-Control-Allow-Origin":"*"}})}function y(e){return new Response(JSON.stringify({error:"invalid_token",message:"Invalid or expired token"}),{status:401,headers:{"Content-Type":"application/json","WWW-Authenticate":d(e,{code:"invalid_token",description:"Invalid or expired token"}),"Access-Control-Allow-Origin":"*"}})}export{S as constructForbiddenResponse,y as constructInvalidTokenResponse,E as constructUnauthorizedResponse,M as handleMcpAuth,P as isMcpContentProtected,m as shouldHandleMcpAuth};
1
+ import{extractTokenFromAuthHeader as p}from"../../../plugins/mcp/utils/jwt.js";import{SUPPORTED_MCP_SCOPES as h}from"../constants.js";import{getUserParamsFromCookies as A}from"../../../web-server/auth.js";import{ServerRoutes as u}from"../../../../constants/api.js";import{DEFAULT_ANONYMOUS_VISITOR_TEAM as d,RBAC_ALL_OTHER_TEAMS as f,RbacFeatures as m}from"../../../../constants/common.js";import{withPathPrefix as T}from"@redocly/theme/core/utils";import{checkTokenAudience as R,isTokenAudienceEnforced as O,toAudienceList as k}from"./token-audience.js";import{reportMcpTokenAudienceMismatch as _}from"./token-audience-telemetry.js";function s(e){return!e||typeof e!="object"||Object.keys(e).length===0?!1:!(e[d]&&e[d]!=="none"||e[f]&&e[f]!=="none")}function C(e,t){if(!t||Object.keys(t).length===0)return e;const r=t.content;if(r&&Object.keys(r).length>0&&Object.values(r).some(s))return!0;const o=t.teamFoldersBaseRoles;if(s(o))return!0;const i=t.features;return s(i?.[m.MCP])?!0:e}function x(e){const t=e.getConfig().access;return C(!!t?.requiresLogin,t?.rbac||{})}async function v(e,t){const r=e.headers.get("Authorization");if(!r)return{isAuthenticated:!1};const o=p(r),i=t?.config?.ssoDirect||{},n=o?await A(i,{authorization:o}):{};if(!(o&&n&&n.isAuthenticated))return{isAuthenticated:!1,isTokenValid:!1};const a=n.aud;if(R(a)==="mismatch"){const c=O();if(_({audience:k(a).join(","),enforced:c}),c)return{isAuthenticated:!1,isTokenValid:!1}}return{isAuthenticated:!0,isTokenValid:!0,currentUser:{teams:n.teams||[],email:n.email||"",claims:n,isAuthenticated:!0,idpAccessToken:n.idpAccessToken||void 0,idpId:n.idpId||void 0},accessToken:o}}function l(e,t){const r=`${e}${u.MCP_OAUTH_PROTECTED_RESOURCE}${T("/mcp")}`,o=`${e}${u.MCP_OAUTH_AUTHORIZATION_SERVER}`,i=t?[`error="${t.code}"`,`error_description="${t.description}"`]:[];return i.push(`resource_metadata="${r}"`,`scope="${h.join(" ")}"`,`authorization_uri="${o}"`),`Bearer ${i.join(", ")}`}function w(e){return new Response(JSON.stringify({error:"unauthorized",message:"Authentication required"}),{status:401,headers:{"Content-Type":"application/json","WWW-Authenticate":l(e),"Access-Control-Allow-Origin":"*"}})}function F(){return new Response(JSON.stringify({error:"forbidden",message:"You do not have access to this MCP server"}),{status:403,headers:{"Content-Type":"application/json","Access-Control-Allow-Origin":"*"}})}function H(e){return new Response(JSON.stringify({error:"invalid_token",message:"Invalid or expired token"}),{status:401,headers:{"Content-Type":"application/json","WWW-Authenticate":l(e,{code:"invalid_token",description:"Invalid or expired token"}),"Access-Control-Allow-Origin":"*"}})}export{F as constructForbiddenResponse,H as constructInvalidTokenResponse,w as constructUnauthorizedResponse,v as handleMcpAuth,x as isMcpContentProtected,C as shouldHandleMcpAuth};
@@ -0,0 +1,7 @@
1
+ type TokenAudienceMismatchEvent = {
2
+ audience: string;
3
+ enforced: boolean;
4
+ };
5
+ export declare function reportMcpTokenAudienceMismatch({ audience, enforced, }: TokenAudienceMismatchEvent): void;
6
+ export {};
7
+ //# sourceMappingURL=token-audience-telemetry.d.ts.map
@@ -0,0 +1 @@
1
+ import{telemetry as t}from"../../../telemetry/index.js";import{logger as o}from"../../../tools/notifiers/logger.js";import{McpServerType as c}from"../constants.js";import{serverAttributes as m}from"../utils/telemetry-attributes.js";function a({audience:e,enforced:r}){try{t.sendMcpTokenAudienceMismatchMessage([{...m(c.Docs),audience:e,enforced:r}])}catch{}o.warn(`MCP token audience mismatch [audience=${e}] enforced=${r}`)}export{a as reportMcpTokenAudienceMismatch};
@@ -0,0 +1,6 @@
1
+ import type { McpUserInfo } from '../types.js';
2
+ export type TokenAudienceResult = 'match' | 'mismatch' | 'skipped';
3
+ export declare function toAudienceList(aud: McpUserInfo['aud']): string[];
4
+ export declare function checkTokenAudience(aud: McpUserInfo['aud']): TokenAudienceResult;
5
+ export declare function isTokenAudienceEnforced(): boolean;
6
+ //# sourceMappingURL=token-audience.d.ts.map
@@ -0,0 +1 @@
1
+ import{envConfig as t}from"../../../config/env-config.js";function i(n){return n?(Array.isArray(n)?n:[n]).filter(e=>typeof e=="string"&&!!e):[]}function c(n){const e=t.ORGANIZATION_ID,r=i(n);return!e||r.length===0?"skipped":r.includes(e)?"match":"mismatch"}function f(){return t.REDOCLY_MCP_ENFORCE_TOKEN_AUDIENCE===!0}export{c as checkTokenAudience,f as isTokenAudienceEnforced,i as toAudienceList};
@@ -1 +1 @@
1
- import{mcpToolHandlers as l}from"../../../../../client/mcp-tool-handlers-entry.js";import{runInSandbox as p}from"../../../../sandbox/sandbox.js";import{isMcpToolAvailable as h}from"../../workers/execute-mcp-tool.js";import{buildExecuteHostFetch as b,isFetchCapable as E}from"../../gateway-mcp/fetch-capability.js";import{withAuthRequiredMeta as T}from"../../gateway-mcp/upstream-auth.js";import{CODE_MODE_TOOL_NAMES as C,EXECUTE_TOOL_NAME as O}from"../constants.js";import{sanitizeToolName as A}from"../build-tool-type-declarations.js";import{invokeTool as w}from"../invoke-tool.js";import{createSandboxSetup as x}from"../sandbox/create-sandbox-setup.js";import{auditCode as y}from"../code-audit.js";import{reportCodeExecuted as M}from"../code-execution-telemetry.js";import{logCodeExecutionAudit as N}from"../code-execution-audit.js";const v=async(e,t,r)=>{const o=await F(t,r),n=[],i=E(t)?b(t,c=>n.push(c)):void 0;let a=0;const u=i?c=>(a+=1,i(c)):void 0,d=y(e.code);N({audit:d,code:e.code,description:e.description,sessionHandle:e.sessionHandle,toolNames:Object.keys(o),fetchBudget:t.gatewayFetchBudgetPerExec,fetchCapable:i!==void 0});const m=Date.now(),{result:f,error:s}=await p(e.code,{setupContext:x(o,u)});return M({audit:d,fetchCount:a,outcome:s===void 0?"ok":"error",durationMs:Date.now()-m}),T({content:[{type:"text",text:JSON.stringify({result:f,error:s})}],isError:s!==void 0},n)};async function F(e,t){const r={};for(const o of Object.keys(l))C.has(o)||!await h({toolName:o,context:e}).catch(()=>!1)||(r[A(o)]=i=>w(o,i,e,t));return r}var J={[O]:v};export{J as default};
1
+ import{mcpToolHandlers as l}from"../../../../../client/mcp-tool-handlers-entry.js";import{runInSandbox as p}from"../../../../sandbox/sandbox.js";import{isMcpToolAvailable as h}from"../../workers/execute-mcp-tool.js";import{buildExecuteHostFetch as b,isFetchCapable as E}from"../../gateway-mcp/fetch-capability.js";import{withAuthRequiredMeta as T}from"../../gateway-mcp/upstream-auth.js";import{CODE_MODE_TOOL_NAMES as C,EXECUTE_TOOL_NAME as O}from"../constants.js";import{sanitizeToolName as w}from"../build-tool-type-declarations.js";import{invokeTool as A}from"../invoke-tool.js";import{createSandboxSetup as x}from"../sandbox/create-sandbox-setup.js";import{auditCode as y}from"../code-audit.js";import{reportCodeExecuted as M}from"../code-execution-telemetry.js";import{logCodeExecutionAudit as N}from"../code-execution-audit.js";const v=async(e,t,r)=>{const o=await F(t,r),n=[],i=E(t)?await b(t,a=>n.push(a)):void 0;let c=0;const u=i?a=>(c+=1,i(a)):void 0,d=y(e.code);N({audit:d,code:e.code,description:e.description,sessionHandle:e.sessionHandle,toolNames:Object.keys(o),fetchBudget:t.gatewayFetchBudgetPerExec,fetchCapable:i!==void 0});const m=Date.now(),{result:f,error:s}=await p(e.code,{setupContext:x(o,u)});return M({audit:d,fetchCount:c,outcome:s===void 0?"ok":"error",durationMs:Date.now()-m}),T({content:[{type:"text",text:JSON.stringify({result:f,error:s})}],isError:s!==void 0},n)};async function F(e,t){const r={};for(const o of Object.keys(l))C.has(o)||!await h({toolName:o,context:e}).catch(()=>!1)||(r[w(o)]=i=>A(o,i,e,t));return r}var J={[O]:v};export{J as default};
@@ -14,6 +14,7 @@ export declare function isManageApiCredentialsToolAvailable(context: McpToolCont
14
14
  export declare function manageApiCredentialsSchema(context: McpToolContext): McpToolSchema;
15
15
  export declare function manageApiCredentials(context: McpToolContext, deps: ManageApiCredentialsDeps): (args: {
16
16
  api?: unknown;
17
+ scheme?: unknown;
17
18
  sessionHandle?: unknown;
18
19
  }) => Promise<CallToolResult | InputRequiredResult>;
19
20
  //# sourceMappingURL=manage-credentials.d.ts.map
@@ -1,2 +1,2 @@
1
- import{MANAGE_API_CREDENTIALS_TOOL_NAME as m}from"../../constants.js";import{buildUpstreamCredentialFallback as h,buildUpstreamCredentialInputRequired as f}from"../../gateway-mcp/elicitation.js";import{getCallableApis as o,isFetchCapable as g}from"../../gateway-mcp/fetch-capability.js";import{secretStore as A}from"../../gateway-mcp/secret-store.js";import{MISSING_SESSION_HANDLE_MESSAGE as v,resolveSecretSubject as b}from"../../gateway-mcp/subject.js";import{resolveUpstreamAuthScheme as y}from"../../gateway-mcp/upstream-auth-scheme.js";function k(e){return!!e.elicitationEnabled&&g(e)}function j(e){const t=o(e).map(n=>n.relativePath);return{name:m,description:["Get a secure link where the user sets, replaces, or removes the credentials this server sends to a documented API.","Call it when the user wants to change or clear an API key, or when a tool result tells you the stored credentials were rejected.","It returns a link for the user to open - never ask for the secret in the conversation and never pass it as an argument."].join(`
2
- `),annotations:{title:"Manage API credentials",readOnlyHint:!1,openWorldHint:!1},schema:{type:"object",required:["api"],additionalProperties:!1,properties:{api:{type:"string",description:`The API to manage credentials for.${t.length>0?` One of: ${t.join(", ")}.`:""}`,minLength:1,...t.length>0?{enum:t}:{}},sessionHandle:{type:"string",description:"Handle returned by createAnonymousSession. Required while the caller is anonymous, so the credentials are stored against the same subject the API calls use.",minLength:1}}}}}function H(e,i){return async t=>{const n=b(e.user,typeof t.sessionHandle=="string"?t.sessionHandle:void 0);if(n.kind==="invalid")return l(n.message);if(n.kind==="anonymous")return l(v);const{subject:u}=n,s=typeof t.api=="string"?t.api:"",r=o(e).find(a=>a.relativePath===s||a.name===s);if(!r){const a=o(e).map(d=>d.relativePath).join(", ");return l(`Unknown api "${s}". Credentials can only be managed for the APIs this server can call: ${a||"none"}.`)}const c=await i.getKv(),p={subject:u,baseUrl:e.baseUrl??"",target:{api:r.relativePath,name:r.name},auth:await y(e,r.relativePath),kv:c,hasExistingSecret:await A.hasSecret(c,u,r.relativePath),reason:{kind:"requested"}};return i.getClientCapabilities()?.elicitation?.url?await f(p):{content:[{type:"text",text:await h(p)}],isError:!1}}}function l(e){return{content:[{type:"text",text:e}],isError:!0}}export{k as isManageApiCredentialsToolAvailable,H as manageApiCredentials,j as manageApiCredentialsSchema};
1
+ import{MANAGE_API_CREDENTIALS_TOOL_NAME as y}from"../../constants.js";import{buildUpstreamCredentialFallback as b,buildUpstreamCredentialInputRequired as v,schemeLabelOf as w}from"../../gateway-mcp/elicitation.js";import{getCallableApis as u,isFetchCapable as P}from"../../gateway-mcp/fetch-capability.js";import{secretStore as S}from"../../gateway-mcp/secret-store.js";import{MISSING_SESSION_HANDLE_MESSAGE as I,resolveSecretSubject as k}from"../../gateway-mcp/subject.js";import{resolveUpstreamApiAuth as j}from"../../gateway-mcp/upstream-auth-scheme.js";function q(e){return!!e.elicitationEnabled&&P(e)}function H(e){const t=u(e).map(s=>s.relativePath);return{name:y,description:["Get a secure link where the user sets, replaces, or removes the credentials this server sends to a documented API.","Call it when the user wants to change or clear an API key, or when a tool result tells you the stored credentials were rejected.","When a tool result lists several kinds of credential for an operation, ask the user which one they hold and wait for the answer before calling this tool, then pass that name as scheme.","It returns a link for the user to open - never ask for the secret in the conversation and never pass it as an argument."].join(`
2
+ `),annotations:{title:"Manage API credentials",readOnlyHint:!1,openWorldHint:!1},schema:{type:"object",required:["api"],additionalProperties:!1,properties:{api:{type:"string",description:`The API to manage credentials for.${t.length>0?` One of: ${t.join(", ")}.`:""}`,minLength:1,...t.length>0?{enum:t}:{}},scheme:{type:"string",description:"Name of the security scheme to manage the credential for, as named in the API description (a tool result that reports a rejected credential names it). Omit it when the API has a single scheme.",minLength:1},sessionHandle:{type:"string",description:"Handle returned by createAnonymousSession. Required while the caller is anonymous, so the credentials are stored against the same subject the API calls use.",minLength:1}}}}}function U(e,c){return async t=>{const s=k(e.user,typeof t.sessionHandle=="string"?t.sessionHandle:void 0);if(s.kind==="invalid")return i(s.message);if(s.kind==="anonymous")return i(I);const{subject:d}=s,h=typeof t.api=="string"?t.api:"",n=u(e).find(l=>l.relativePath===h||l.name===h);if(!n){const l=u(e).map(A=>A.relativePath).join(", ");return i(`Unknown api "${h}". Credentials can only be managed for the APIs this server can call: ${l||"none"}.`)}const a=await j(e,n.relativePath),r=typeof t.scheme=="string"?t.scheme:void 0,m=Object.keys(a.schemes);if(r&&!a.schemes[r])return i(`Unknown scheme "${r}" for api "${n.relativePath}". The security schemes this server can store credentials for are: ${m.join(", ")}.`);if(!r&&m.length>1)return i(`The "${n.name}" API has more than one security scheme; call this tool again with scheme set to one of: ${m.join(", ")}.`);const o=r??a.defaultScheme,p=w(a.schemes,o),f=await c.getKv(),g={subject:d,baseUrl:e.baseUrl??"",target:{api:n.relativePath,name:n.name,scheme:o,...p?{schemeLabel:p}:{}},auth:a.schemes[o],kv:f,hasExistingSecret:await S.hasSecret(f,d,n.relativePath,o),reason:{kind:"requested"}};return c.getClientCapabilities()?.elicitation?.url?await v(g):{content:[{type:"text",text:await b(g)}],isError:!1}}}function i(e){return{content:[{type:"text",text:e}],isError:!0}}export{q as isManageApiCredentialsToolAvailable,U as manageApiCredentials,H as manageApiCredentialsSchema};
@@ -1 +1 @@
1
- import a from"node:path";import{existsSync as f}from"node:fs";import{readFile as d}from"node:fs/promises";import{replaceFileExtension as h}from"../../../../../plugins/openapi-docs/store-definition-bundles";import{PUBLIC_API_DEFINITIONS_FOLDER as u}from"../../../../../constants/common";import{filterDataByAccessDeep as l}from"../../../../../utils/rbac";import{checkEndpointAndDeleteXMcp as c}from"../../../utils/xmcp-utils.js";import{HTTP_METHODS as y}from"./constants.js";function P(t){return typeof t=="object"&&t!==null&&"responses"in t&&typeof t.responses=="object"}function S(t){const{paths:n={}}=t,e=[];for(const[r,i]of Object.entries(n)){const s=!c(i,"docs");for(const[p,o]of Object.entries(i))y.has(p.toLowerCase())&&(s||!c(o,"docs")||e.push({path:r,method:p.toUpperCase(),summary:o.summary,description:o.description,security:o.security}))}return e}async function T({relativePath:t,outdir:n,user:e,rbac:r={},requiresLogin:i=!1}){const s=a.join(n||"",u,h(t,".json"));if(!f(s))return;const o=await d(s,"utf-8"),m=JSON.parse(o);return l(m,{isAuthenticated:e?.isAuthenticated,email:e?.email,teams:e?.teams},r,i)}export{T as getApiDescriptionFromFs,S as getEndpointsFromPaths,P as isMcpEndpoint};
1
+ import a from"node:path";import{existsSync as f}from"node:fs";import{readFile as d}from"node:fs/promises";import{replaceFileExtension as h}from"../../../../../plugins/openapi-docs/store-definition-bundles.js";import{PUBLIC_API_DEFINITIONS_FOLDER as u}from"../../../../../constants/common.js";import{filterDataByAccessDeep as l}from"../../../../../utils/rbac.js";import{checkEndpointAndDeleteXMcp as c}from"../../../utils/xmcp-utils.js";import{HTTP_METHODS as y}from"./constants.js";function P(t){return typeof t=="object"&&t!==null&&"responses"in t&&typeof t.responses=="object"}function S(t){const{paths:n={}}=t,e=[];for(const[r,i]of Object.entries(n)){const s=!c(i,"docs");for(const[p,o]of Object.entries(i))y.has(p.toLowerCase())&&(s||!c(o,"docs")||e.push({path:r,method:p.toUpperCase(),summary:o.summary,description:o.description,security:o.security}))}return e}async function T({relativePath:t,outdir:n,user:e,rbac:r={},requiresLogin:i=!1}){const s=a.join(n||"",u,h(t,".json"));if(!f(s))return;const o=await d(s,"utf-8"),m=JSON.parse(o);return l(m,{isAuthenticated:e?.isAuthenticated,email:e?.email,teams:e?.teams},r,i)}export{T as getApiDescriptionFromFs,S as getEndpointsFromPaths,P as isMcpEndpoint};
@@ -0,0 +1,4 @@
1
+ import type { UpstreamAuthScheme } from './upstream-auth-scheme.js';
2
+ export declare function rejectCredential(auth: UpstreamAuthScheme, value: string): string | undefined;
3
+ export declare function assertHeaderSafe(header: string, value: string): void;
4
+ //# sourceMappingURL=credential-validation.d.ts.map
@@ -0,0 +1 @@
1
+ const r=/[\r\n]/,o=255;function a(n){for(let e=0;e<n.length;e+=1){const t=n.charCodeAt(e);if(t===0||t>255)return!0}return!1}function s(n,e){if(!e)return"Enter a value before saving.";if(r.test(e))return"The value contains a line break. Paste it as a single line and save again.";if(a(e))return"The value contains a character that cannot be sent in an HTTP header, such as a curly quote or an invisible character. Copy the value again as plain text and save.";if(n.kind==="cookie")return i(n.name,e)}function i(n,e){if(e.includes(";")||e.toLowerCase().includes(`${n.toLowerCase()}=`))return`This looks like a whole cookie header. Paste only the value of the ${n} cookie, without the "${n}=" prefix and without any other name=value pairs.`}function c(n,e){if(!(!r.test(e)&&!a(e)))throw new Error(`The credential cannot be sent as the ${n} header value.`)}export{c as assertHeaderSafe,s as rejectCredential};
@@ -1,11 +1,13 @@
1
1
  import type { InputRequiredResult } from '@modelcontextprotocol/server';
2
2
  import type { UpstreamAuthRequiredEvent } from './upstream-auth.js';
3
- import type { UpstreamAuthScheme } from './upstream-auth-scheme.js';
3
+ import type { SchemeChoice, UpstreamAuthScheme } from './upstream-auth-scheme.js';
4
4
  import type { KvService } from '@redocly/config';
5
5
  export declare const CREDENTIALS_INPUT_REQUEST_KEY = "credentials";
6
6
  export type CredentialTarget = {
7
7
  api: string;
8
8
  name: string;
9
+ scheme: string;
10
+ schemeLabel?: string;
9
11
  };
10
12
  /**
11
13
  * Why the prompt is being raised. `authFailure` is the automatic path behind an upstream 401;
@@ -28,7 +30,7 @@ type CredentialElicitationRequest = {
28
30
  reason: CredentialElicitationReason;
29
31
  };
30
32
  export declare function isCredentialElicitationDeclined(inputResponses: Record<string, unknown> | undefined): boolean;
31
- export declare function targetOf(event: UpstreamAuthRequiredEvent): CredentialTarget;
33
+ export declare function schemeLabelOf(schemes: Record<string, unknown>, scheme: string): string | undefined;
32
34
  /**
33
35
  * The 2026-07-28-era credentials prompt: the tool call returns an input-required result the
34
36
  * client fulfils and retries, with no push `elicitation/create` and no session behind it.
@@ -43,6 +45,12 @@ export declare function buildUpstreamCredentialFallback(request: CredentialElici
43
45
  * upstream rejected, or a 403/407 that is more likely a permissions problem than a missing key.
44
46
  * Minting another link here is what produced the credentials-link loop.
45
47
  */
46
- export declare function buildCredentialsToolHint(event: UpstreamAuthRequiredEvent): string;
48
+ export declare function buildCredentialsToolHint(event: UpstreamAuthRequiredEvent, schemeLabel?: string): string;
49
+ /**
50
+ * Text for an operation that accepts several security schemes and has no stored credential for
51
+ * any of them. Picking one here is what sent an API key as a session cookie, so the model is told
52
+ * to ask the user which credential they hold and pass it back as `scheme`.
53
+ */
54
+ export declare function buildSchemeChoiceHint(event: UpstreamAuthRequiredEvent, choices: readonly SchemeChoice[]): string;
47
55
  export {};
48
56
  //# sourceMappingURL=elicitation.d.ts.map
@@ -1,3 +1,4 @@
1
- import{inputRequired as c,inputResponse as f}from"@modelcontextprotocol/server";import{MANAGE_API_CREDENTIALS_TOOL_NAME as T}from"../constants.js";import{secretStore as $,ELICITATION_TTL_MS as A}from"./secret-store.js";import{ANONYMOUS_SUBJECT_PREFIX as l}from"./subject.js";const h="credentials";function C(e){const t=f(e,h);return t.kind==="elicit"&&(t.action==="decline"||t.action==="cancel")}function _(e){return{api:e.api,name:e.name}}async function b(e){const{url:t}=await d(e);return c({inputRequests:{[h]:c.elicitUrl({message:P(e.target.name,e.hasExistingSecret),url:t})}})}async function O(e){const{url:t}=await d(e);return y(e,t,I(e.subject))}function R(e){return[e.status===401?`The stored credentials for "${e.name}" were rejected (HTTP 401).`:`The "${e.name}" API rejected the request with HTTP ${e.status}.`,"",`Do not retry the same call. Call \`${T}\` with api: "${e.api}" to get a link the user has to open in a browser to replace or remove the stored credentials, then retry once they confirm they saved them.`].join(`
2
- `)}async function d({kv:e,subject:t,baseUrl:n,target:i,auth:a,hasExistingSecret:o}){const r=await $.createElicitation(e,{subject:t,api:i.api,name:i.name,auth:a,hasExistingSecret:o});return{token:r,url:g(n,r)}}function I(e){return e.startsWith(l)?e.slice(l.length):void 0}function P(e,t){const n=`The link works for ${u()} minutes.`;return t?`Open this page in a browser to replace or remove the stored credentials for the "${e}" API. They go straight to the API and never enter the chat. ${n}`:`The "${e}" API needs credentials. Open this page in a browser to paste them - they go straight to the API and never enter the chat. ${n}`}function u(){return Math.round(A/6e4)}function g(e,t){if(!e)return`/mcp/credentials?token=${t}`;try{const n=new URL("/mcp/credentials",e);return n.searchParams.set("token",t),n.toString()}catch{return`${e}/mcp/credentials?token=${t}`}}function y({target:e,reason:t,hasExistingSecret:n},i,a){const r=[`**Stop and show the user this link. They have to open it in a browser to ${n?`replace or remove the stored credentials for the "${e.name}" API`:`add credentials for the "${e.name}" API`} - nothing continues until they do.**`,"",i,"",`The link is valid ${u()} minutes and opens a form on this site. Credentials go straight to the API from there: never ask for them in the conversation and never pass them as a tool argument.`,"",t.kind==="authFailure"?`The upstream API "${e.name}" returned ${t.status} and needs credentials.`:n?`Credentials are already stored for the "${e.name}" API; the link lets the user replace or remove them.`:`The "${e.name}" API needs credentials.`,a?`Once the user confirms they saved them, call this tool again with sessionHandle: "${a}" - the credentials are stored against that handle, applied server-side, and never appear in the conversation.`:"Once the user confirms they saved them, call this tool again - the credentials are applied server-side and never appear in the conversation."],s=t.kind==="authFailure"?t.otherApiNames??[]:[];if(s.length>0){const p=s.map(m=>`"${m}"`).join(", ");r.push("",`The remaining APIs (${p}) will prompt for credentials on subsequent calls.`)}return r.join(`
3
- `)}export{h as CREDENTIALS_INPUT_REQUEST_KEY,R as buildCredentialsToolHint,O as buildUpstreamCredentialFallback,b as buildUpstreamCredentialInputRequired,C as isCredentialElicitationDeclined,_ as targetOf};
1
+ import{inputRequired as c,inputResponse as $}from"@modelcontextprotocol/server";import{MANAGE_API_CREDENTIALS_TOOL_NAME as h}from"../constants.js";import{secretStore as T,ELICITATION_TTL_MS as A}from"./secret-store.js";import{ANONYMOUS_SUBJECT_PREFIX as l}from"./subject.js";const d="credentials";function O(e){const t=$(e,d);return t.kind==="elicit"&&(t.action==="decline"||t.action==="cancel")}function _(e,t){return Object.keys(e).length>1?t:void 0}async function L(e){const{url:t}=await u(e);return c({inputRequests:{[d]:c.elicitUrl({message:y(e.target,e.hasExistingSecret),url:t})}})}async function N(e){const{url:t}=await u(e);return b(e,t,w(e.subject))}function S(e,t){const n=e.status===401?`The stored credentials for "${e.name}" were rejected (HTTP 401).`:`The "${e.name}" API rejected the request with HTTP ${e.status}.`,i=t?`api: "${e.api}" and scheme: "${t}"`:`api: "${e.api}"`;return[n,"",`Do not retry the same call. Call \`${h}\` with ${i} to get a link the user has to open in a browser to replace or remove the stored credentials, then retry once they confirm they saved them.`].join(`
2
+ `)}function j(e,t){const n=t.map(({name:i,label:r,description:a})=>`- ${i} \u2014 ${r}${a?`: ${a}`:""}`);return[`The "${e.name}" API rejected the request with HTTP ${e.status} and this operation accepts more than one kind of credential:`,"",...n,"","Ask the user which one of these they have, and wait for the answer. Never guess and never reuse a value meant for another kind.",`Then call \`${h}\` with api: "${e.api}" and scheme set to the name they picked to get a link where they enter it.`].join(`
3
+ `)}async function u({kv:e,subject:t,baseUrl:n,target:i,auth:r,hasExistingSecret:a}){const o=await T.createElicitation(e,{subject:t,api:i.api,name:i.name,scheme:i.scheme,...i.schemeLabel?{schemeLabel:i.schemeLabel}:{},auth:r,hasExistingSecret:a});return{token:o,url:P(n,o)}}function w(e){return e.startsWith(l)?e.slice(l.length):void 0}function y(e,t){const n=`The link works for ${m()} minutes.`,i=I(e);return t?`Open this page in a browser to replace or remove the stored credentials for ${i}. They go straight to the API and never enter the chat. ${n}`:`${k(i)} needs credentials. Open this page in a browser to paste them - they go straight to the API and never enter the chat. ${n}`}function I({name:e,schemeLabel:t}){return t?`the "${t}" scheme of the "${e}" API`:`the "${e}" API`}function k(e){return e.charAt(0).toUpperCase()+e.slice(1)}function m(){return Math.round(A/6e4)}function P(e,t){if(!e)return`/mcp/credentials?token=${t}`;try{const n=new URL("/mcp/credentials",e);return n.searchParams.set("token",t),n.toString()}catch{return`${e}/mcp/credentials?token=${t}`}}function b({target:e,reason:t,hasExistingSecret:n},i,r){const o=[`**Stop and show the user this link. They have to open it in a browser to ${n?`replace or remove the stored credentials for the "${e.name}" API`:`add credentials for the "${e.name}" API`} - nothing continues until they do.**`,"",i,"",`The link is valid ${m()} minutes and opens a form on this site. Credentials go straight to the API from there: never ask for them in the conversation and never pass them as a tool argument.`,"",t.kind==="authFailure"?`The upstream API "${e.name}" returned ${t.status} and needs credentials.`:n?`Credentials are already stored for the "${e.name}" API; the link lets the user replace or remove them.`:`The "${e.name}" API needs credentials.`,...e.schemeLabel?[`The operation authenticates with its "${e.schemeLabel}" security scheme.`]:[],r?`Once the user confirms they saved them, call this tool again with sessionHandle: "${r}" - the credentials are stored against that handle, applied server-side, and never appear in the conversation.`:"Once the user confirms they saved them, call this tool again - the credentials are applied server-side and never appear in the conversation."],s=t.kind==="authFailure"?t.otherApiNames??[]:[];if(s.length>0){const p=s.map(f=>`"${f}"`).join(", ");o.push("",`The remaining APIs (${p}) will prompt for credentials on subsequent calls.`)}return o.join(`
4
+ `)}export{d as CREDENTIALS_INPUT_REQUEST_KEY,S as buildCredentialsToolHint,j as buildSchemeChoiceHint,N as buildUpstreamCredentialFallback,L as buildUpstreamCredentialInputRequired,O as isCredentialElicitationDeclined,_ as schemeLabelOf};
@@ -3,11 +3,20 @@ import type { SandboxFetch } from '../../codemode/types.js';
3
3
  import type { UpstreamAuthRequiredEvent } from '../upstream-auth.js';
4
4
  import type { StoredSecret } from '../secret-store.js';
5
5
  export declare function getDefaultAgent(): Agent;
6
+ export type FetchBridgeRoute = {
7
+ pattern: RegExp;
8
+ method: string;
9
+ schemes: readonly string[];
10
+ };
6
11
  export type FetchBridgeApi = {
7
12
  slug: string;
8
13
  name: string;
9
14
  matchers: readonly RegExp[];
10
- secret?: StoredSecret;
15
+ secrets?: Readonly<Record<string, StoredSecret>>;
16
+ defaultScheme?: string;
17
+ routes?: readonly FetchBridgeRoute[];
18
+ credentialHeaders?: readonly string[];
19
+ schemePriority?: readonly string[];
11
20
  };
12
21
  type FetchBridgeOptions = {
13
22
  allowedHosts: readonly RegExp[];
@@ -1 +1 @@
1
- import{Agent as W}from"undici";import{envConfig as I}from"../../../../config/env-config.js";import{logger as R}from"../../../../tools/notifiers/logger.js";import{assertUrlAllowed as B}from"./ssrf-guard.js";import{createSsrfSafeLookup as J}from"./ssrf-safe-lookup.js";import{SsrfBlockedError as C}from"./ssrf-blocklist.js";import{GatewayFetchBlockedError as $,GatewayFetchSystemError as K,GatewayFetchUserError as U}from"./fetch-errors.js";import{redactHeaders as x,redactSecretsFromString as V}from"./redact.js";import{normalizeFetchPath as X}from"./normalize-path.js";import{reportGatewayFetch as G}from"./fetch-telemetry.js";import{logGatewayFetchAudit as O}from"./fetch-audit.js";const N="x-forwarded-for",Y=3e4,z=1024*1024,Q=new Set([401,403,407]);let M;function Z(){if(!M){const t=I.isDevelopMode;t&&R.warn("Gateway MCP SSRF guard: loopback upstreams are ALLOWED (develop mode only, never in runtime)."),M=new W({connect:{lookup:J({allowLoopback:t})}})}return M}function be({allowedHosts:t,apis:e=[],authorization:o,onAuthRequired:s,fetchImpl:i=fetch,dispatcher:u=Z(),timeoutMs:d=Y,maxResponseBytes:h=z,maxFetchesPerExec:f,clientIp:m}){const k=[...t,...e.flatMap(r=>r.matchers)],L=[o,...e.map(r=>r.secret?.value)].filter(r=>!!r),v=e.map(r=>r.secret?.header).filter(r=>!!r);let H=0;return async r=>{const w=r.method??"GET",A=Date.now();let _,g,b,S={},T,D;try{if(f!==void 0){const l=Math.max(0,f);if(H+=1,H>l)throw new U(`Outbound fetch budget exceeded (max ${l} fetches per execute); split the work across calls`)}const n=B(r.url,k);_=n.hostname,g=X(n.pathname);const E=e.filter(l=>l.matchers.some(P=>P.test(n.hostname))),c=E.length===1?E[0]:void 0;b=c?.slug,S=se(r.headers,c?.secret,o,m);const p=new AbortController;D=setTimeout(()=>p.abort(),d);const a=await i(n,{method:w,headers:S,body:r.body,redirect:"manual",signal:p.signal,dispatcher:u});T=a.status,Q.has(a.status)&&c&&s&&s({api:c.slug,name:c.name,status:a.status});const F=await ae(a,h);let y=ce(a.headers);if(re(a.status)){y=x(y,v);const{location:l}=y;l&&!oe(l,n,k)&&delete y.location}return G({host:n.hostname,method:w,outcome:"success",durationMs:Date.now()-A,path:g,api:b,status:a.status,bytes:Buffer.byteLength(F,"utf8")}),O({rawUrl:n.href,method:w,host:n.hostname,outcome:"success",durationMs:Date.now()-A,injectedSecretValues:L,path:g,api:b,status:a.status,requestHeaders:S,requestBody:r.body,responseHeaders:y,responseBody:F}),{status:a.status,statusText:a.statusText,ok:a.ok,headers:y,bodyText:F}}catch(n){const{outcome:E,userSafe:c}=ee(n),p=_??(c instanceof $?c.host:void 0)??te(r.url)??"invalid-url";throw G({host:p,method:w,outcome:E,durationMs:Date.now()-A,path:g,api:b,status:T}),O({rawUrl:r.url,method:w,host:p,outcome:E,durationMs:Date.now()-A,injectedSecretValues:L,path:g,api:b,status:T,requestHeaders:S,requestBody:r.body}),c||(R.error(`Gateway MCP fetch failed [${w} ${p}]: ${V(ne(n),L)} headers=${JSON.stringify(x(S,v))}`),new K("Upstream fetch failed due to an internal error"))}finally{D!==void 0&&clearTimeout(D)}}}function q(t){let e=t;for(let o=0;o<5&&e instanceof Error;o++){if(e instanceof U||e instanceof C)return e;e=e.cause}}function ee(t){const e=q(t);return{outcome:e instanceof $||e instanceof C?"blocked":e?"user_error":"system_error",userSafe:e}}function te(t){try{return new URL(t).hostname||void 0}catch{return}}function re(t){return t>=300&&t<400}function oe(t,e,o){try{return!!B(new URL(t,e).href,o)}catch{return!1}}function ne(t){if(!(t instanceof Error))return String(t);const e=t.cause;return e instanceof Error?`${t.message}: ${e.message}`:t.message}async function ae(t,e){const o=Number(t.headers.get("content-length"));if(Number.isFinite(o)&&o>e)throw j(e,o);if(!t.body)return"";const s=t.body.getReader(),i=new TextDecoder;let u=0,d="";try{for(;;){const{done:h,value:f}=await s.read();if(h)break;if(u+=f.byteLength,u>e)throw j(e,u);d+=i.decode(f,{stream:!0})}return d+i.decode()}finally{await s.cancel().catch(()=>{})}}function j(t,e){return new U(`Response is too large (over ${t} bytes, got ${e}); request less data`)}function se(t,e,o,s){const i={},u=new Set;for(const[h,f]of Object.entries(t??{})){const m=h.toLowerCase();m==="host"||m==="content-length"||m!==N&&(u.add(m),i[h]=f)}s&&(i[N]=s);const d=e??(o?{header:"Authorization",value:o}:void 0);return d&&!u.has(d.header.toLowerCase())&&(i[d.header]=d.value),i}function ce(t){const e={};return t.forEach((o,s)=>{e[s.toLowerCase()]=o}),e}export{be as buildFetchBridge,Z as getDefaultAgent,ae as readCappedBody};
1
+ import{Agent as V}from"undici";import{envConfig as X}from"../../../../config/env-config.js";import{logger as $}from"../../../../tools/notifiers/logger.js";import{assertUrlAllowed as x}from"./ssrf-guard.js";import{createSsrfSafeLookup as Y}from"./ssrf-safe-lookup.js";import{SsrfBlockedError as B}from"./ssrf-blocklist.js";import{GatewayFetchBlockedError as G,GatewayFetchSystemError as z,GatewayFetchUserError as M}from"./fetch-errors.js";import{redactHeaders as j,redactSecretsFromString as Q}from"./redact.js";import{normalizeFetchPath as Z}from"./normalize-path.js";import{reportGatewayFetch as N}from"./fetch-telemetry.js";import{logGatewayFetchAudit as P}from"./fetch-audit.js";const W="x-forwarded-for",q=3e4,ee=1024*1024,te=new Set([401,403,407]);let U;function re(){if(!U){const e=X.isDevelopMode;e&&$.warn("Gateway MCP SSRF guard: loopback upstreams are ALLOWED (develop mode only, never in runtime)."),U=new V({connect:{lookup:Y({allowLoopback:e})}})}return U}function ke({allowedHosts:e,apis:t=[],authorization:r,onAuthRequired:o,fetchImpl:a=fetch,dispatcher:c=re(),timeoutMs:f=q,maxResponseBytes:i=ee,maxFetchesPerExec:w,clientIp:l}){const L=[...e,...t.flatMap(n=>n.matchers)],h=t.flatMap(n=>Object.values(n.secrets??{})),k=[r,...h.map(n=>n.value)].filter(n=>!!n),_=h.map(n=>n.header);let C=0;return async n=>{const p=n.method??"GET",v=Date.now();let R,y,b,A={},T,D;try{if(w!==void 0){const S=Math.max(0,w);if(C+=1,C>S)throw new M(`Outbound fetch budget exceeded (max ${S} fetches per execute); split the work across calls`)}const d=x(n.url,L);R=d.hostname,y=Z(d.pathname);const E=t.filter(S=>S.matchers.some(K=>K.test(d.hostname))),s=E.length===1?E[0]:void 0;b=s?.slug;const m=s?ie(s,d.pathname,p):void 0,H=s&&m?fe(s,m):void 0,J=H?s?.secrets?.[H]:void 0;A=he({callerHeaders:n.headers,secret:J,authorization:r,clientIp:l,credentialHeaders:s?.credentialHeaders});const O=new AbortController;D=setTimeout(()=>O.abort(),f);const u=await a(d,{method:p,headers:A,body:n.body,redirect:"manual",signal:O.signal,dispatcher:c});T=u.status,te.has(u.status)&&s&&o&&o({api:s.slug,name:s.name,status:u.status,...H?{scheme:H}:{},...m?.length?{schemes:[...m]}:{}});const F=await ue(u,i);let g=me(u.headers);if(ae(u.status)){g=j(g,_);const{location:S}=g;S&&!ce(S,d,L)&&delete g.location}return N({host:d.hostname,method:p,outcome:"success",durationMs:Date.now()-v,path:y,api:b,status:u.status,bytes:Buffer.byteLength(F,"utf8")}),P({rawUrl:d.href,method:p,host:d.hostname,outcome:"success",durationMs:Date.now()-v,injectedSecretValues:k,path:y,api:b,status:u.status,requestHeaders:A,requestBody:n.body,responseHeaders:g,responseBody:F}),{status:u.status,statusText:u.statusText,ok:u.ok,headers:g,bodyText:F}}catch(d){const{outcome:E,userSafe:s}=ne(d),m=R??(s instanceof G?s.host:void 0)??se(n.url)??"invalid-url";throw N({host:m,method:p,outcome:E,durationMs:Date.now()-v,path:y,api:b,status:T}),P({rawUrl:n.url,method:p,host:m,outcome:E,durationMs:Date.now()-v,injectedSecretValues:k,path:y,api:b,status:T,requestHeaders:A,requestBody:n.body}),s||($.error(`Gateway MCP fetch failed [${p} ${m}]: ${Q(de(d),k)} headers=${JSON.stringify(j(A,_))}`),new z("Upstream fetch failed due to an internal error"))}finally{D!==void 0&&clearTimeout(D)}}}function oe(e){let t=e;for(let r=0;r<5&&t instanceof Error;r++){if(t instanceof M||t instanceof B)return t;t=t.cause}}function ne(e){const t=oe(e);return{outcome:t instanceof G||t instanceof B?"blocked":t?"user_error":"system_error",userSafe:t}}function se(e){try{return new URL(e).hostname||void 0}catch{return}}function ae(e){return e>=300&&e<400}function ce(e,t,r){try{return!!x(new URL(e,t).href,r)}catch{return!1}}function de(e){if(!(e instanceof Error))return String(e);const t=e.cause;return t instanceof Error?`${e.message}: ${t.message}`:e.message}async function ue(e,t){const r=Number(e.headers.get("content-length"));if(Number.isFinite(r)&&r>t)throw I(t,r);if(!e.body)return"";const o=e.body.getReader(),a=new TextDecoder;let c=0,f="";try{for(;;){const{done:i,value:w}=await o.read();if(i)break;if(c+=w.byteLength,c>t)throw I(t,c);f+=a.decode(w,{stream:!0})}return f+a.decode()}finally{await o.cancel().catch(()=>{})}}function I(e,t){return new M(`Response is too large (over ${e} bytes, got ${t}); request less data`)}function ie(e,t,r){const o=e.routes?.find(a=>a.method===r&&a.pattern.test(t));return o?o.schemes:le(e)}function fe(e,t){const r=t.filter(o=>e.secrets?.[o]);return r.length===0?t[0]:r.reduce((o,a)=>{const c=e.secrets?.[o]?.savedAt??0;return(e.secrets?.[a]?.savedAt??0)>c?a:o})}function le(e){const t=Object.keys(e.secrets??{});if(t.length===0)return e.defaultScheme?[e.defaultScheme]:[];const r=(e.schemePriority??[]).filter(o=>t.includes(o));return[...r,...t.filter(o=>!r.includes(o))]}function he({callerHeaders:e,secret:t,authorization:r,clientIp:o,credentialHeaders:a}){const c={},f=new Set,i=t??(r?{header:"Authorization",value:r}:void 0),w=i?new Set((a??[]).map(l=>l.toLowerCase()).filter(l=>l!==i.header.toLowerCase())):new Set;for(const[l,L]of Object.entries(e??{})){const h=l.toLowerCase();h==="host"||h==="content-length"||h!==W&&(w.has(h)||(f.add(h),c[l]=L))}return o&&(c[W]=o),i&&!f.has(i.header.toLowerCase())&&(c[i.header]=i.value),c}function me(e){const t={};return e.forEach((r,o)=>{t[o.toLowerCase()]=r}),t}export{ke as buildFetchBridge,re as getDefaultAgent,ue as readCappedBody};
@@ -9,5 +9,5 @@ export declare function getCallableApis(context: McpToolContext): ApiDescription
9
9
  * No EntitlementsProvider read — this code runs in graphs where the provider is uninitialized.
10
10
  */
11
11
  export declare function isFetchCapable(context: McpToolContext): boolean;
12
- export declare function buildExecuteHostFetch(context: McpToolContext, onAuthRequired?: (event: UpstreamAuthRequiredEvent) => void): SandboxFetch;
12
+ export declare function buildExecuteHostFetch(context: McpToolContext, onAuthRequired?: (event: UpstreamAuthRequiredEvent) => void): Promise<SandboxFetch>;
13
13
  //# sourceMappingURL=fetch-capability.d.ts.map
@@ -1 +1 @@
1
- import{buildAllowedHostMatchers as a}from"./fetch/allowed-hosts.js";import{buildFetchBridge as s}from"./fetch/fetch-bridge.js";function i(e){return Object.values(e.apiDescriptionsMap??{}).filter(r=>r.fetchEligible)}function u(e){return i(e).length>0}function n(e,r){const l=i(e).map(t=>({slug:t.relativePath,name:t.name,matchers:a(t.servers??[]),secret:e.upstreamSecrets?.[t.relativePath]}));return s({allowedHosts:a([]),apis:l,authorization:e.upstreamAuthorization,onAuthRequired:r,maxFetchesPerExec:e.gatewayFetchBudgetPerExec,clientIp:e.clientIp})}export{n as buildExecuteHostFetch,i as getCallableApis,u as isFetchCapable};
1
+ import{buildAllowedHostMatchers as s}from"./fetch/allowed-hosts.js";import{buildFetchBridge as c}from"./fetch/fetch-bridge.js";import{credentialHeadersOf as o,orderedSchemesOf as u,resolveUpstreamApiAuth as h}from"./upstream-auth-scheme.js";function i(e){return Object.values(e.apiDescriptionsMap??{}).filter(a=>a.fetchEligible)}function p(e){return i(e).length>0}async function f(e,a){const l=await Promise.all(i(e).map(async t=>{const r=await h(e,t.relativePath);return{slug:t.relativePath,name:t.name,matchers:s(t.servers??[]),secrets:e.upstreamSecrets?.[t.relativePath],defaultScheme:r.defaultScheme,routes:r.routes,credentialHeaders:o(r.schemes),schemePriority:u(r.schemes)}}));return c({allowedHosts:s([]),apis:l,authorization:e.upstreamAuthorization,onAuthRequired:a,maxFetchesPerExec:e.gatewayFetchBudgetPerExec,clientIp:e.clientIp})}export{f as buildExecuteHostFetch,i as getCallableApis,p as isFetchCapable};
@@ -4,20 +4,24 @@ export declare const ELICITATION_TTL_MS: number;
4
4
  export type StoredSecret = {
5
5
  header: string;
6
6
  value: string;
7
+ savedAt?: number;
7
8
  };
9
+ export type UpstreamSecrets = Record<string, Record<string, StoredSecret>>;
8
10
  export type ElicitationTarget = {
9
11
  subject: string;
10
12
  api: string;
11
13
  name: string;
14
+ scheme: string;
15
+ schemeLabel?: string;
12
16
  auth: UpstreamAuthScheme;
13
17
  hasExistingSecret?: boolean;
14
18
  };
15
19
  export declare class SecretStore {
16
20
  #private;
17
- setSecret(kv: KvService, subject: string, api: string, secret: StoredSecret): Promise<void>;
18
- getSecretsForSubject(kv: KvService, subject: string): Promise<Record<string, StoredSecret>>;
19
- hasSecret(kv: KvService, subject: string, api: string): Promise<boolean>;
20
- deleteSecret(kv: KvService, subject: string, api: string): Promise<void>;
21
+ setSecret(kv: KvService, subject: string, api: string, scheme: string, secret: StoredSecret): Promise<void>;
22
+ getSecretsForSubject(kv: KvService, subject: string): Promise<UpstreamSecrets>;
23
+ hasSecret(kv: KvService, subject: string, api: string, scheme: string): Promise<boolean>;
24
+ deleteSecret(kv: KvService, subject: string, api: string, scheme: string): Promise<void>;
21
25
  deleteSubject(kv: KvService, subject: string): Promise<void>;
22
26
  createElicitation(kv: KvService, target: ElicitationTarget): Promise<string>;
23
27
  peekElicitation(kv: KvService, token: string): Promise<ElicitationTarget | undefined>;
@@ -1 +1 @@
1
- import{createCipheriv as o,createDecipheriv as f,createHash as u,hkdfSync as a,randomBytes as h,randomUUID as l}from"node:crypto";import{JWT_SECRET_KEY as c}from"../../../constants/common.js";import{secretTtlSeconds as m}from"./subject.js";const p=900*1e3,d="mcp-upstream-secrets",y="mcp-elicitation",S="mcp-elicitation";class g{async setSecret(t,e,r,n){const i={api:r,...this.#c(this.#a(e),n,r)};await t.set(this.#t(e,r),i,{ttlInSeconds:m(e)})}async getSecretsForSubject(t,e){const r=this.#a(e),{items:n}=await t.list({prefix:this.#n(e)}),i={};for(const s of n)if(s.value)try{i[s.value.api]=this.#i(r,s.value,s.value.api)}catch{continue}return i}async hasSecret(t,e,r){return!!await t.get(this.#t(e,r))}async deleteSecret(t,e,r){await t.delete(this.#t(e,r))}async deleteSubject(t,e){const{items:r}=await t.list({prefix:this.#n(e)}),n=r.flatMap(i=>i.value?[this.#t(e,i.value.api)]:[]);n.length!==0&&await t.transaction(async i=>{for(const s of n)await i.delete(s)})}async createElicitation(t,e){const r=l();return await t.set(this.#e(r),this.#c(this.#r(),e),{ttlInSeconds:p/1e3}),r}async peekElicitation(t,e){const r=await t.get(this.#e(e));if(r)try{return this.#i(this.#r(),r)}catch{return}}async consumeElicitation(t,e){const r=this.#e(e),n=await t.transaction(async i=>{const s=await i.get(r);return s&&await i.delete(r),s});if(n)try{return this.#i(this.#r(),n)}catch{return}}#n(t){return["mcp","secret",this.#s(t)]}#t(t,e){return["mcp","secret",this.#s(t),e]}#e(t){return["mcp","elicitation",t]}#s(t){return u("sha256").update(t).digest("hex")}#a(t){return Buffer.from(a("sha256",c,t,d,32))}#r(){return Buffer.from(a("sha256",c,S,y,32))}#c(t,e,r){const n=h(12),i=o("aes-256-gcm",t,n);r&&i.setAAD(Buffer.from(r,"utf8"));const s=Buffer.concat([i.update(JSON.stringify(e),"utf8"),i.final()]);return{iv:n.toString("base64"),tag:i.getAuthTag().toString("base64"),data:s.toString("base64")}}#i(t,e,r){const n=f("aes-256-gcm",t,Buffer.from(e.iv,"base64"));r&&n.setAAD(Buffer.from(r,"utf8")),n.setAuthTag(Buffer.from(e.tag,"base64"));const i=Buffer.concat([n.update(Buffer.from(e.data,"base64")),n.final()]).toString("utf8");return JSON.parse(i)}}const B=new g;export{p as ELICITATION_TTL_MS,g as SecretStore,B as secretStore};
1
+ import{createCipheriv as h,createDecipheriv as m,createHash as d,hkdfSync as o,randomBytes as l,randomUUID as p}from"node:crypto";import{JWT_SECRET_KEY as f}from"../../../constants/common.js";import{assertHeaderSafe as y}from"./credential-validation.js";import{secretTtlSeconds as S}from"./subject.js";const g=900*1e3,I="mcp-upstream-secrets",T="mcp-elicitation",w="mcp-elicitation";class A{async setSecret(t,e,r,s,i){y(i.header,i.value);const n={...i,savedAt:Date.now()},a={api:r,scheme:s,...this.#o(this.#c(e),n,this.#n(r,s))};await t.set(this.#t(e,r,s),a,{ttlInSeconds:S(e)})}async getSecretsForSubject(t,e){const r=this.#c(e),{items:s}=await t.list({prefix:this.#i(e)}),i={};for(const n of s){if(!n.value?.scheme)continue;const{api:a,scheme:c}=n.value;try{const u=this.#s(r,n.value,this.#n(a,c));i[a]={...i[a],[c]:u}}catch{continue}}return i}async hasSecret(t,e,r,s){return!!await t.get(this.#t(e,r,s))}async deleteSecret(t,e,r,s){await t.delete(this.#t(e,r,s))}async deleteSubject(t,e){const{items:r}=await t.list({prefix:this.#i(e)}),s=r.flatMap(i=>i.value?[i.key]:[]);s.length!==0&&await t.transaction(async i=>{for(const n of s)await i.delete(n)})}async createElicitation(t,e){const r=p();return await t.set(this.#e(r),this.#o(this.#r(),e),{ttlInSeconds:g/1e3}),r}async peekElicitation(t,e){const r=await t.get(this.#e(e));if(r)try{return this.#s(this.#r(),r)}catch{return}}async consumeElicitation(t,e){const r=this.#e(e),s=await t.transaction(async i=>{const n=await i.get(r);return n&&await i.delete(r),n});if(s)try{return this.#s(this.#r(),s)}catch{return}}#i(t){return["mcp","secret",this.#a(t)]}#t(t,e,r){return["mcp","secret",this.#a(t),e,r]}#n(t,e){return`${t}\0${e}`}#e(t){return["mcp","elicitation",t]}#a(t){return d("sha256").update(t).digest("hex")}#c(t){return Buffer.from(o("sha256",f,t,I,32))}#r(){return Buffer.from(o("sha256",f,w,T,32))}#o(t,e,r){const s=l(12),i=h("aes-256-gcm",t,s);r&&i.setAAD(Buffer.from(r,"utf8"));const n=Buffer.concat([i.update(JSON.stringify(e),"utf8"),i.final()]);return{iv:s.toString("base64"),tag:i.getAuthTag().toString("base64"),data:n.toString("base64")}}#s(t,e,r){const s=m("aes-256-gcm",t,Buffer.from(e.iv,"base64"));r&&s.setAAD(Buffer.from(r,"utf8")),s.setAuthTag(Buffer.from(e.tag,"base64"));const i=Buffer.concat([s.update(Buffer.from(e.data,"base64")),s.final()]).toString("utf8");return JSON.parse(i)}}const N=new A;export{g as ELICITATION_TTL_MS,A as SecretStore,N as secretStore};
@@ -7,12 +7,35 @@ export type UpstreamAuthScheme = {
7
7
  } | {
8
8
  kind: 'apiKey';
9
9
  header: string;
10
+ } | {
11
+ kind: 'cookie';
12
+ name: string;
10
13
  } | {
11
14
  kind: 'oauth2ClientCredentials';
12
15
  tokenUrl: string;
13
16
  scopes: string[];
14
17
  };
18
+ export type UpstreamAuthRoute = {
19
+ pattern: RegExp;
20
+ method: string;
21
+ schemes: string[];
22
+ };
23
+ export type UpstreamApiAuth = {
24
+ schemes: Record<string, UpstreamAuthScheme>;
25
+ defaultScheme: string;
26
+ routes: UpstreamAuthRoute[];
27
+ descriptions?: Record<string, string>;
28
+ };
29
+ export type SchemeChoice = {
30
+ name: string;
31
+ label: string;
32
+ description?: string;
33
+ };
15
34
  type SecuritySchemeLoader = typeof getApiDescriptionFromFs;
16
- export declare function resolveUpstreamAuthScheme(context: McpToolContext, apiRelativePath: string, loadDescription?: SecuritySchemeLoader): Promise<UpstreamAuthScheme>;
35
+ export declare const DEFAULT_SCHEME_NAME = "default";
36
+ export declare function resolveUpstreamApiAuth(context: McpToolContext, apiRelativePath: string, loadDescription?: SecuritySchemeLoader): Promise<UpstreamApiAuth>;
37
+ export declare function schemeChoicesOf(auth: UpstreamApiAuth, names: readonly string[]): SchemeChoice[];
38
+ export declare function credentialHeadersOf(schemes: Record<string, UpstreamAuthScheme>): string[];
39
+ export declare function orderedSchemesOf(schemes: Record<string, UpstreamAuthScheme>): string[];
17
40
  export {};
18
41
  //# sourceMappingURL=upstream-auth-scheme.d.ts.map
@@ -1 +1,2 @@
1
- import{getApiDescriptionFromFs as o}from"../docs-mcp/tools/openapi/utils.js";const c={kind:"raw"};async function u(i,r,n=o){const s=Object.values(i.apiDescriptionsMap??{}).find(t=>t.relativePath===r);if(!s)return c;try{const t=await n({relativePath:s.relativePath,outdir:i.outdir||"",user:i.user,rbac:i.config?.access?.rbac||{},requiresLogin:!!i.config?.access?.requiresLogin});return a(t)}catch{return c}}function a(i){const r=Object.values(i?.components?.securitySchemes??{}).filter(l),n=r.find(e=>e.type==="oauth2"&&e.flows?.clientCredentials);if(n?.flows.clientCredentials){const e=n.flows.clientCredentials;return{kind:"oauth2ClientCredentials",tokenUrl:e.tokenUrl,scopes:Object.keys(e.scopes??{})}}if(r.find(e=>e.type==="http"&&e.scheme==="bearer"||e.type==="oauth2"))return{kind:"bearer"};const t=r.find(e=>e.type==="apiKey"&&e.in==="header");return t?{kind:"apiKey",header:t.name||"X-Api-Key"}:c}function l(i){return typeof i=="object"&&i!==null&&"type"in i}export{u as resolveUpstreamAuthScheme};
1
+ import{getApiDescriptionFromFs as O}from"../docs-mcp/tools/openapi/utils.js";import{OPERATION_METHODS as A}from"../docs-mcp/tools/openapi/constants.js";const S=120,l="default",g={kind:"raw"},h=["oauth2ClientCredentials","bearer","apiKey","cookie","raw"],C=new Set(A),E=/\{[^}]*\}/g;function c(){return{schemes:{[l]:g},defaultScheme:l,routes:[]}}async function L(e,t,n=O){const r=Object.values(e.apiDescriptionsMap??{}).find(i=>i.relativePath===t);if(!r)return c();try{const i=await n({relativePath:r.relativePath,outdir:e.outdir||"",user:e.user,rbac:e.config?.access?.rbac||{},requiresLogin:!!e.config?.access?.requiresLogin});return i?P(i,r.servers??[]):c()}catch{return c()}}function P(e,t){const n=T(e),r=Object.keys(n);if(r.length===0)return c();const i=m(e.security,n)[0]??a(r,n)[0],o=x(e,r);return{schemes:n,defaultScheme:i,routes:H(e,n,t),...Object.keys(o).length>0?{descriptions:o}:{}}}function N(e,t){return t.flatMap(n=>{const r=e.schemes[n];if(!r)return[];const i=e.descriptions?.[n];return[{name:n,label:w(r),...i?{description:i}:{}}]})}function U(e){return[...new Set(Object.values(e).map(j))]}function q(e){return a(Object.keys(e),e)}function j(e){return e.kind==="apiKey"?e.header:e.kind==="cookie"?"Cookie":"Authorization"}function w(e){switch(e.kind){case"bearer":return"API key or bearer token";case"cookie":return`browser session cookie (${e.name})`;case"apiKey":return`API key in the ${e.header} header`;case"oauth2ClientCredentials":return"OAuth2 client credentials";default:return"Authorization header value"}}function x(e,t){const n={};for(const r of t){const i=e.components?.securitySchemes?.[r],o=k(i)?i.description:void 0;if(typeof o!="string")continue;const s=o.split(`
2
+ `)[0].trim();s&&(n[r]=s.slice(0,S))}return n}function T(e){const t={};for(const[n,r]of Object.entries(e.components?.securitySchemes??{})){if(!k(r))continue;const i=v(r);i&&(t[n]=i)}return t}function v(e){if(e.type==="oauth2"){const t=e.flows?.clientCredentials;return t?{kind:"oauth2ClientCredentials",tokenUrl:t.tokenUrl,scopes:Object.keys(t.scopes??{})}:{kind:"bearer"}}if(e.type==="http"&&e.scheme==="bearer")return{kind:"bearer"};if(e.type==="apiKey"&&e.in==="header")return{kind:"apiKey",header:e.name||"X-Api-Key"};if(e.type==="apiKey"&&e.in==="cookie"&&e.name)return{kind:"cookie",name:e.name}}function a(e,t){return[...e].sort((n,r)=>h.indexOf(t[n].kind)-h.indexOf(t[r].kind)||e.indexOf(n)-e.indexOf(r))}function m(e,t){const n=[];for(const r of e??[])for(const i of Object.keys(r))t[i]&&!n.includes(i)&&n.push(i);return n}function H(e,t,n){const r=R(n),i=[];for(const[o,s]of Object.entries(e.paths??{})){if(!s||typeof s!="object")continue;const f=I(r,o);if(f)for(const[p,b]of Object.entries(s)){if(!C.has(p.toLowerCase()))continue;const u=b?.security??e.security;if(u===void 0)continue;const d=m(u,t);d.length===0&&u.length>0||i.push({pattern:f,method:p.toUpperCase(),schemes:a(d,t)})}}return i}function I(e,t){if(t.startsWith("/"))return new RegExp(`^${e}${y(t)}/?$`)}function y(e){return e.split(E).map($).join("[^/]+").replace(/\/+$/,"")}function R(e){const t=[...new Set(e.map(n=>_(n.url)).filter(Boolean).map(y))];return t.length>0?`(?:${t.join("|")})?`:""}function _(e){if(!e)return"";const t=e.replace(/^[a-z][a-z0-9+.-]*:\/\//i,""),n=t.indexOf("/");return n===-1?"":t.slice(n).split(/[?#]/)[0].replace(/\/+$/,"")}function $(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function k(e){return typeof e=="object"&&e!==null&&"type"in e}export{l as DEFAULT_SCHEME_NAME,U as credentialHeadersOf,q as orderedSchemesOf,L as resolveUpstreamApiAuth,N as schemeChoicesOf};
@@ -4,7 +4,13 @@ export type UpstreamAuthRequiredEvent = {
4
4
  api: string;
5
5
  name: string;
6
6
  status: number;
7
+ scheme?: string;
8
+ schemes?: string[];
7
9
  };
10
+ export declare function upstreamAuthKey(event: {
11
+ api: string;
12
+ scheme?: string;
13
+ }): string;
8
14
  export declare function withAuthRequiredMeta(result: CallToolResult, events: UpstreamAuthRequiredEvent[]): CallToolResult;
9
15
  export declare function readAuthRequiredMeta(result: CallToolResult): UpstreamAuthRequiredEvent[];
10
16
  export declare function stripAuthRequiredMeta(result: CallToolResult): CallToolResult;
@@ -1 +1 @@
1
- const i="com.redocly/upstream-auth-required";function u(t,n){const e=new Map;for(const a of n){const o=e.get(a.api);(!o||o.status!==401&&a.status===401)&&e.set(a.api,a)}const r=[...e.values()];return r.length===0?t:{...t,_meta:{...t._meta,[i]:r}}}function p(t){const n=t._meta?.[i];return Array.isArray(n)?n.filter(e=>typeof e?.api=="string"&&typeof e?.name=="string"&&typeof e?.status=="number"):[]}function s(t){if(!t._meta||!(i in t._meta))return t;const{[i]:n,...e}=t._meta,r={...t};return Object.keys(e).length>0?r._meta=e:delete r._meta,r}export{i as UPSTREAM_AUTH_REQUIRED_META,p as readAuthRequiredMeta,s as stripAuthRequiredMeta,u as withAuthRequiredMeta};
1
+ const i="com.redocly/upstream-auth-required";function u(e){return`${e.api}\0${e.scheme??""}`}function c(e,n){const t=new Map;for(const a of n){const s=u(a),o=t.get(s);(!o||o.status!==401&&a.status===401)&&t.set(s,a)}const r=[...t.values()];return r.length===0?e:{...e,_meta:{...e._meta,[i]:r}}}function p(e){const n=e._meta?.[i];return Array.isArray(n)?n.filter(t=>typeof t?.api=="string"&&typeof t?.name=="string"&&typeof t?.status=="number").map(t=>{const r=Array.isArray(t.schemes)?t.schemes.filter(o=>typeof o=="string"):[],{schemes:a,...s}=t;return r.length>0?{...s,schemes:r}:s}):[]}function m(e){if(!e._meta||!(i in e._meta))return e;const{[i]:n,...t}=e._meta,r={...e};return Object.keys(t).length>0?r._meta=t:delete r._meta,r}export{i as UPSTREAM_AUTH_REQUIRED_META,p as readAuthRequiredMeta,m as stripAuthRequiredMeta,u as upstreamAuthKey,c as withAuthRequiredMeta};
@@ -1 +1 @@
1
- import{logger as A}from"../../../tools/notifiers/logger.js";import{getFeedbackClientIp as v}from"../../../web-server/utils/feedback-ip.js";import{getForwardedOrigin as f}from"../../../web-server/utils/get-request-origin.js";import{GATEWAY_FETCH_LIMIT_DEFAULTS as N}from"../../../../constants/common.js";import{isObject as _}from"../../../../utils/guards/is-object.js";import{getAccessibleSkills as k}from"../../../utils/skills/get-accessible-skills.js";import{getSkillUrl as B}from"../../../utils/skills/get-skill-url.js";import{createDocsMcpServer as P}from"../servers/docs-server.js";import{filterApiDescriptionsByRbac as H,filterGraphqlDescriptionsByRbac as L}from"../utils.js";import{createMethodNotAllowedError as j,withErrorHandling as V}from"./errors.js";import{constructForbiddenResponse as G,constructInvalidTokenResponse as J,constructUnauthorizedResponse as $,handleMcpAuth as z,shouldHandleMcpAuth as K}from"../auth/auth-handlers.js";import{extractTokenFromAuthHeader as Y}from"../utils/jwt.js";import{DEFAULT_DOCS_MCP_SERVER_NAME as W}from"../constants.js";import{canAccessFeature as X}from"../../../utils/rbac.js";import{DEFAULT_ANONYMOUS_VISITOR_TEAM as Q,RbacFeatures as Z}from"../../../../constants/common.js";const m="X-Redocly-AI-Metadata";function q(r){if(r)try{const e=JSON.parse(r);if(_(e))return e;A.warn(`Ignoring ${m} header: not a JSON object.`)}catch{A.warn(`Ignoring ${m} header: invalid JSON.`)}}const x=async(r,e,o)=>{const t=!!e?.config?.access?.requiresLogin,i=e?.config?.access?.rbac||{},g=o?.props?.config?.mcpMode??"tools",M=o?.props?.config?.gatewayFetchBudgetPerExec??N.budgetPerExec,E=o?.props?.config?.searchIgnoredRoutes??[];let d;const h=r.headers.get("Authorization");if(K(t,i)){const{isAuthenticated:l,isTokenValid:s,currentUser:a,accessToken:u}=await z(r,e);if(!l){const p=f(r);return s===!1?J(p):$(p)}a&&(e.user=a),d=u}else h&&(d=Y(h||"")??void 0);const T={isAuthenticated:!!e.user?.isAuthenticated,teams:e.user?.teams||[Q],claims:e.user?.claims??{}};if(!X(Z.MCP,T,i,t))return G();let c;return await V(async()=>{const l=o?.props?.config?.elicitationEnabled??!1;if(r.method==="GET")return new Response(JSON.stringify({error:"Method Not Allowed",message:`In order to use this MCP server, you need to register it in your MCP Client (VS Code, Cursor, Claude Code, etc.) using this URL: ${r.url}`}),{status:405,headers:{"Content-Type":"application/json"}});if(r.method!=="POST")return j();const s=o,a=s?.props?.config?.apiDescriptionsMap||{},u=s?.props?.config?.graphqlDescriptions||[],p=s?.props?.config?.mcpDocsServerName||W,{config:{mcp:b={}}}=e,D=H(a,e.user,i,t),R=L(u,e.user,i,t),S=e.config.products?Object.values(e.config.products).map(n=>n?.name):[],y=b.docs?.name||p,w=q(r.headers.get(m)),C=s?.props?.tools||[],I=s?.props?.skillsBaseUrl||f(r),O=k(s?.props?.skills||[],e.user,i,t).map(n=>({slug:n.slug,name:n.name,description:n.description,content:n.content,uri:B(I,n.slug)})),U=await r.json(),F={name:y,tools:C,skills:O,context:{...e,accessToken:d,outdir:e.outdir||"",baseUrl:e.baseUrl||f(r),apiDescriptionsMap:D,graphqlDescriptions:R,products:S,metadata:w,mcpMode:g,elicitationEnabled:l,gatewayFetchBudgetPerExec:M,searchIgnoredRoutes:E,clientIp:v(r)}};return c=await P({...F,getKv:e.getKv}),await ee(r,c,U)},async()=>{c&&(await c.cleanup(),c=void 0)},g)};async function ee(r,e,o){return e.transport.handleRequest(r,o!==void 0?{parsedBody:o}:void 0)}var Ae=x;export{Ae as default};
1
+ import{logger as A}from"../../../tools/notifiers/logger.js";import{getFeedbackClientIp as v}from"../../../web-server/utils/feedback-ip.js";import{getForwardedOrigin as f}from"../../../web-server/utils/get-request-origin.js";import{GATEWAY_FETCH_LIMIT_DEFAULTS as N}from"../../../../constants/common.js";import{isObject as _}from"../../../../utils/guards/is-object.js";import{getAccessibleSkills as k}from"../../../utils/skills/get-accessible-skills.js";import{getSkillUrl as B}from"../../../utils/skills/get-skill-url.js";import{createDocsMcpServer as P}from"../servers/docs-server.js";import{filterApiDescriptionsByRbac as H,filterGraphqlDescriptionsByRbac as L}from"../utils.js";import{createMethodNotAllowedError as j,withErrorHandling as V}from"./errors.js";import{constructForbiddenResponse as G,constructInvalidTokenResponse as J,constructUnauthorizedResponse as $,handleMcpAuth as z,shouldHandleMcpAuth as K}from"../auth/auth-handlers.js";import{extractTokenFromAuthHeader as Y}from"../utils/jwt.js";import{DEFAULT_DOCS_MCP_SERVER_NAME as W}from"../constants.js";import{canAccessFeature as X}from"../../../utils/rbac.js";import{DEFAULT_ANONYMOUS_VISITOR_TEAM as Q,RbacFeatures as Z}from"../../../../constants/common.js";const m="X-Redocly-AI-Metadata";function q(r){if(r)try{const e=JSON.parse(r);if(_(e))return e;A.warn(`Ignoring ${m} header: not a JSON object.`)}catch{A.warn(`Ignoring ${m} header: invalid JSON.`)}}const x=async(r,e,o)=>{const t=!!e?.config?.access?.requiresLogin,i=e?.config?.access?.rbac||{},g=o?.props?.config?.mcpMode??"tools",M=o?.props?.config?.gatewayFetchBudgetPerExec??N.budgetPerExec,E=o?.props?.config?.searchIgnoredRoutes??[];let d;const h=r.headers.get("Authorization");if(K(t,i)){const{isAuthenticated:l,isTokenValid:s,currentUser:a,accessToken:u}=await z(r,e);if(!l){const p=f(r);return s===!1?J(p):$(p)}a&&(e.user=a),d=u}else h&&(d=Y(h||"")??void 0);const T={isAuthenticated:!!e.user?.isAuthenticated,teams:e.user?.teams||[Q],claims:e.user?.claims??{}};if(!X(Z.MCP,T,i,t))return G();let c;return await V(async()=>{const l=o?.props?.config?.elicitationEnabled??!1;if(r.method==="GET")return new Response(JSON.stringify({error:"Method Not Allowed",message:`In order to use this MCP server, you need to register it in your MCP client (VS Code, Cursor, Claude Code, etc.) using this URL: ${r.url}`}),{status:405,headers:{"Content-Type":"application/json"}});if(r.method!=="POST")return j();const s=o,a=s?.props?.config?.apiDescriptionsMap||{},u=s?.props?.config?.graphqlDescriptions||[],p=s?.props?.config?.mcpDocsServerName||W,{config:{mcp:b={}}}=e,D=H(a,e.user,i,t),R=L(u,e.user,i,t),S=e.config.products?Object.values(e.config.products).map(n=>n?.name):[],y=b.docs?.name||p,w=q(r.headers.get(m)),I=s?.props?.tools||[],C=s?.props?.skillsBaseUrl||f(r),O=k(s?.props?.skills||[],e.user,i,t).map(n=>({slug:n.slug,name:n.name,description:n.description,content:n.content,uri:B(C,n.slug)})),U=await r.json(),F={name:y,tools:I,skills:O,context:{...e,accessToken:d,outdir:e.outdir||"",baseUrl:e.baseUrl||f(r),apiDescriptionsMap:D,graphqlDescriptions:R,products:S,metadata:w,mcpMode:g,elicitationEnabled:l,gatewayFetchBudgetPerExec:M,searchIgnoredRoutes:E,clientIp:v(r)}};return c=await P({...F,getKv:e.getKv}),await ee(r,c,U)},async()=>{c&&(await c.cleanup(),c=void 0)},g)};async function ee(r,e,o){return e.transport.handleRequest(r,o!==void 0?{parsedBody:o}:void 0)}var Ae=x;export{Ae as default};