@redocly/reef 0.132.0-next.6 → 0.132.0-next.8

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 (104) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/dist/cli/telemetry/index.js +1 -1
  3. package/dist/client/App.js +1 -1
  4. package/dist/client/app/hooks/utils/match-banner-target.d.ts +23 -1
  5. package/dist/client/app/hooks/utils/match-banner-target.js +1 -1
  6. package/dist/client/mcp-tool-handlers-entry.d.ts +3 -0
  7. package/dist/client/mcp-tool-handlers-entry.js +1 -0
  8. package/dist/client/templates/asyncapi-docs/helpers.d.ts +1 -1
  9. package/dist/client/types/ai-search.d.ts +5 -3
  10. package/dist/constants/l10n/langs/ar.js +1 -1
  11. package/dist/constants/l10n/langs/de.js +1 -1
  12. package/dist/constants/l10n/langs/en.js +1 -1
  13. package/dist/constants/l10n/langs/es.js +1 -1
  14. package/dist/constants/l10n/langs/fr.js +1 -1
  15. package/dist/constants/l10n/langs/hi.js +1 -1
  16. package/dist/constants/l10n/langs/it.js +1 -1
  17. package/dist/constants/l10n/langs/ja.js +1 -1
  18. package/dist/constants/l10n/langs/ko.js +1 -1
  19. package/dist/constants/l10n/langs/pl.js +1 -1
  20. package/dist/constants/l10n/langs/pt-BR.js +1 -1
  21. package/dist/constants/l10n/langs/pt.js +1 -1
  22. package/dist/constants/l10n/langs/ru.js +1 -1
  23. package/dist/constants/l10n/langs/uk.js +1 -1
  24. package/dist/constants/l10n/langs/zh.js +1 -1
  25. package/dist/markdoc/nodes/fence/index.js +1 -1
  26. package/dist/markdoc/nodes/index.d.ts +1 -1
  27. package/dist/markdoc/nodes/index.js +1 -1
  28. package/dist/server/api-routes/run-api-routes-worker.js +1 -1
  29. package/dist/server/config/env-config.js +1 -1
  30. package/dist/server/config/env-schema.d.ts +3 -3
  31. package/dist/server/config/env-schemas/api-urls.d.ts +3 -3
  32. package/dist/server/config/env-schemas/api-urls.js +1 -1
  33. package/dist/server/esbuild/esbuild.js +3 -3
  34. package/dist/server/esbuild/plugins/codegen/index.d.ts +1 -0
  35. package/dist/server/esbuild/plugins/codegen/index.js +7 -3
  36. package/dist/server/esbuild/plugins/mcp-tool-handlers-resolver.d.ts +7 -0
  37. package/dist/server/esbuild/plugins/mcp-tool-handlers-resolver.js +1 -0
  38. package/dist/server/plugins/config-parser/loaders/content-slugs-loader.js +1 -1
  39. package/dist/server/plugins/config-parser/normalize-redirect-sources.js +1 -1
  40. package/dist/server/plugins/default-theme/resolve-products-config.js +1 -1
  41. package/dist/server/plugins/markdown/attribute-resolvers/index.js +1 -1
  42. package/dist/server/plugins/markdown/attribute-resolvers/resolve-diagram-from-file.d.ts +4 -0
  43. package/dist/server/plugins/markdown/attribute-resolvers/resolve-diagram-from-file.js +1 -0
  44. package/dist/server/plugins/markdown/attribute-resolvers/resolve-link.js +1 -1
  45. package/dist/server/plugins/markdown/attribute-resolvers/resolve-native-md-link.js +1 -1
  46. package/dist/server/plugins/markdown/markdoc/markdoc-options.d.ts +1 -1
  47. package/dist/server/plugins/markdown/markdoc/plugins/render-diagrams.d.ts +16 -0
  48. package/dist/server/plugins/markdown/markdoc/plugins/render-diagrams.js +1 -0
  49. package/dist/server/plugins/markdown/runtime-transform.js +1 -1
  50. package/dist/server/plugins/mcp/docs-mcp/tool-schemas.d.ts +7 -0
  51. package/dist/server/plugins/mcp/docs-mcp/tool-schemas.js +1 -0
  52. package/dist/server/plugins/mcp/docs-mcp/tools/get-endpoint-info.d.ts +5 -9
  53. package/dist/server/plugins/mcp/docs-mcp/tools/get-endpoint-info.js +1 -1
  54. package/dist/server/plugins/mcp/docs-mcp/tools/get-endpoints.d.ts +5 -9
  55. package/dist/server/plugins/mcp/docs-mcp/tools/get-endpoints.js +1 -1
  56. package/dist/server/plugins/mcp/docs-mcp/tools/get-full-api-description.d.ts +5 -9
  57. package/dist/server/plugins/mcp/docs-mcp/tools/get-full-api-description.js +1 -1
  58. package/dist/server/plugins/mcp/docs-mcp/tools/get-security-schemes.d.ts +5 -9
  59. package/dist/server/plugins/mcp/docs-mcp/tools/get-security-schemes.js +1 -1
  60. package/dist/server/plugins/mcp/docs-mcp/tools/helpers/load-api-description.d.ts +4 -0
  61. package/dist/server/plugins/mcp/docs-mcp/tools/helpers/load-api-description.js +1 -0
  62. package/dist/server/plugins/mcp/docs-mcp/tools/index.d.ts +10 -7
  63. package/dist/server/plugins/mcp/docs-mcp/tools/index.js +1 -1
  64. package/dist/server/plugins/mcp/docs-mcp/tools/list-apis.d.ts +5 -9
  65. package/dist/server/plugins/mcp/docs-mcp/tools/list-apis.js +1 -1
  66. package/dist/server/plugins/mcp/docs-mcp/tools/search.d.ts +5 -10
  67. package/dist/server/plugins/mcp/docs-mcp/tools/search.js +3 -3
  68. package/dist/server/plugins/mcp/docs-mcp/tools/utils.d.ts +6 -3
  69. package/dist/server/plugins/mcp/docs-mcp/tools/utils.js +6 -6
  70. package/dist/server/plugins/mcp/docs-mcp/tools/whoami.d.ts +5 -9
  71. package/dist/server/plugins/mcp/docs-mcp/tools/whoami.js +1 -1
  72. package/dist/server/plugins/mcp/handlers/docs-mcp-handler.js +1 -1
  73. package/dist/server/plugins/mcp/handlers/handle-mcp-request.js +1 -1
  74. package/dist/server/plugins/mcp/index.js +1 -1
  75. package/dist/server/plugins/mcp/servers/docs-server.d.ts +13 -22
  76. package/dist/server/plugins/mcp/servers/docs-server.js +1 -1
  77. package/dist/server/plugins/mcp/types.d.ts +24 -56
  78. package/dist/server/plugins/mcp/workers/execute-mcp-tool.d.ts +2 -2
  79. package/dist/server/plugins/mcp/workers/execute-mcp-tool.js +1 -1
  80. package/dist/server/store.d.ts +5 -2
  81. package/dist/server/store.js +1 -1
  82. package/dist/server/telemetry/index.js +1 -1
  83. package/dist/server/types/plugins/common.d.ts +10 -0
  84. package/dist/server/types/plugins/markdown.d.ts +1 -1
  85. package/dist/server/utils/rbac.js +1 -1
  86. package/dist/server/utils/redirects/validate-redirects.js +1 -1
  87. package/dist/server/utils/resolve-asset-path.js +1 -1
  88. package/dist/server/web-server/auth.js +3 -3
  89. package/dist/server/web-server/routes/auth.js +1 -1
  90. package/dist/server/web-server/routes/cors-proxy.d.ts +1 -0
  91. package/dist/server/web-server/routes/cors-proxy.js +2 -2
  92. package/dist/server/web-server/routes/otel/otel.js +1 -1
  93. package/dist/server/web-server/utils.js +1 -1
  94. package/dist/server/workers/types.d.ts +2 -2
  95. package/dist/server/workers/worker-pool.js +1 -1
  96. package/package.json +8 -8
  97. package/dist/server/plugins/markdown/markdoc/plugins/render-mermaid.d.ts +0 -4
  98. package/dist/server/plugins/markdown/markdoc/plugins/render-mermaid.js +0 -1
  99. package/dist/server/plugins/mcp/docs-mcp/tools/docs-mcp-tool.d.ts +0 -55
  100. package/dist/server/plugins/mcp/docs-mcp/tools/docs-mcp-tool.js +0 -1
  101. package/dist/server/plugins/mcp/handlers/mcp-request-handler.d.ts +0 -11
  102. package/dist/server/plugins/mcp/handlers/mcp-request-handler.js +0 -1
  103. package/dist/server/plugins/mcp/servers/base-server.d.ts +0 -17
  104. package/dist/server/plugins/mcp/servers/base-server.js +0 -1
@@ -8,7 +8,7 @@ export type RoutesInfoActions = {
8
8
  followRedirect?: boolean;
9
9
  }) => PageRouteDetails | undefined;
10
10
  getAllRoutesForLocale: (locale?: string) => PageRouteDetails[];
11
- slugHasRouteOrRedirect: (slug: string) => boolean;
11
+ hasRouteOrRedirectBySlug: (slug: string) => boolean;
12
12
  buildRevision: number;
13
13
  };
14
14
  export type MarkdocResolveContext = {
@@ -1 +1 @@
1
- import R from"path";import x from"picomatch";import"../node-crypto-polyfill.js";import{REDOCLY_TEAMS_RBAC as _,REDOCLY_ROUTE_RBAC as A}from"@redocly/config";import{DEFAULT_ANONYMOUS_VISITOR_TEAM as O,ServerRoutes as w,PUBLIC_RBAC_SCOPE_ITEM as y,RBAC_ALL_OTHER_TEAMS as u,DEFAULT_RBAC_SCOPE as S}from"../../constants/common.js";import{DEPRECATED_PUBLIC_API_DEFINITIONS_FOLDER as I,PUBLIC_API_DEFINITIONS_FOLDER as C,PUBLIC_ASSETS_FOLDER as N}from"../constants/common.js";import{removeTrailingSlash as B}from"../../utils/url/remove-trailing-slash.js";import{removeLeadingSlash as k}from"../../utils/url/remove-leading-slash.js";import{parsePathVersions as M}from"../../utils/path/parse-path-versions.js";import{reporter as W}from"../tools/notifiers/reporter.js";import{bold as U}from"../tools/notifiers/helpers/colors.js";import{shaDirPathShort as $}from"../utils/crypto/sha-dir-path-short.js";import{isTruthy as b}from"../../utils/guards/is-truthy.js";import{canExpandConfig as v,expandRbacConfig as Y,getTeamFolderDefaults as z,parseTeamFoldersTemplate as H,parseTeamNameTemplate as K}from"./rbac-expand.js";import{getUserParamsFromCookies as G}from"../web-server/auth.js";import{getDeeperGlobPattern as V}from"./globs.js";import{EntitlementsProvider as J}from"../entitlements/entitlements-provider.js";const j=["NONE","READ","TRIAGE","WRITE","MAINTAIN","ADMIN"],Q=new Set(["x-parsed-md-description","x-parsed-md-summary"]);function yt(t,e){const n=j.indexOf(t.toUpperCase()),r=j.indexOf(e.toUpperCase());return n>r?t:e}const E={};function P(t,e){if(!t?.content)return y;const n=t.content,{slug:r,fsPath:s}=e;if(!r&&!s)return y;const o=f=>{const h=`slug:${f}`,m=E[h]??x(f);E[h]=m;const g=`fsPath:${f}`,L=E[g]??x(k(f));return E[g]=L,!!(r&&m(r))||!!(s&&L(s))};if(X(r||s||"")&&Object.keys(n).filter(m=>o(m)).length===0)return n[S]||y;const c=Object.keys(n).filter(f=>o(f));if(c.length==0)return y;const l=c.map(f=>x.scan(f,{tokens:!0,parts:!0}));let p=l[0];for(let f=1;f<l.length;f++)p=V(p,l[f]);return n[p.input]}function Et(t,e,n={},r=!1){if(r&&Object.keys(n).length===0)return e.isAuthenticated;const s=n.features?.[t];return s?e.teams.some(o=>s[o]&&s[o].toLowerCase()!=="none"):!0}function Pt(t,e){return T(t,{isAuthenticated:!1,teams:[O]},e.access?.rbac||{},e.access?.requiresLogin||!1)}function T(t,e={},n={},r=!1){if(t.slug&&typeof t.slug=="string"&&Object.values(w).some(c=>{const l=c.split(":")[0].replace(/\/$/,"");return t.slug===l||t.slug?.startsWith(c)})||typeof t.slug=="string"&&t.slug?.endsWith("/mcp")&&J.instance().canAccessFeature("mcp"))return!0;if(r&&Object.keys(n).length===0)return!!e.isAuthenticated;const s=Y(n,e.teams||[]),o=t[_]||P(s,t[A]||{});if(Object.keys(o||{}).length===0)return!1;if(Object.keys(o).length===1&&o[u]&&o[u].toLowerCase()!=="none")return!0;const a=(e?.email?[...e?.teams||[],e?.email]:e?.teams)||[],i=[];for(const c of a??[])o[c]?i.push(o[c]):o[u]&&c!==e?.email&&i.push(o[u]);return i.length?i.some(c=>c.toLowerCase()!=="none"):!1}function Tt(t,e,n,r){if(!t.startsWith(C)&&!t.startsWith(I))return!0;const s=t.replace(new RegExp(`^${C}/`),"").replace(new RegExp(`^${I}/`),""),a=s==="."?"":s,i={[A]:{slug:t,fsPath:a},slug:t};return T(i,r,e,n)}function xt(t,e,n,r,s){if(!t.startsWith(N))return!0;const o=t.match(/.*\..{64}\.([A-Fa-f0-9]{8})\.[^\.]+$/)?.[1];if(!o)return!0;const a=r[o];if(!a)return!0;const{base:i,ext:c}=R.parse(t),l=i.split(".")[0],p=c.split(".").join(""),h=a==="."?"":a,m={[A]:{slug:t,fsPath:R.posix.join(h,`${l}.${p}`)},slug:t};return T(m,s,e,n)}async function Ot(t,e){const{isAuthenticated:n=!1,idpAccessToken:r,federatedAccessToken:s,federatedIdToken:o,...a}=await G(t,e),{teams:i=[]}=a;let c;return n?c=i.filter(l=>l!==O):c=[O],{isAuthenticated:n,idpAccessToken:r,teams:c,claims:a}}function F(t,e,n={},r=!1){if(!t)return t;if(Array.isArray(t)){const s=[];for(const o of t){const a=F(o,e,n,r);a!==void 0&&s.push(a)}return s}if(typeof t=="object"){if(!T(t,e,n,r))return;let s=!1;const o={};for(const a in t){if(a===_||a===A)continue;if(Q.has(a)){o[a]=t[a];continue}const i=F(t[a],e,n,r);if(a==="items"&&Array.isArray(i)&&i.length===0&&t[a].length!==0){s=!0;continue}i!==void 0&&(o[a]=i)}return s?void 0:o}return t}function Dt(t){return typeof t=="string"?t.split(" ").filter(Boolean):Array.isArray(t)?t.map(e=>e.toString()):[]}function gt(t,e){if(!e)return;const n=e.content;if(!n)return e;const r=Object.entries(n).flatMap(([o,a])=>o===S?[[o,a]]:[[o,a],...t.localeFolders.map(i=>[o.startsWith("/")?`/${i.toLocaleLowerCase()}${o}`:R.posix.join(t.localizationFolder,i,o),a])]),s=Object.fromEntries(r);return{...e,content:s}}async function Lt(t,e){if(!e)return{};const n={},r=new Set((await t.scan()).flatMap(({relativePath:s})=>{const{versionFolderPath:o}=M(s)||{},a=R.dirname(s);return o?[o,a]:a}));for(const s of r)n[$(s)]=s;return n}const d=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function X(t){return t?t.split("/").filter(Boolean).some(n=>n.startsWith(".")):!1}const Z=t=>{if(t&&d(t)&&("content"in t&&d(t.content)||"reunite"in t&&d(t.reunite)||"features"in t&&d(t.features)||t.teamFolders&&t.teamNamePatterns)){const e=Object.values(t.content||{});if(e.length===0)return!0;if(e.every(d))return e.every(n=>Object.values(n).every(r=>typeof r=="string"))}return!1},_t=async t=>{if(t){if(Object.keys(t).length===0)return{};if(Z(t))return q(t);await W.panicOnContentError(`You are using an incorrect format of ${U("rbac:")} configuration. See: https://redocly.com/docs/realm/access`)}},q=t=>{const e={...t};if(e.content){const n={};for(const r in e.content)if(e.content[r]!==void 0){const s=B(r);n[s]=e.content[r]}e.content=n}return e};function St(t,e){const n=t.fsPath,r=t.slug,s=[];if(v(e)&&(n||r)){const o=[n,r].filter(b),a=H(e,o);if(a){const i=e?.teamNamePatterns?.map(l=>l.replace("{teamPathSegment}",a.teamPathSegment).replace("{projectRole}","read"))??[];s.push(...i);const c=P({content:{...z(e),...e.content}},t);s.push(...D(c))}else{const i=P(e,t);s.push(...D(i))}}else{const o=P(e,t);s.push(...D(o))}return tt(e,s)}function D(t){if(!t)return[];const e=[],n=u in t?{authenticated:t[u],anonymous:t[u]}:{};for(const[r,s]of Object.entries({...n,...t}))s.toLowerCase()!=="none"&&r!==u&&e.push(r);return e}function tt(t,e){return e.map(r=>K(t,r)??{teamName:r}).map(r=>r.projectRole&&r.projectRole!=="READ"?r.teamName?.toLowerCase().replace(r.projectRole?.toLowerCase?.()??"","read")??"":r.teamName?.toLowerCase()??"")}export{j as PROJECT_ROLES_ORDERED_BY_ACCESS_LEVEL,gt as applyL10nToRbacConfig,xt as canAccessAsset,Et as canAccessFeature,T as canAccessResource,Tt as canDownloadApiDefinition,tt as expandTeamsForRead,D as extractTeamsFromScopeItems,F as filterDataByAccessDeep,Ot as getAuthDetailsFromCookies,yt as getHigherRole,St as getRbacTeamsListForResource,P as getScopeItemsForResource,Z as isRbacConfigValid,Pt as isResourcePubliclyAccessible,q as normalizeRbacConfig,_t as parseRbacConfig,Dt as parseTeamClaimToArray,Lt as resolveDirectoryHashes};
1
+ import y from"path";import T from"picomatch";import"../node-crypto-polyfill.js";import{REDOCLY_TEAMS_RBAC as _,REDOCLY_ROUTE_RBAC as R}from"@redocly/config";import{DEFAULT_ANONYMOUS_VISITOR_TEAM as x,ServerRoutes as w,PUBLIC_RBAC_SCOPE_ITEM as A,RBAC_ALL_OTHER_TEAMS as u,DEFAULT_RBAC_SCOPE as S}from"../../constants/common.js";import{DEPRECATED_PUBLIC_API_DEFINITIONS_FOLDER as j,PUBLIC_API_DEFINITIONS_FOLDER as I,PUBLIC_ASSETS_FOLDER as N}from"../constants/common.js";import{removeTrailingSlash as k}from"../../utils/url/remove-trailing-slash.js";import{removeLeadingSlash as B}from"../../utils/url/remove-leading-slash.js";import{parsePathVersions as b}from"../../utils/path/parse-path-versions.js";import{reporter as M}from"../tools/notifiers/reporter.js";import{bold as W}from"../tools/notifiers/helpers/colors.js";import{shaDirPathShort as U}from"../utils/crypto/sha-dir-path-short.js";import{isTruthy as $}from"../../utils/guards/is-truthy.js";import{canExpandConfig as v,expandRbacConfig as Y,getTeamFolderDefaults as z,parseTeamFoldersTemplate as K,parseTeamNameTemplate as H}from"./rbac-expand.js";import{getUserParamsFromCookies as G}from"../web-server/auth.js";import{getDeeperGlobPattern as V}from"./globs.js";import{EntitlementsProvider as J}from"../entitlements/entitlements-provider.js";const C=["NONE","READ","TRIAGE","WRITE","MAINTAIN","ADMIN"],Q=new Set(["x-parsed-md-description","x-parsed-md-summary"]);function Ot(t,e){const r=C.indexOf(t.toUpperCase()),n=C.indexOf(e.toUpperCase());return r>n?t:e}const E={};function O(t,e){if(!t?.content)return A;const r=t.content,{slug:n,fsPath:s}=e;if(!n&&!s)return A;const o=f=>{const d=`slug:${f}`,p=E[d]??T(f);E[d]=p;const D=`fsPath:${f}`,L=E[D]??T(B(f));return E[D]=L,!!(n&&p(n))||!!(s&&L(s))};if(q(n||s||"")&&Object.keys(r).filter(p=>o(p)).length===0)return r[S]||A;const i=Object.keys(r).filter(f=>o(f));if(i.length==0)return A;const l=i.map(f=>T.scan(f,{tokens:!0,parts:!0}));let h=l[0];for(let f=1;f<l.length;f++)h=V(h,l[f]);return r[h.input]}function Pt(t,e,r={},n=!1){if(n&&Object.keys(r).length===0)return e.isAuthenticated;const s=r.features?.[t];return s?e.teams.some(o=>s[o]&&s[o].toLowerCase()!=="none"):!0}function Tt(t,e){return P(t,{isAuthenticated:!1,teams:[x]},e.access?.rbac||{},e.access?.requiresLogin||!1)}function P(t,e={},r={},n=!1){if(t.slug&&typeof t.slug=="string"&&Object.values(w).some(i=>{const l=i.split(":")[0].replace(/\/$/,"");return t.slug===l||t.slug?.startsWith(i)})||typeof t.slug=="string"&&t.slug?.endsWith("/mcp")&&J.instance().canAccessFeature("mcp"))return!0;if(n&&Object.keys(r).length===0)return!!e.isAuthenticated;const s=Y(r,e.teams||[]),o=t[_]||O(s,t[R]||{});if(Object.keys(o||{}).length===0)return!1;if(Object.keys(o).length===1&&o[u]&&o[u].toLowerCase()!=="none")return!0;const c=(e?.email?[...e?.teams||[],e?.email]:e?.teams)||[],a=[];for(const i of c??[])o[i]?a.push(o[i]):o[u]&&i!==e?.email&&a.push(o[u]);return a.length?a.some(i=>i.toLowerCase()!=="none"):!1}function xt(t,e,r,n){if(!t.startsWith(I)&&!t.startsWith(j))return!0;const s=t.replace(new RegExp(`^${I}/`),"").replace(new RegExp(`^${j}/`),""),c=s==="."?"":s,a={[R]:{slug:t,fsPath:c},slug:t};return P(a,n,e,r)}function gt(t,e,r,n,s){if(!t.startsWith(N))return!0;const o=t.match(/.*\..{64}\.([A-Fa-f0-9]{8})\.[^\.]+$/)?.[1];if(!o)return!0;const c=n[o];if(!c)return!0;const{base:a,ext:i}=y.parse(t),l=a.split(".")[0],h=i.split(".").join(""),d=c==="."?"":c,p={[R]:{slug:t,fsPath:y.posix.join(d,`${l}.${h}`)},slug:t};return P(p,s,e,r)}async function Dt(t,e){const{isAuthenticated:r=!1,idpAccessToken:n,federatedAccessToken:s,federatedIdToken:o,...c}=await G(t,e),{teams:a=[]}=c;let i;return r?i=a.filter(l=>l!==x):i=[x],{isAuthenticated:r,idpAccessToken:n,teams:i,claims:c}}function F(t,e,r={},n=!1){if(!t)return t;if(Array.isArray(t)){const s=[];for(const o of t){const c=F(o,e,r,n);c!==void 0&&s.push(c)}return s}if(typeof t=="object"){if(!P(t,e,r,n))return;let s=!1;const o={};for(const c in t){if(c===_||c===R)continue;if(Q.has(c)){o[c]=t[c];continue}const a=F(t[c],e,r,n);if(c==="items"&&Array.isArray(a)&&a.length===0&&t[c].length!==0){s=!0;continue}a!==void 0&&(o[c]=a),c==="paths"&&X(a)&&Z(a)}return s?void 0:o}return t}function Lt(t){return typeof t=="string"?t.split(" ").filter(Boolean):Array.isArray(t)?t.map(e=>e.toString()):[]}function _t(t,e){if(!e)return;const r=e.content;if(!r)return e;const n=Object.entries(r).flatMap(([o,c])=>o===S?[[o,c]]:[[o,c],...t.localeFolders.map(a=>[o.startsWith("/")?`/${a.toLocaleLowerCase()}${o}`:y.posix.join(t.localizationFolder,a,o),c])]),s=Object.fromEntries(n);return{...e,content:s}}async function St(t,e){if(!e)return{};const r={},n=new Set((await t.scan()).flatMap(({relativePath:s})=>{const{versionFolderPath:o}=b(s)||{},c=y.dirname(s);return o?[o,c]:c}));for(const s of n)r[U(s)]=s;return r}const m=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function X(t){return m(t)&&Object.keys(t).length>0}function Z(t){for(const e of Object.keys(t)){const r=t[e];m(r)&&Object.keys(r).length===0&&delete t[e]}}function q(t){return t?t.split("/").filter(Boolean).some(r=>r.startsWith(".")):!1}const tt=t=>{if(t&&m(t)&&("content"in t&&m(t.content)||"reunite"in t&&m(t.reunite)||"features"in t&&m(t.features)||t.teamFolders&&t.teamNamePatterns)){const e=Object.values(t.content||{});if(e.length===0)return!0;if(e.every(m))return e.every(r=>Object.values(r).every(n=>typeof n=="string"))}return!1},jt=async t=>{if(t){if(Object.keys(t).length===0)return{};if(tt(t))return et(t);await M.panicOnContentError(`You are using an incorrect format of ${W("rbac:")} configuration. See: https://redocly.com/docs/realm/access`)}},et=t=>{const e={...t};if(e.content){const r={};for(const n in e.content)if(e.content[n]!==void 0){const s=k(n);r[s]=e.content[n]}e.content=r}return e};function It(t,e){const r=t.fsPath,n=t.slug,s=[];if(v(e)&&(r||n)){const o=[r,n].filter($),c=K(e,o);if(c){const a=e?.teamNamePatterns?.map(l=>l.replace("{teamPathSegment}",c.teamPathSegment).replace("{projectRole}","read"))??[];s.push(...a);const i=O({content:{...z(e),...e.content}},t);s.push(...g(i))}else{const a=O(e,t);s.push(...g(a))}}else{const o=O(e,t);s.push(...g(o))}return rt(e,s)}function g(t){if(!t)return[];const e=[],r=u in t?{authenticated:t[u],anonymous:t[u]}:{};for(const[n,s]of Object.entries({...r,...t}))s.toLowerCase()!=="none"&&n!==u&&e.push(n);return e}function rt(t,e){return e.map(n=>H(t,n)??{teamName:n}).map(n=>n.projectRole&&n.projectRole!=="READ"?n.teamName?.toLowerCase().replace(n.projectRole?.toLowerCase?.()??"","read")??"":n.teamName?.toLowerCase()??"")}export{C as PROJECT_ROLES_ORDERED_BY_ACCESS_LEVEL,_t as applyL10nToRbacConfig,gt as canAccessAsset,Pt as canAccessFeature,P as canAccessResource,xt as canDownloadApiDefinition,rt as expandTeamsForRead,g as extractTeamsFromScopeItems,F as filterDataByAccessDeep,Dt as getAuthDetailsFromCookies,Ot as getHigherRole,It as getRbacTeamsListForResource,O as getScopeItemsForResource,tt as isRbacConfigValid,Tt as isResourcePubliclyAccessible,et as normalizeRbacConfig,jt as parseRbacConfig,Lt as parseTeamClaimToArray,St as resolveDirectoryHashes};
@@ -1 +1 @@
1
- import h from"node:path";import{existsSync as R,lstatSync as w,readdirSync as N}from"node:fs";import{CONFIG_FILE_NAME as y}from"../../../constants/common.js";import{PUBLIC_STATIC_FOLDER as F}from"../../constants/common.js";import{normalizeRouteSlug as s}from"../../../utils/path/normalize-route-slug.js";import{isLocalLink as C}from"../../../utils/path/is-local-link.js";import{reporter as T}from"../../tools/notifiers/reporter.js";import{followRedirectChain as k}from"./follow-redirect-chain.js";function D(e){const i=e.getConfig().redirects;if(!i)return;const o=e.getGlobalConfig("wildcardRedirectsTree")??{},c=e.getGlobalConfig("originalRedirectSources");for(const[r,l]of Object.entries(i)){const t=l?.to;if(!t||c&&!c.includes(r))continue;const d=r.toLowerCase(),L=t.toLowerCase(),m=r.endsWith("*"),f=t.endsWith("*");if(f)continue;const u=a=>{T.reportBrokenLink({type:"BROKEN_LINK",brokenLinkType:"LINK",sourceFileRelativePath:y,sourceFileLocation:{line:0},title:r,link:t,rawLink:t,message:a})};if(z(r,t,m,f)){u(`Redirect from "${r}" points to the same page. This causes an infinite redirect loop.`);continue}if(m&&!f&&C(t)){const a=s(r.split("*")[0]).toLowerCase(),p=s(L);if(a===p){u(`Circular redirect: "${r}" points to the same base path "${t}", causing an infinite redirect loop.`);continue}}if(!m&&!f&&C(t)){const a=s(d),p=s(L),g=k(p,[a],i,o,!1);if(g.type==="cycle"&&g.cycle.length>0){u(`Circular redirect: ${g.cycle.join(" \u2192 ")}.`);continue}}C(t)&&I(t,e)&&u(`Redirect target "${t}" does not exist. Check that the page or route exists.`)}}function z(e,n,i,o){if(!i&&!o){const c=s(e).toLowerCase(),r=s(n).toLowerCase();return c===r}return!1}function I(e,n){const i=s(e).toLowerCase();return n.slugHasRouteOrRedirect(i)?!1:!v(e,n)}function v(e,n){const o=decodeURI(e.split("?")[0].split("#")[0]).replace(/^\/+/,"");if(!o)return!1;const c=n.contentDir;return c?S(c,o)||S(h.join(c,F),o):!1}function S(e,n){const i=x(e,n);return i?P(i):!1}function x(e,n){const i=n.split("/").filter(Boolean);let o=e;for(const c of i){const r=h.join(o,c);if(R(r)){o=r;continue}let l;try{l=N(o)}catch{return null}const t=l.find(d=>d.toLowerCase()===c.toLowerCase());if(!t)return null;o=h.join(o,t)}return o}function P(e){if(!R(e))return!1;try{return w(e).isFile()}catch{return!1}}export{D as validateRedirects};
1
+ import h from"node:path";import{existsSync as R,lstatSync as y,readdirSync as N}from"node:fs";import{CONFIG_FILE_NAME as w}from"../../../constants/common.js";import{PUBLIC_STATIC_FOLDER as F}from"../../constants/common.js";import{normalizeRouteSlug as s}from"../../../utils/path/normalize-route-slug.js";import{isLocalLink as C}from"../../../utils/path/is-local-link.js";import{reporter as T}from"../../tools/notifiers/reporter.js";import{followRedirectChain as k}from"./follow-redirect-chain.js";function D(e){const i=e.getConfig().redirects;if(!i)return;const o=e.getGlobalConfig("wildcardRedirectsTree")??{},c=e.getGlobalConfig("originalRedirectSources");for(const[r,l]of Object.entries(i)){const t=l?.to;if(!t||c&&!c.includes(r))continue;const d=r.toLowerCase(),L=t.toLowerCase(),m=r.endsWith("*"),f=t.endsWith("*");if(f)continue;const u=a=>{T.reportBrokenLink({type:"BROKEN_LINK",brokenLinkType:"LINK",sourceFileRelativePath:w,sourceFileLocation:{line:0},title:r,link:t,rawLink:t,message:a})};if(z(r,t,m,f)){u(`Redirect from "${r}" points to the same page. This causes an infinite redirect loop.`);continue}if(m&&!f&&C(t)){const a=s(r.split("*")[0]).toLowerCase(),p=s(L);if(a===p){u(`Circular redirect: "${r}" points to the same base path "${t}", causing an infinite redirect loop.`);continue}}if(!m&&!f&&C(t)){const a=s(d),p=s(L),g=k(p,[a],i,o,!1);if(g.type==="cycle"&&g.cycle.length>0){u(`Circular redirect: ${g.cycle.join(" \u2192 ")}.`);continue}}C(t)&&I(t,e)&&u(`Redirect target "${t}" does not exist. Check that the page or route exists.`)}}function z(e,n,i,o){if(!i&&!o){const c=s(e).toLowerCase(),r=s(n).toLowerCase();return c===r}return!1}function I(e,n){const i=s(e);return n.hasRouteOrRedirectBySlug(i)?!1:!v(e,n)}function v(e,n){const o=decodeURI(e.split("?")[0].split("#")[0]).replace(/^\/+/,"");if(!o)return!1;const c=n.contentDir;return c?S(c,o)||S(h.join(c,F),o):!1}function S(e,n){const i=x(e,n);return i?P(i):!1}function x(e,n){const i=n.split("/").filter(Boolean);let o=e;for(const c of i){const r=h.join(o,c);if(R(r)){o=r;continue}let l;try{l=N(o)}catch{return null}const t=l.find(d=>d.toLowerCase()===c.toLowerCase());if(!t)return null;o=h.join(o,t)}return o}function P(e){if(!R(e))return!1;try{return y(e).isFile()}catch{return!1}}export{D as validateRedirects};
@@ -1 +1 @@
1
- import i from"node:path";import{withPathPrefix as f}from"@redocly/theme/core/utils";import{PUBLIC_STATIC_FOLDER as p}from"../constants/common.js";import{isLocalLink as u}from"../../utils/path/is-local-link.js";import{copyStaticFile as F,FileNotFoundError as d}from"./fs.js";async function h(r,n,o){if(!u(r))return r;const t=r.startsWith("/")?i.posix.join(p,r):void 0;if(t&&await n.exists(t))return f(r);const c=r.startsWith("/")?r.slice(1):i.posix.join(i.dirname(o.fromFileRelativePath),r),m=n.getFileInfo(c);if(!m)throw new d(`Cannot resolve asset path: ${r}`,r);return F(o.contentDir,m.realRelativePath,o.outdir)}export{h as resolveAssetPath};
1
+ import t from"node:path";import{withPathPrefix as f}from"@redocly/theme/core/utils";import{PUBLIC_STATIC_FOLDER as e}from"../constants/common.js";import{isLocalLink as p}from"../../utils/path/is-local-link.js";import{copyStaticFile as u,FileNotFoundError as x}from"./fs.js";async function h(r,o,i){if(!p(r))return r;const n=r.startsWith("/")?t.posix.join(e,r):void 0;if(n&&await o.exists(n))return f(r);const c=r.startsWith("/")?r.slice(1):t.posix.join(t.dirname(i.fromFileRelativePath),r),m=await o.exists(c)?await o.getFileInfo(c):null;if(!m)throw new x(`Cannot resolve asset path: ${r}`,r);return u(i.contentDir,m.realRelativePath,i.outdir)}export{h as resolveAssetPath};
@@ -1,7 +1,7 @@
1
- import"../node-crypto-polyfill.js";import{DOMParser as b}from"@xmldom/xmldom";import{SignedXml as B}from"xml-crypto";import F from"xpath";import{deflateSync as H,inflateSync as J}from"fflate";import{createHash as q}from"crypto";import{ulid as W}from"ulid";import{AuthProviderType as u,DEFAULT_TEAM_CLAIM_NAME as K}from"@redocly/config";import{AUTH_URL as Q,JWT_SECRET_KEY as I}from"../constants/common.js";import{getPathPrefix as X,withPathPrefix as Y}from"@redocly/theme/core/utils";import{DEFAULT_AUTHENTICATED_TEAM as G,REQUIRED_OIDC_SCOPES as D,ServerRoutes as N}from"../../constants/common.js";import{appendQueryParams as Z}from"../../utils/url/append-query-params.js";import{logger as ee}from"../tools/notifiers/logger.js";import{randomString as te}from"../utils/crypto/random-string.js";import{randomUUID as P}from"../utils/crypto/random-uuid.js";import{AlgorithmTypes as y,JwtTokenExpired as ne}from"./jwt/types.js";import*as p from"./jwt/jwt.js";import{parseTeamClaimToArray as re}from"../utils/index.js";import{arrayBufferToBase64 as ae,decodeBase64 as R,encodeBase64URL as oe,urlSafeBase64 as v}from"./jwt/encode.js";import{formatSamlCertificate as se}from"./utils/format-saml-certificate.js";function j(e){return e?.type===u.OIDC}function ie(e){return e?.type===u.SAML2}async function ze(e,t){if(j(t))return ce(e,t);if(ie(t))return ue(e,t)}async function ce(e,t){const r=await V(e,t),n=new Set((t.scopes||[]).concat(D)),a=t.authorizationRequestCustomParams||{};return{type:u.OIDC,idpId:e,name:"OAuth provider",authorizationEndpoint:r.authorization_endpoint,clientId:t.clientId,responseType:"code",scope:Array.from(n).join(" "),extraParams:a,pkce:t.pkce}}function ue(e,t){return{type:u.SAML2,idpId:e,name:"SAML2 provider",ssoUrl:t.ssoUrl,issuerId:t.issuerId,entityId:t.entityId||t.issuerId}}async function Be(e,t,r,n,a={}){const o=new Set((n.scopes||[]).concat(D));return await fetch(e,{method:"POST",body:new URLSearchParams({client_id:n.clientId,scope:Array.from(o).join(" "),code:t,redirect_uri:E(r),grant_type:"authorization_code",...n.clientSecret?{client_secret:n.clientSecret}:{},...a}).toString(),headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}}).then(s=>s.json())}function de(e,{authorizationEndpoint:t,clientId:r,responseType:n,scope:a,extraParams:o,idpId:s,pkce:l},m,A,S){if(!t||!r||!n||!a)return{loginUrl:void 0};const c=new URL(t),f=S?.redirectUriOverride??`${e}${Y(N.OIDC_CALLBACK)}`,_={state:P(),idpId:s,redirectUri:f,redirectTo:m,branch:S?.branchOverride??me(e),inviteCode:A,source:S?.sourceOverride??"portal"},h={};if(l){const d=v(te(50)),x=v(q("sha256").update(d).digest("base64")),g="S256";c.searchParams.append("code_challenge",x),c.searchParams.append("code_challenge_method",g),h.code_verifier={value:d,options:{secure:!0,httpOnly:!0,expires:new Date(Date.now()+1e3*60*10),path:X()||"/"}}}c.searchParams.append("client_id",r),c.searchParams.append("scope",a),c.searchParams.append("response_type",n),c.searchParams.append("redirect_uri",E(f)),c.searchParams.append("state",oe(JSON.stringify(_)));for(const d in o)o[d]!==void 0&&c.searchParams.append(d,o[d]);return{loginUrl:c.toString(),cookies:h}}function Fe(e,t,r,n){const a=new URL(e);return a.searchParams.append("post_logout_redirect_uri",t),n&&a.searchParams.append("state",n),a.searchParams.append("id_token_hint",r),a.toString()}async function He(e){const t=Math.floor(Date.now()/1e3),r=t+(e.ttlSec??600);return p.sign({type:"mcp_auth_code",client_id:e.clientId,redirect_uri:e.redirectUri,id_token:e.idToken,...e.idpAccessToken?{idp_access_token:e.idpAccessToken}:{},iat:t,exp:r},I,y.HS256)}async function Je(e){await p.verify(e,I,y.HS256);const{payload:t}=p.decode(e);if(t.type!=="mcp_auth_code")throw new Error("Invalid authorization code type");if(!t.client_id||!t.redirect_uri)throw new Error("Authorization code missing required claims");if(typeof t.exp=="number"&&Date.now()>=t.exp*1e3)throw new Error("Authorization code expired");return t}function qe(e){const t=e||W(),r=t.startsWith("mcp_")?t:`mcp_${t}`;return{id:r,object:"mcp_session",uri:`urn:redocly:realm:mcp:session:${r}`}}function E(e){return e.match(/^https:\/\/preview-[^\.]+--/)?"https://previewauth--"+e.split("--")[1]:e.match(/^(https:\/\/[^\.]+)--[^\.]+\.preview\./)?e.replace(/^(https:\/\/[^\.]+?)--[^\.]+\.preview\./,"$1.previewauth."):e}function me(e){return e.match(/^(https:\/\/[^\.]+)--([^\.]+)\.preview\./)?.[2]||void 0}function le(e){return e.type===u.OIDC}function pe(e){return e.type===u.SAML2}function We(e,t,r,n){return le(e)?de(t,e,r,n):pe(e)?fe(t,e,r,n):{}}function fe(e,t,r,n){const o=`<samlp:AuthnRequest xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
1
+ import"../node-crypto-polyfill.js";import{DOMParser as b}from"@xmldom/xmldom";import{SignedXml as B}from"xml-crypto";import F from"xpath";import{deflateSync as H,inflateSync as J}from"fflate";import{createHash as q}from"crypto";import{ulid as W}from"ulid";import{AuthProviderType as u,DEFAULT_TEAM_CLAIM_NAME as K}from"@redocly/config";import{AUTH_URL as Y,JWT_SECRET_KEY as I}from"../constants/common.js";import{envConfig as Q}from"../config/env-config.js";import{getPathPrefix as X,withPathPrefix as G}from"@redocly/theme/core/utils";import{DEFAULT_AUTHENTICATED_TEAM as Z,REQUIRED_OIDC_SCOPES as R,ServerRoutes as N}from"../../constants/common.js";import{appendQueryParams as ee}from"../../utils/url/append-query-params.js";import{logger as te}from"../tools/notifiers/logger.js";import{randomString as ne}from"../utils/crypto/random-string.js";import{randomUUID as U}from"../utils/crypto/random-uuid.js";import{AlgorithmTypes as y,JwtTokenExpired as re}from"./jwt/types.js";import*as p from"./jwt/jwt.js";import{parseTeamClaimToArray as oe}from"../utils/index.js";import{arrayBufferToBase64 as ae,decodeBase64 as P,encodeBase64URL as se,urlSafeBase64 as v}from"./jwt/encode.js";import{formatSamlCertificate as ie}from"./utils/format-saml-certificate.js";function E(e){return e?.type===u.OIDC}function ce(e){return e?.type===u.SAML2}async function Je(e,t){if(E(t))return ue(e,t);if(ce(t))return de(e,t)}async function ue(e,t){const r=await V(e,t),n=new Set((t.scopes||[]).concat(R)),o=t.authorizationRequestCustomParams||{};return{type:u.OIDC,idpId:e,name:"OAuth provider",authorizationEndpoint:r.authorization_endpoint,clientId:t.clientId,responseType:"code",scope:Array.from(n).join(" "),extraParams:o,pkce:t.pkce}}function de(e,t){return{type:u.SAML2,idpId:e,name:"SAML2 provider",ssoUrl:t.ssoUrl,issuerId:t.issuerId,entityId:t.entityId||t.issuerId}}async function qe(e,t,r,n,o={}){const a=new Set((n.scopes||[]).concat(R));return await fetch(e,{method:"POST",body:new URLSearchParams({client_id:n.clientId,scope:Array.from(a).join(" "),code:t,redirect_uri:j(r),grant_type:"authorization_code",...n.clientSecret?{client_secret:n.clientSecret}:{},...o}).toString(),headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}}).then(s=>s.json())}function me(e,{authorizationEndpoint:t,clientId:r,responseType:n,scope:o,extraParams:a,idpId:s,pkce:l},m,A,S){if(!t||!r||!n||!o)return{loginUrl:void 0};const c=new URL(t),f=S?.redirectUriOverride??`${e}${G(N.OIDC_CALLBACK)}`,_={state:U(),idpId:s,redirectUri:f,redirectTo:m,branch:S?.branchOverride??le(e),inviteCode:A,source:S?.sourceOverride??"portal"},h={};if(l){const d=v(ne(50)),x=v(q("sha256").update(d).digest("base64")),g="S256";c.searchParams.append("code_challenge",x),c.searchParams.append("code_challenge_method",g),h.code_verifier={value:d,options:{secure:!0,httpOnly:!0,expires:new Date(Date.now()+1e3*60*10),path:X()||"/"}}}c.searchParams.append("client_id",r),c.searchParams.append("scope",o),c.searchParams.append("response_type",n),c.searchParams.append("redirect_uri",j(f)),c.searchParams.append("state",se(JSON.stringify(_)));for(const d in a)a[d]!==void 0&&c.searchParams.append(d,a[d]);return{loginUrl:c.toString(),cookies:h}}function We(e,t,r,n){const o=new URL(e);return o.searchParams.append("post_logout_redirect_uri",t),n&&o.searchParams.append("state",n),o.searchParams.append("id_token_hint",r),o.toString()}async function Ke(e){const t=Math.floor(Date.now()/1e3),r=t+(e.ttlSec??600);return p.sign({type:"mcp_auth_code",client_id:e.clientId,redirect_uri:e.redirectUri,id_token:e.idToken,...e.idpAccessToken?{idp_access_token:e.idpAccessToken}:{},iat:t,exp:r},I,y.HS256)}async function Ye(e){await p.verify(e,I,y.HS256);const{payload:t}=p.decode(e);if(t.type!=="mcp_auth_code")throw new Error("Invalid authorization code type");if(!t.client_id||!t.redirect_uri)throw new Error("Authorization code missing required claims");if(typeof t.exp=="number"&&Date.now()>=t.exp*1e3)throw new Error("Authorization code expired");return t}function Qe(e){const t=e||W(),r=t.startsWith("mcp_")?t:`mcp_${t}`;return{id:r,object:"mcp_session",uri:`urn:redocly:realm:mcp:session:${r}`}}function j(e){return e.match(/^https:\/\/preview-[^\.]+--/)?"https://previewauth--"+e.split("--")[1]:e.match(/^(https:\/\/[^\.]+)--[^\.]+\.preview\./)?e.replace(/^(https:\/\/[^\.]+?)--[^\.]+\.preview\./,"$1.previewauth."):e}function le(e){return e.match(/^(https:\/\/[^\.]+)--([^\.]+)\.preview\./)?.[2]||void 0}function pe(e){return e.type===u.OIDC}function fe(e){return e.type===u.SAML2}function Xe(e,t,r,n){return pe(e)?me(t,e,r,n):fe(e)?he(t,e,r,n):{}}function he(e,t,r,n){const a=`<samlp:AuthnRequest xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
2
2
  xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
3
3
  Version="2.0"
4
- ID="_${P()}"
4
+ ID="_${U()}"
5
5
  IssueInstant="${new Date().toISOString()}"
6
6
  AssertionConsumerServiceURL="${e}${N.SAML_CALLBACK}"
7
7
  AttributeConsumingServiceIndex="0">
@@ -9,4 +9,4 @@ import"../node-crypto-polyfill.js";import{DOMParser as b}from"@xmldom/xmldom";im
9
9
  <samlp:NameIDPolicy
10
10
  AllowCreate="true"
11
11
  Format="urn:oasis:names:tc:SAML:2.0:nameid-format:persistent"/>
12
- </samlp:AuthnRequest>`,s=he(o);return{loginUrl:Z(t.ssoUrl,{SAMLRequest:s,RelayState:JSON.stringify({idpId:t.idpId,redirectTo:r,inviteCode:n,source:"portal"})})}}function he(e){return ae(H(new TextEncoder().encode(e)).buffer)}function Ke(e){const t=R(e);if(t.startsWith("<samlp:Response")||t.indexOf("<saml2p:Response")>-1)return t;const r=J(new Uint8Array(atob(e).split("").map(n=>n.charCodeAt(0))));return new TextDecoder().decode(r)}function Qe(e){try{return JSON.parse(R(e||""))}catch{throw new Error("Invalid OAuth2 state")}}function Xe(e){const t=new b().parseFromString(e,"application/xml"),n=i(t,"//*[local-name(.)='StatusCode']/@Value")[0]?.nodeValue?.endsWith("Success")||!1,o=i(t,"//*[local-name(.)='Response']/@Destination")[0]?.nodeValue||"",s=i(t,"//*[local-name(.)='Assertion']//*[local-name(.)='Issuer']/text()")[0],l=s&&s.nodeValue||void 0,m=i(t,"//*[local-name(.)='Audience']/text()")[0],A=m&&m.nodeValue||void 0,c=i(t,"//*[local-name(.)='Assertion']//*[local-name(.)='X509Certificate']/text()")[0]?.nodeValue||"",f=i(t,"//*[local-name(.)='Subject']//*[local-name(.)='NameID']/text()")[0],_=f&&f.nodeValue||"",h=i(t,"//*[local-name(.)='Subject']//*[local-name(.)='NameID']/@Format")[0],d=h&&h.nodeValue||"",x=i(t,"//*[local-name(.)='Conditions']/@NotOnOrAfter")[0],g=ye(x),T={},k=i(t,"//*[local-name(.)='AttributeStatement']//*[local-name(.)='Attribute']");if(k.length)for(const C of k){const O=i(C,"./@Name")[0];if(O.nodeValue){const U=i(C,"./*[local-name(.)='AttributeValue']/text()")[0];U?.nodeValue&&(T[O.nodeValue]=U.nodeValue)}}return{uid:_,success:n,expiresAt:g,issuerId:l,entityId:A,attrs:T,cert:c,nameFormat:d,destination:o}}function ye(e){const t=typeof e?.nodeValue=="string"&&L(Date.parse(e.nodeValue)),r=L(Date.now()),n=L(Date.now()+720*60*1e3);return t?t>r&&t<n?n:t:r}function L(e){return Math.floor(e/1e3)}const M={},w={jwks:{}};async function V(e,t){return M[e]||(M[e]=t.configurationUrl?await $(t.configurationUrl):t.configuration),M[e]}async function we(e){for(const t of Object.keys(e)){const r=e[t];if(!j(r))continue;const n=await V(t,r);if(n.jwks_uri){const a=await $(n.jwks_uri);for(const o of a.keys)w.jwks[o.kid]={...o,idpId:t}}}}async function $(e){return fetch(e,{headers:{Accept:"application/json"}}).then(t=>t.json())}async function Ye(e){return fetch(`${Q}/oidc/userinfo`,{headers:{Accept:"application/json",Authorization:`Bearer ${e}`}}).then(t=>t.status===200?t.json():void 0).catch(()=>{})}function Ge(e){if(!e.configurationUrl)return!1;const t=new URL(e.configurationUrl);return["localhost","127.0.0.1","blueharvest.cloud","bhstage.cloud","cloud.redocly.com","beta.redocly.com","cloud.eu.redocly.com","beta.eu.redocly.com","cba.au.redocly.com"].some(n=>Se(t.hostname,n))}function Se(e,t){return e===t||e.endsWith(`.${t}`)}async function Ze(e,t){const r=new b().parseFromString(e),n=i(r,"//*[local-name(.)='Signature' and namespace-uri(.)='http://www.w3.org/2000/09/xmldsig#']")[0];if(!n)throw new Error("Cannot find Signature in the SAML response");const a=se(t),o=new B({publicCert:a});o.loadSignature(n);try{return o.checkSignature(e)}catch{return!1}}function et(e,t,r,n){t==="urn:oasis:names:tc:SAML:2.0:nameid-format:transient"&&(e=r["http://schemas.microsoft.com/identity/claims/objectidentifier"]);let a;(t==="urn:oasis:names:tc:SAML:2.0:nameid-format:email"||t==="urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress")&&(a=e),t==="urn:oasis:names:tc:SAML:2.0:nameid-format:persistent"&&e?.match(/.+@.+/)&&(a=e);const o=r["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name"],s=o?.match(/.+@.+/);return a=a||r["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress"]||(s?o:void 0),a=a?.toLowerCase(),{sub:e,given_name:r["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname"],family_name:r["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname"],name:r["http://schemas.microsoft.com/identity/claims/displayname"]||o,email:a,email_verified:!0,teams:n?re(r[n]):[]}}function z(e,t={}){return e.map(r=>t[r]||r)}async function tt(e,t){if(!t)return{};const r=t.authorization;if(!r)return{};try{const n=p.decode(r);if(n.header.alg===y.RS256){w.jwks[n.header.kid]===void 0&&await we(e);const m=w.jwks[n.header.kid];if(!m)return w.jwks[n.header.kid]=null,{};await p.verify(r,m,y.RS256)}else await p.verify(r,I,y.HS256);const a=n.payload.idpId||w.jwks[n.header.kid]?.idpId,o=e[a]||{},s=xe(o),l=_e(o);return{...n.payload,email:n.payload.email?.toLowerCase(),idpId:a,teams:Array.from(new Set([...z(n.payload.teams||[],l),..."defaultTeams"in o&&o.defaultTeams||[],...z("teamsClaimName"in o&&n.payload[s||""]||[],l),G])),name:Ae(n.payload),isAuthenticated:!0,idpAccessToken:n.payload.idp_access_token||t.idp_access_token,federatedAccessToken:t.federated_access_token,federatedIdToken:t.federated_id_token,authCookie:r}}catch(n){n instanceof ne||ee.error("Malformed JWT token: %s",n.message)}return{}}function Ae(e){return(e.firstName&&e.lastName?`${e.firstName} ${e.lastName}`:e.name||e.given_name||e.firstName||e.lastName)||e.email}function _e(e){switch(e.type){case u.SAML2:return e.teamsAttributeMap;case u.OIDC:return e.teamsClaimMap;default:return}}function xe(e){switch(e.type){case u.SAML2:return e.teamsAttributeName;case u.OIDC:return e.teamsClaimName;default:return K}}function i(e,t){return F.select(t,e)||[]}export{We as buildLoginUrl,de as buildOidcLoginUrl,Fe as buildOidcLogoutUrl,fe as buildSAML2LoginUrl,He as createMcpAuthorizationCode,qe as createMcpSessionResource,Ke as decodeSamlResponse,he as encodeSAML2,et as extractUserClaims,ze as getAuthProviderLoginParams,ce as getOidcLoginParams,V as getOidcMetadata,Ye as getRedoclyTokenPayload,ue as getSaml2LoginParams,tt as getUserParamsFromCookies,Ae as getUsernameFromPayload,j as isOidcProviderConfig,Ge as isRedoclySso,ie as isSaml2ProviderConfig,Be as oidcExchangeCodeForToken,w as oidcJwksCache,M as oidcMetadataCache,Qe as parseOidcState,me as parsePreviewBranch,Xe as parseSamlResponse,E as rewritePreviewAuthRedirectUri,Je as verifyMcpAuthorizationCode,Ze as verifySAMLResponse};
12
+ </samlp:AuthnRequest>`,s=ye(a);return{loginUrl:ee(t.ssoUrl,{SAMLRequest:s,RelayState:JSON.stringify({idpId:t.idpId,redirectTo:r,inviteCode:n,source:"portal"})})}}function ye(e){return ae(H(new TextEncoder().encode(e)).buffer)}function Ge(e){const t=P(e);if(t.startsWith("<samlp:Response")||t.indexOf("<saml2p:Response")>-1)return t;const r=J(new Uint8Array(atob(e).split("").map(n=>n.charCodeAt(0))));return new TextDecoder().decode(r)}function Ze(e){try{return JSON.parse(P(e||""))}catch{throw new Error("Invalid OAuth2 state")}}function et(e){const t=new b().parseFromString(e,"application/xml"),n=i(t,"//*[local-name(.)='StatusCode']/@Value")[0]?.nodeValue?.endsWith("Success")||!1,a=i(t,"//*[local-name(.)='Response']/@Destination")[0]?.nodeValue||"",s=i(t,"//*[local-name(.)='Assertion']//*[local-name(.)='Issuer']/text()")[0],l=s&&s.nodeValue||void 0,m=i(t,"//*[local-name(.)='Audience']/text()")[0],A=m&&m.nodeValue||void 0,c=i(t,"//*[local-name(.)='Assertion']//*[local-name(.)='X509Certificate']/text()")[0]?.nodeValue||"",f=i(t,"//*[local-name(.)='Subject']//*[local-name(.)='NameID']/text()")[0],_=f&&f.nodeValue||"",h=i(t,"//*[local-name(.)='Subject']//*[local-name(.)='NameID']/@Format")[0],d=h&&h.nodeValue||"",x=i(t,"//*[local-name(.)='Conditions']/@NotOnOrAfter")[0],g=we(x),M={},C=i(t,"//*[local-name(.)='AttributeStatement']//*[local-name(.)='Attribute']");if(C.length)for(const T of C){const D=i(T,"./@Name")[0];if(D.nodeValue){const O=i(T,"./*[local-name(.)='AttributeValue']/text()")[0];O?.nodeValue&&(M[D.nodeValue]=O.nodeValue)}}return{uid:_,success:n,expiresAt:g,issuerId:l,entityId:A,attrs:M,cert:c,nameFormat:d,destination:a}}function we(e){const t=typeof e?.nodeValue=="string"&&L(Date.parse(e.nodeValue)),r=L(Date.now()),n=L(Date.now()+720*60*1e3);return t?t>r&&t<n?n:t:r}function L(e){return Math.floor(e/1e3)}const k={},w={jwks:{}};async function V(e,t){if(!k[e]){const r=t.configurationUrl?await $(t.configurationUrl):t.configuration;k[e]=Se()?Ae(r):r}return k[e]}function Se(){const e=Q.REDOCLY_ENFORCE_RESIDENCY;return!!e&&e.includes("host.docker.internal")}function Ae(e){if(typeof e!="object"||e===null)return e;const t={...e};for(const r of Object.keys(t)){const n=t[r];typeof n=="string"&&n.includes("://localhost")&&(t[r]=n.replace("://localhost","://host.docker.internal"))}return t}async function _e(e){for(const t of Object.keys(e)){const r=e[t];if(!E(r))continue;const n=await V(t,r);if(n.jwks_uri){const o=await $(n.jwks_uri);for(const a of o.keys)w.jwks[a.kid]={...a,idpId:t}}}}async function $(e){return fetch(e,{headers:{Accept:"application/json"}}).then(t=>t.json())}async function tt(e){return fetch(`${Y}/oidc/userinfo`,{headers:{Accept:"application/json",Authorization:`Bearer ${e}`}}).then(t=>t.status===200?t.json():void 0).catch(()=>{})}function nt(e){if(!e.configurationUrl)return!1;const t=new URL(e.configurationUrl);return["localhost","127.0.0.1","blueharvest.cloud","bhstage.cloud","cloud.redocly.com","beta.redocly.com","cloud.eu.redocly.com","beta.eu.redocly.com","cba.au.redocly.com"].some(n=>xe(t.hostname,n))}function xe(e,t){return e===t||e.endsWith(`.${t}`)}async function rt(e,t){const r=new b().parseFromString(e),n=i(r,"//*[local-name(.)='Signature' and namespace-uri(.)='http://www.w3.org/2000/09/xmldsig#']")[0];if(!n)throw new Error("Cannot find Signature in the SAML response");const o=ie(t),a=new B({publicCert:o});a.loadSignature(n);try{return a.checkSignature(e)}catch{return!1}}function ot(e,t,r,n){t==="urn:oasis:names:tc:SAML:2.0:nameid-format:transient"&&(e=r["http://schemas.microsoft.com/identity/claims/objectidentifier"]);let o;(t==="urn:oasis:names:tc:SAML:2.0:nameid-format:email"||t==="urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress")&&(o=e),t==="urn:oasis:names:tc:SAML:2.0:nameid-format:persistent"&&e?.match(/.+@.+/)&&(o=e);const a=r["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name"],s=a?.match(/.+@.+/);return o=o||r["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress"]||(s?a:void 0),o=o?.toLowerCase(),{sub:e,given_name:r["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname"],family_name:r["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname"],name:r["http://schemas.microsoft.com/identity/claims/displayname"]||a,email:o,email_verified:!0,teams:n?oe(r[n]):[]}}function z(e,t={}){return e.map(r=>t[r]||r)}async function at(e,t){if(!t)return{};const r=t.authorization;if(!r)return{};try{const n=p.decode(r);if(n.header.alg===y.RS256){w.jwks[n.header.kid]===void 0&&await _e(e);const m=w.jwks[n.header.kid];if(!m)return w.jwks[n.header.kid]=null,{};await p.verify(r,m,y.RS256)}else await p.verify(r,I,y.HS256);const o=n.payload.idpId||w.jwks[n.header.kid]?.idpId,a=e[o]||{},s=Le(a),l=Ie(a);return{...n.payload,email:n.payload.email?.toLowerCase(),idpId:o,teams:Array.from(new Set([...z(n.payload.teams||[],l),..."defaultTeams"in a&&a.defaultTeams||[],...z("teamsClaimName"in a&&n.payload[s||""]||[],l),Z])),name:ge(n.payload),isAuthenticated:!0,idpAccessToken:n.payload.idp_access_token||t.idp_access_token,federatedAccessToken:t.federated_access_token,federatedIdToken:t.federated_id_token,authCookie:r}}catch(n){n instanceof re||te.error("Malformed JWT token: %s",n.message)}return{}}function ge(e){return(e.firstName&&e.lastName?`${e.firstName} ${e.lastName}`:e.name||e.given_name||e.firstName||e.lastName)||e.email}function Ie(e){switch(e.type){case u.SAML2:return e.teamsAttributeMap;case u.OIDC:return e.teamsClaimMap;default:return}}function Le(e){switch(e.type){case u.SAML2:return e.teamsAttributeName;case u.OIDC:return e.teamsClaimName;default:return K}}function i(e,t){return F.select(t,e)||[]}export{Xe as buildLoginUrl,me as buildOidcLoginUrl,We as buildOidcLogoutUrl,he as buildSAML2LoginUrl,Ke as createMcpAuthorizationCode,Qe as createMcpSessionResource,Ge as decodeSamlResponse,ye as encodeSAML2,ot as extractUserClaims,Je as getAuthProviderLoginParams,ue as getOidcLoginParams,V as getOidcMetadata,tt as getRedoclyTokenPayload,de as getSaml2LoginParams,at as getUserParamsFromCookies,ge as getUsernameFromPayload,E as isOidcProviderConfig,nt as isRedoclySso,ce as isSaml2ProviderConfig,qe as oidcExchangeCodeForToken,w as oidcJwksCache,k as oidcMetadataCache,Ze as parseOidcState,le as parsePreviewBranch,et as parseSamlResponse,j as rewritePreviewAuthRedirectUri,Ye as verifyMcpAuthorizationCode,rt as verifySAMLResponse};
@@ -1 +1 @@
1
- import{setCookie as _,deleteCookie as q}from"hono/cookie";import{AuthProviderType as W}from"@redocly/config";import{withPathPrefix as I,getPathPrefix as R}from"@redocly/theme/core/utils";import{compareURIs as Y}from"../../../utils/url/compare-uris.js";import{ensureArray as b}from"../../../utils/array/ensure-array.js";import{ALTERNATIVE_AUD_CLAIM_NAME as F,JWT_SECRET_KEY as v,ORG_SLUG as Q,ORG_ID as Z}from"../../constants/common.js";import{DEFAULT_COOKIE_EXPIRATION as B,ServerRoutes as S}from"../../../constants/common.js";import{sanitizeRedirectPathname as z}from"../../../utils/url/sanitize-redirect-pathname.js";import{telemetry as M}from"../../telemetry/index.js";import{envConfig as H}from"../../config/env-config.js";import{getAuthProviderLoginParams as x,isOidcProviderConfig as $,isSaml2ProviderConfig as ee,oidcExchangeCodeForToken as re,buildLoginUrl as oe,decodeSamlResponse as ne,extractUserClaims as te,parseSamlResponse as ie,parseOidcState as se,verifySAMLResponse as ae,getUsernameFromPayload as de,buildOidcLogoutUrl as ce,getOidcMetadata as j,getRedoclyTokenPayload as le,isRedoclySso as ue,rewritePreviewAuthRedirectUri as pe,parsePreviewBranch as N,buildOidcLoginUrl as ge,createMcpSessionResource as k}from"../auth.js";import*as O from"../jwt/jwt.js";import{AlgorithmTypes as P}from"../jwt/types.js";import{handleErrorPageRender as fe}from"../utils.js";import{encodeBase64URL as me}from"../jwt/encode.js";async function ve(i){if(H.isProductionEnv)return i.newResponse(null,404,{});const{password:e,...r}=await i.req.json(),a=await O.sign({...r,name:r.username||r.email||"Unknown"},v,P.HS256);return _(i,"authorization",a,{path:R()||"/",httpOnly:!0,secure:!0,sameSite:"none"}),i.newResponse(null,200,{})}function $e(){return async i=>{const e=i.get("logger"),r=encodeURIComponent(i.req.query("message")||"");e.error(`Login error: ${r}`);const a=`${S.LOGIN}/?error=${encodeURIComponent(r)}`;return i.newResponse(null,301,{Location:a})}}function K(i){if(!i||!i.includes(S.MCP_CALLBACK))return null;try{const e=i.split("/"),r=e[e.length-1];if(r){const a=Buffer.from(r,"base64url").toString("utf-8");return JSON.parse(a).mcpSessionId||null}}catch{}return null}function Ue(i){return async e=>{const r=e.get("logger"),a=i.getConfig().ssoDirect,n=se(e.req.query("state")),f=n.idpId,t=n.source==="mcp"||n.redirectTo&&typeof n.redirectTo=="string"&&n.redirectTo.includes(S.MCP_CALLBACK),c=t?K(typeof n.redirectTo=="string"?n.redirectTo:void 0):null,s=a?.[f];if(!$(s))return r.error("OIDC login error: missing OIDC provider config"),e.text("Forbidden",403);const d=await j(f,s);if(a&&!d.token_endpoint){const p="Invalid OIDC configuration: token_endpoint is required";return r.error(`OIDC login error: ${p}`),e.text(p,500)}try{const p=d.token_endpoint,l=e.req.query("code"),m=e.req.query("error");if(m)return t&&M.sendMcpAuthorizationFailedMessage([{...k(c),error:`OIDC error: ${m}`,error_details:e.req.query("error_description")||null}]),fe(e,i,{slug:"/"},403,"403OIDC");if(!l){const w="Code is expected but not present";return r.error(`OIDC login error: ${w}`),t&&M.sendMcpAuthorizationFailedMessage([{...k(c),error:w,error_details:null}]),new Response(`Forbidden: ${w}`,{status:403})}const h=e.req.header("x-forwarded-host"),g=e.req.header("x-forwarded-proto")||"https",A=t&&typeof n.redirectUri=="string"?n.redirectUri:new URL(I(S.OIDC_CALLBACK),h?`${g}://${h}`:e.req.url).toString(),C=e.get("cookies")?.code_verifier,u=await re(p,l,A,s,{...s.tokenRequestCustomParams,...C?{code_verifier:C}:{}});if(u.error)return r.error(`Error from OIDC provider: "${u.error}"`),t&&M.sendMcpAuthorizationFailedMessage([{...k(c),error:`Token exchange error: ${u.error}`,error_details:u.error_description||null}]),e.text(`Forbidden: ${u.error_description||u.error}`,403);if(!u?.id_token){const w="No id_token, please, add openid to scopes";return r.error(`OIDC login error: ${w}`),t&&M.sendMcpAuthorizationFailedMessage([{...k(c),error:w,error_details:null}]),new Response(`Forbidden: ${w}`,{status:403})}const{payload:o,header:U}=O.decode(u.id_token),J=U.alg===P.RS256;if(s.audience?.length&&![...b(o.aud||[]),...b(o[F]||[])].some(L=>s.audience?.includes(L))){const L="No valid audience found in id_token";return r.error(`OIDC login error: ${L}`),t&&M.sendMcpAuthorizationFailedMessage([{...k(c),error:L,error_details:null}]),new Response(`Forbidden: ${L}`)}const E=J?u.id_token:await O.sign({...o,idpId:f},v,P.HS256);de(o)||r.warn("To display your username, the required 'email' or 'full_profile' scope must be added to the identity provider configuration");const D=s?.tokenExpirationTime?Date.now()+s.tokenExpirationTime*1e3:o.exp*1e3||Date.now()+B*1e3;if(s.introspectEndpoint){const w=await fetch(s.introspectEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({access_token:u.access_token})});if(w.ok){const T=(await w.json()).ext?.federatedIdentity;T&&(_(e,"federated_access_token",T.access_token||"",{path:R()||"/",httpOnly:!1,expires:new Date(D)}),_(e,"federated_id_token",T.id_token||"",{path:R()||"/",httpOnly:!1,expires:new Date(D)}))}else r.warn(`OIDC introspect error: ${w.statusText}`)}if(_(e,"authorization",E,{path:R()||"/",httpOnly:!0,expires:new Date(D)}),E!==u.id_token&&_(e,"idp_id_token",u.id_token||"",{path:R()||"/",httpOnly:!0,expires:new Date(D)}),_(e,"idp_access_token",u.access_token||"",{path:R()||"/",httpOnly:!0,expires:new Date(D)}),q(e,"code_verifier",{path:R()||"/"}),t&&n.redirectTo&&typeof n.redirectTo=="string"&&n.redirectTo.includes(S.MCP_CALLBACK)){const L=`${e.req.url.split("?")[0].replace(S.OIDC_CALLBACK,"")}${n.redirectTo}`;return e.newResponse(null,302,{Location:L})}const G=typeof n.redirectTo=="string"?n.redirectTo:void 0;let V=z(new URL(G||"/",e.req.url).pathname);const X=e.newResponse(null,302,{Location:V});return r.updateContext({email:o.email,subject:o.sub}),r.info("OIDC login successful"),X}catch(p){const l=p instanceof Error?p.message:String(p),m=p instanceof Error?p.stack:String(p);if(r.error(`OIDC login error: ${l}`),t&&M.sendMcpAuthorizationFailedMessage([{...k(c),error:l,error_details:m}]),p.error==="access_denied")return r.info("Access denied"),e.text("Forbidden",403)}const y="Something went wrong";return r.error(`OIDC login error: ${y}`),t&&M.sendMcpAuthorizationFailedMessage([{...k(c),error:y,error_details:null}]),e.text(y,500)}}function Te(i){return async e=>{const r=e.get("logger"),n=e.get("auth").claims?.idpId,t=i.getConfig().ssoDirect?.[n];if(e.req.method==="POST")return $(t)||q(e,"authorization",{path:R()||"/"}),r.info("Logout successful"),e.newResponse(null,200,{});let c;if($(t)){const s=(await j(n,t)).end_session_endpoint;if(s){const d=new URL(e.req.url),y=e.req.header("x-forwarded-proto")||d.protocol.slice(0,-1)||"https",p=e.req.header("x-forwarded-host")||d.host,l=`${y}://${p}`,m=N(l),h=m?me(JSON.stringify({branch:N(l)})):void 0,g=m?`${pe(l)}/_auth/logout`:`${l}/post-logout`;c=ce(s,g,e.get("cookies")?.idp_id_token||e.get("cookies")?.authorization||"",h)}}return r.info("Logout successful"),q(e,"authorization",{path:R()||"/"}),e.newResponse(null,302,{Location:c||I("/")})}}function qe(i){return async e=>{const r=i.getConfig().access?.logoutReturnUrl,a=r||I("/");return e.newResponse(null,302,{Location:a})}}function be(i){return async e=>{const r=e.get("logger"),a=e.req.param("code"),n=H.BH_API_URL,f=(t,c,s)=>t&&c?`${t} ${c.charAt(0)}`:s;try{if(!n)throw new Error("BH_API_URL is not set");const t=i.getConfig().ssoDirect;if(!t||!Object.keys(t).length)return r.warn("Invite no sso configured to handle"),e.redirect(I("/"));const c=await fetch(`${n}/user-invites/public/${a}`);if(!c.ok)return c.status===404?(r.warn(`Invite ${a} not found redirect to homepage`),e.redirect(I("/"))):(r.error("Invite error",await c.text()),e.redirect(I("/")));const s=await c.json(),d=new URL(I("/invite"),e.req.url);return d.searchParams.set("code",a),d.searchParams.set("org",s.organization.name),d.searchParams.set("invitedBy",f(s.invitedBy.firstName,s.invitedBy.lastName,s.invitedBy.name)),e.newResponse(null,302,{Location:d.toString()})}catch(t){return r.error("Error processing invite",{error:t,inviteCode:a}),e.text(t.message||"Failed to process invite",400)}}}function Ee(i){return async e=>{const r=e.get("logger"),a=i.getConfig().ssoDirect,n=new URL(e.req.url),f=e.req.query("inviteCode"),t=e.req.header("x-forwarded-proto")||n.protocol.slice(0,-1)||"https",c=e.req.header("x-forwarded-host")||n.host,s=`${t}://${c}`;let d=n.searchParams.get("idpId");const y=n.searchParams.get("redirectTo"),p=Object.keys(a||{})[0];d=d||p;const l=n.searchParams.get("mcp_redirect_uri"),m=!!l;if(!a?.[d]){const o="Invalid idpId";if(r.error(`IdP login error: ${o}`),m){const U=K(y||void 0);M.sendMcpAuthorizationFailedMessage([{...k(U),error:o,error_details:null}])}return e.text(`Forbidden: ${o}`,403)}const g=d&&a?await x(d,a[d]):void 0,A={};for(const o of Object.keys(g?.extraParams||{}))A[o]=n.searchParams.get(o)||g?.extraParams?.[o]||void 0;let C,u={};if(m&&l&&g&&g.type===W.OIDC){r.info(`Building MCP OAuth login URL with redirect_uri: ${l}`);const o=ge("",{...g,extraParams:A},y,f,{redirectUriOverride:l,sourceOverride:"mcp",branchOverride:void 0});C=o.loginUrl,u=o.cookies||{}}else if(g){const o=oe({...g,extraParams:A},s,y,f);C=o.loginUrl,u=o.cookies||{}}return Object.keys(u).forEach(o=>{_(e,o,u[o].value,u[o].options)}),r.info(`IdP login initiated for ID '${d}'`),e.newResponse(null,302,{Location:C||new URL(e.req.url).pathname})}}function Fe(i){return async e=>{const r=e.get("logger"),a=await e.req.formData(),n=a.get("SAMLResponse"),f=a.get("RelayState");if(typeof n!="string"||typeof f!="string"){const o="SAMLResponse is required";return r.error(`SAML2 login error: ${o}`),e.text(`Bad request: ${o}`,400)}const t=ne(n),{success:c,uid:s,nameFormat:d,attrs:y,issuerId:p,expiresAt:l}=ie(t),{idpId:m,redirectTo:h}=JSON.parse(f);if(!c){const o="SAML2 assertion is not successful";return r.error(`SAML2 login error: ${o}`),e.text(`Permission denied: ${o}`,401)}if(!l||Math.ceil(Date.now()/1e3)>=l){const o="SAML2 Token Expired";return r.error(`SAML2 login error: ${o}`),e.text(o,401)}const g=i.getConfig().ssoDirect?.[m];if(!g||!ee(g)){const o="Cannot find valid IdP";return r.error(`SAML2 login error: ${o}`),e.text(`Permission denied: ${o}`,401)}if(!(g.issuerId&&p&&Y(g.issuerId,p))){const o="IssuerID is misconfigured or untrusted assertions issuer received";return r.error(`SAML2 login error: ${o}`),e.text(`Permission denied: ${o}`,401)}if(!await ae(t,g.x509PublicCert)){const o="SAMLResponse signature invalid";return r.error(`SAML2 login error: ${o}`),e.text(o,401)}const C=te(s,d,y,g.teamsAttributeName);if(!C.sub){const o="The provider did not return a valid user identity.";return r.error(`SAML2 login error: ${o}`),e.text(o,400)}if(!C.email){const o="The provider did not return a valid user email.";return r.error(`SAML2 login error: ${o}`),e.text(o,400)}const u=await O.sign({...C,idpId:m},v,P.HS256);return _(e,"authorization",u,{path:R()||"/",httpOnly:!0,expires:new Date(l*1e3)}),r.updateContext({email:C.email,subject:C.sub}),r.info("SAML2 login successful"),e.newResponse(null,302,{Location:h||"/"})}}function Be(i){return async e=>{const r=e.get("logger"),a=new URL(e.req.query("redirectTo")||"/",e.req.url),n=I(z(a.pathname)),f=i.getConfig().ssoDirect,t=Object.entries(f||{}).find(([,h])=>$(h)&&ue(h));if(!(f&&t))return e.newResponse(null,302,{Location:n});const s=e.req.query("token"),d=s&&await le(s);if(!d)return e.newResponse(null,302,{Location:n});if(!b(d[F]||[]).some(h=>h===Q||h===Z))return e.newResponse(null,302,{Location:n});const l=await O.sign({...d,idpId:t?.at(0)},v,P.HS256),m=Date.now()+B*1e3;return _(e,"authorization",l,{path:R()||"/",httpOnly:!0,expires:new Date(m),sameSite:"None",secure:!0}),r.info("Token login successful"),e.newResponse(null,302,{Location:n})}}export{ve as authorizeHandler,Ee as idpLoginHandler,be as inviteHandler,Te as logoutHandler,Ue as oidcCallbackHandler,qe as postLogoutHandler,$e as redoclyLoginCallbackHandler,Be as redoclyTokenLoginHandler,Fe as samlCallbackHandler};
1
+ import{setCookie as L,deleteCookie as q}from"hono/cookie";import{AuthProviderType as V}from"@redocly/config";import{withPathPrefix as M,getPathPrefix as R}from"@redocly/theme/core/utils";import{compareURIs as X}from"../../../utils/url/compare-uris.js";import{ensureArray as b}from"../../../utils/array/ensure-array.js";import{ALTERNATIVE_AUD_CLAIM_NAME as E,JWT_SECRET_KEY as $,ORG_SLUG as W,ORG_ID as Y}from"../../constants/common.js";import{DEFAULT_COOKIE_EXPIRATION as F,ServerRoutes as S}from"../../../constants/common.js";import{sanitizeRedirectPathname as B}from"../../../utils/url/sanitize-redirect-pathname.js";import{telemetry as k}from"../../telemetry/index.js";import{envConfig as z}from"../../config/env-config.js";import{getAuthProviderLoginParams as Q,isOidcProviderConfig as U,isSaml2ProviderConfig as Z,oidcExchangeCodeForToken as x,buildLoginUrl as ee,decodeSamlResponse as re,extractUserClaims as oe,parseSamlResponse as ne,parseOidcState as te,verifySAMLResponse as ie,getUsernameFromPayload as se,buildOidcLogoutUrl as ae,getOidcMetadata as H,getRedoclyTokenPayload as de,isRedoclySso as ce,rewritePreviewAuthRedirectUri as le,parsePreviewBranch as j,buildOidcLoginUrl as ue,createMcpSessionResource as A}from"../auth.js";import*as O from"../jwt/jwt.js";import{AlgorithmTypes as v}from"../jwt/types.js";import{handleErrorPageRender as pe}from"../utils.js";import{encodeBase64URL as ge}from"../jwt/encode.js";async function Oe(i){if(z.isProductionEnv)return i.newResponse(null,404,{});const{password:e,...r}=await i.req.json(),a=await O.sign({...r,name:r.username||r.email||"Unknown"},$,v.HS256);return L(i,"authorization",a,{path:R()||"/",httpOnly:!0,secure:!0,sameSite:"none"}),i.newResponse(null,200,{})}function ve(){return async i=>{const e=i.get("logger"),r=encodeURIComponent(i.req.query("message")||"");e.error(`Login error: ${r}`);const a=`${S.LOGIN}/?error=${encodeURIComponent(r)}`;return i.newResponse(null,301,{Location:a})}}function N(i){if(!i||!i.includes(S.MCP_CALLBACK))return null;try{const e=i.split("/"),r=e[e.length-1];if(r){const a=Buffer.from(r,"base64url").toString("utf-8");return JSON.parse(a).mcpSessionId||null}}catch{}return null}function Pe(i){return async e=>{const r=e.get("logger"),a=i.getConfig().ssoDirect,n=te(e.req.query("state")),m=n.idpId,t=n.source==="mcp"||n.redirectTo&&typeof n.redirectTo=="string"&&n.redirectTo.includes(S.MCP_CALLBACK),c=t?N(typeof n.redirectTo=="string"?n.redirectTo:void 0):null,s=a?.[m];if(!U(s))return r.error("OIDC login error: missing OIDC provider config"),e.text("Forbidden",403);const d=await H(m,s);if(a&&!d.token_endpoint){const u="Invalid OIDC configuration: token_endpoint is required";return r.error(`OIDC login error: ${u}`),e.text(u,500)}try{const u=d.token_endpoint,l=e.req.query("code"),h=e.req.query("error");if(h)return t&&k.sendMcpAuthorizationFailedMessage([{...A(c),error:`OIDC error: ${h}`,error_details:e.req.query("error_description")||null}]),pe(e,i,{slug:"/"},403,"403OIDC");if(!l){const w="Code is expected but not present";return r.error(`OIDC login error: ${w}`),t&&k.sendMcpAuthorizationFailedMessage([{...A(c),error:w,error_details:null}]),new Response(`Forbidden: ${w}`,{status:403})}const C=typeof n.redirectUri=="string"?n.redirectUri:new URL(M(S.OIDC_CALLBACK),e.req.url).toString(),p=e.get("cookies")?.code_verifier,g=await x(u,l,C,s,{...s.tokenRequestCustomParams,...p?{code_verifier:p}:{}});if(g.error)return r.error(`Error from OIDC provider: "${g.error}"`),t&&k.sendMcpAuthorizationFailedMessage([{...A(c),error:`Token exchange error: ${g.error}`,error_details:g.error_description||null}]),e.text(`Forbidden: ${g.error_description||g.error}`,403);if(!g?.id_token){const w="No id_token, please, add openid to scopes";return r.error(`OIDC login error: ${w}`),t&&k.sendMcpAuthorizationFailedMessage([{...A(c),error:w,error_details:null}]),new Response(`Forbidden: ${w}`,{status:403})}const{payload:f,header:_}=O.decode(g.id_token),o=_.alg===v.RS256;if(s.audience?.length&&![...b(f.aud||[]),...b(f[E]||[])].some(I=>s.audience?.includes(I))){const I="No valid audience found in id_token";return r.error(`OIDC login error: ${I}`),t&&k.sendMcpAuthorizationFailedMessage([{...A(c),error:I,error_details:null}]),new Response(`Forbidden: ${I}`)}const P=o?g.id_token:await O.sign({...f,idpId:m},$,v.HS256);se(f)||r.warn("To display your username, the required 'email' or 'full_profile' scope must be added to the identity provider configuration");const D=s?.tokenExpirationTime?Date.now()+s.tokenExpirationTime*1e3:f.exp*1e3||Date.now()+F*1e3;if(s.introspectEndpoint){const w=await fetch(s.introspectEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({access_token:g.access_token})});if(w.ok){const T=(await w.json()).ext?.federatedIdentity;T&&(L(e,"federated_access_token",T.access_token||"",{path:R()||"/",httpOnly:!1,expires:new Date(D)}),L(e,"federated_id_token",T.id_token||"",{path:R()||"/",httpOnly:!1,expires:new Date(D)}))}else r.warn(`OIDC introspect error: ${w.statusText}`)}if(L(e,"authorization",P,{path:R()||"/",httpOnly:!0,expires:new Date(D)}),P!==g.id_token&&L(e,"idp_id_token",g.id_token||"",{path:R()||"/",httpOnly:!0,expires:new Date(D)}),L(e,"idp_access_token",g.access_token||"",{path:R()||"/",httpOnly:!0,expires:new Date(D)}),q(e,"code_verifier",{path:R()||"/"}),t&&n.redirectTo&&typeof n.redirectTo=="string"&&n.redirectTo.includes(S.MCP_CALLBACK)){const I=`${e.req.url.split("?")[0].replace(S.OIDC_CALLBACK,"")}${n.redirectTo}`;return e.newResponse(null,302,{Location:I})}const K=typeof n.redirectTo=="string"?n.redirectTo:void 0;let J=B(new URL(K||"/",e.req.url).pathname);const G=e.newResponse(null,302,{Location:J});return r.updateContext({email:f.email,subject:f.sub}),r.info("OIDC login successful"),G}catch(u){const l=u instanceof Error?u.message:String(u),h=u instanceof Error?u.stack:String(u);if(r.error(`OIDC login error: ${l}`),t&&k.sendMcpAuthorizationFailedMessage([{...A(c),error:l,error_details:h}]),u.error==="access_denied")return r.info("Access denied"),e.text("Forbidden",403)}const y="Something went wrong";return r.error(`OIDC login error: ${y}`),t&&k.sendMcpAuthorizationFailedMessage([{...A(c),error:y,error_details:null}]),e.text(y,500)}}function $e(i){return async e=>{const r=e.get("logger"),n=e.get("auth").claims?.idpId,t=i.getConfig().ssoDirect?.[n];if(e.req.method==="POST")return U(t)||q(e,"authorization",{path:R()||"/"}),r.info("Logout successful"),e.newResponse(null,200,{});let c;if(U(t)){const s=(await H(n,t)).end_session_endpoint;if(s){const d=new URL(e.req.url),y=e.req.header("x-forwarded-proto")||d.protocol.slice(0,-1)||"https",u=e.req.header("x-forwarded-host")||d.host,l=`${y}://${u}`,h=j(l),C=h?ge(JSON.stringify({branch:j(l)})):void 0,p=h?`${le(l)}/_auth/logout`:`${l}/post-logout`;c=ae(s,p,e.get("cookies")?.idp_id_token||e.get("cookies")?.authorization||"",C)}}return r.info("Logout successful"),q(e,"authorization",{path:R()||"/"}),e.newResponse(null,302,{Location:c||M("/")})}}function Ue(i){return async e=>{const r=i.getConfig().access?.logoutReturnUrl,a=r||M("/");return e.newResponse(null,302,{Location:a})}}function Te(i){return async e=>{const r=e.get("logger"),a=e.req.param("code"),n=z.BH_API_URL,m=(t,c,s)=>t&&c?`${t} ${c.charAt(0)}`:s;try{if(!n)throw new Error("BH_API_URL is not set");const t=i.getConfig().ssoDirect;if(!t||!Object.keys(t).length)return r.warn("Invite no sso configured to handle"),e.redirect(M("/"));const c=await fetch(`${n}/user-invites/public/${a}`);if(!c.ok)return c.status===404?(r.warn(`Invite ${a} not found redirect to homepage`),e.redirect(M("/"))):(r.error("Invite error",await c.text()),e.redirect(M("/")));const s=await c.json(),d=new URL(M("/invite"),e.req.url);return d.searchParams.set("code",a),d.searchParams.set("org",s.organization.name),d.searchParams.set("invitedBy",m(s.invitedBy.firstName,s.invitedBy.lastName,s.invitedBy.name)),e.newResponse(null,302,{Location:d.toString()})}catch(t){return r.error("Error processing invite",{error:t,inviteCode:a}),e.text(t.message||"Failed to process invite",400)}}}function qe(i){return async e=>{const r=e.get("logger"),a=i.getConfig().ssoDirect,n=new URL(e.req.url),m=e.req.query("inviteCode"),t=e.req.header("x-forwarded-proto")||n.protocol.slice(0,-1)||"https",c=e.req.header("x-forwarded-host")||n.host,s=`${t}://${c}`;let d=n.searchParams.get("idpId");const y=n.searchParams.get("redirectTo"),u=Object.keys(a||{})[0];d=d||u;const l=n.searchParams.get("mcp_redirect_uri"),h=!!l;if(!a?.[d]){const o="Invalid idpId";if(r.error(`IdP login error: ${o}`),h){const P=N(y||void 0);k.sendMcpAuthorizationFailedMessage([{...A(P),error:o,error_details:null}])}return e.text(`Forbidden: ${o}`,403)}const p=d&&a?await Q(d,a[d]):void 0,g={};for(const o of Object.keys(p?.extraParams||{}))g[o]=n.searchParams.get(o)||p?.extraParams?.[o]||void 0;let f,_={};if(h&&l&&p&&p.type===V.OIDC){r.info(`Building MCP OAuth login URL with redirect_uri: ${l}`);const o=ue("",{...p,extraParams:g},y,m,{redirectUriOverride:l,sourceOverride:"mcp",branchOverride:void 0});f=o.loginUrl,_=o.cookies||{}}else if(p){const o=ee({...p,extraParams:g},s,y,m);f=o.loginUrl,_=o.cookies||{}}return Object.keys(_).forEach(o=>{L(e,o,_[o].value,_[o].options)}),r.info(`IdP login initiated for ID '${d}'`),e.newResponse(null,302,{Location:f||new URL(e.req.url).pathname})}}function be(i){return async e=>{const r=e.get("logger"),a=await e.req.formData(),n=a.get("SAMLResponse"),m=a.get("RelayState");if(typeof n!="string"||typeof m!="string"){const o="SAMLResponse is required";return r.error(`SAML2 login error: ${o}`),e.text(`Bad request: ${o}`,400)}const t=re(n),{success:c,uid:s,nameFormat:d,attrs:y,issuerId:u,expiresAt:l}=ne(t),{idpId:h,redirectTo:C}=JSON.parse(m);if(!c){const o="SAML2 assertion is not successful";return r.error(`SAML2 login error: ${o}`),e.text(`Permission denied: ${o}`,401)}if(!l||Math.ceil(Date.now()/1e3)>=l){const o="SAML2 Token Expired";return r.error(`SAML2 login error: ${o}`),e.text(o,401)}const p=i.getConfig().ssoDirect?.[h];if(!p||!Z(p)){const o="Cannot find valid IdP";return r.error(`SAML2 login error: ${o}`),e.text(`Permission denied: ${o}`,401)}if(!(p.issuerId&&u&&X(p.issuerId,u))){const o="IssuerID is misconfigured or untrusted assertions issuer received";return r.error(`SAML2 login error: ${o}`),e.text(`Permission denied: ${o}`,401)}if(!await ie(t,p.x509PublicCert)){const o="SAMLResponse signature invalid";return r.error(`SAML2 login error: ${o}`),e.text(o,401)}const f=oe(s,d,y,p.teamsAttributeName);if(!f.sub){const o="The provider did not return a valid user identity.";return r.error(`SAML2 login error: ${o}`),e.text(o,400)}if(!f.email){const o="The provider did not return a valid user email.";return r.error(`SAML2 login error: ${o}`),e.text(o,400)}const _=await O.sign({...f,idpId:h},$,v.HS256);return L(e,"authorization",_,{path:R()||"/",httpOnly:!0,expires:new Date(l*1e3)}),r.updateContext({email:f.email,subject:f.sub}),r.info("SAML2 login successful"),e.newResponse(null,302,{Location:C||"/"})}}function Ee(i){return async e=>{const r=e.get("logger"),a=new URL(e.req.query("redirectTo")||"/",e.req.url),n=M(B(a.pathname)),m=i.getConfig().ssoDirect,t=Object.entries(m||{}).find(([,C])=>U(C)&&ce(C));if(!(m&&t))return e.newResponse(null,302,{Location:n});const s=e.req.query("token"),d=s&&await de(s);if(!d)return e.newResponse(null,302,{Location:n});if(!b(d[E]||[]).some(C=>C===W||C===Y))return e.newResponse(null,302,{Location:n});const l=await O.sign({...d,idpId:t?.at(0)},$,v.HS256),h=Date.now()+F*1e3;return L(e,"authorization",l,{path:R()||"/",httpOnly:!0,expires:new Date(h),sameSite:"None",secure:!0}),r.info("Token login successful"),e.newResponse(null,302,{Location:n})}}export{Oe as authorizeHandler,qe as idpLoginHandler,Te as inviteHandler,$e as logoutHandler,Pe as oidcCallbackHandler,Ue as postLogoutHandler,ve as redoclyLoginCallbackHandler,Ee as redoclyTokenLoginHandler,be as samlCallbackHandler};
@@ -1,5 +1,6 @@
1
1
  import type { Context } from 'hono';
2
2
  export declare function corsProxyHandler(proxyBasePath?: string): (ctx: Context) => Promise<Response>;
3
+ export declare function isPrivateIp(ip: string): boolean;
3
4
  export declare function resolveCorsProxyTarget(requestUrl: string, proxyBasePath: string): URL | null;
4
5
  export declare const CORS_PROXY_STREAM_HEADER = "x-redocly-proxy-streaming";
5
6
  //# sourceMappingURL=cors-proxy.d.ts.map
@@ -1,2 +1,2 @@
1
- import{withPathPrefix as _}from"@redocly/theme/core/utils";import{ServerRoutes as q}from"../../../constants/common.js";import{getRequestOrigin as C}from"../utils/get-request-origin.js";const P=new Set(["connection","keep-alive","proxy-authenticate","proxy-connection","proxy-authorization","te","trailer","transfer-encoding","upgrade","host"]),$=new Set(["cookie","cookie2","accept-encoding"]),T=new Set(["set-cookie","set-cookie2","content-encoding","content-length"]),g="x-redocly-proxy-streaming",H="x-http-method-override",w="x-redocly-cookie";function z(o=_(q.CORS_PROXY)){return async e=>{const n=new URL(e.req.url).pathname;if(n===o||n===`${o}/`)return e.text(`Realm CORS proxy endpoint.
2
- Usage: ${o}/https://api.example.com/path`);const r=I(e.req.url,o);if(!r)return e.text("Invalid proxied URL",400);const i=C(e),c=r.origin===i,h=r.pathname===o||r.pathname.startsWith(`${o}/`);if(c&&!h)return new Response("Please use a direct request",{status:308,headers:{Location:r.toString(),Vary:"origin","Cache-Control":"private"}});const s=new Headers,f=S(e.req.raw.headers);for(const[t,E]of e.req.raw.headers)f.has(t.toLowerCase())||$.has(t.toLowerCase())||s.append(t,E);const d=s.get(w);if(d){const t=e.req.raw.headers.get("cookie")||"";s.set("cookie",t?`${t}; ${d}`:d),s.delete(w)}const u=e.req.raw.headers.get("origin")||"";L(u)&&s.delete("origin");let p=e.req.method;const R=s.get(H);R&&(p=R.toUpperCase(),s.delete(H));const m={method:p,headers:s,redirect:"follow"};p!=="GET"&&p!=="HEAD"&&e.req.raw.body&&(m.body=e.req.raw.body,m.duplex="half");let a;try{a=await fetch(r,m)}catch(t){const E=t instanceof Error?t.message:"unknown error",O=t instanceof Error&&t.cause instanceof Error?`: ${t.cause.message}`:"";return e.text(`Failed to proxy request: ${E}${O}`,502)}const l=new Headers(a.headers),y=S(a.headers);for(const t of y)l.delete(t);for(const t of T)l.delete(t);return l.set(g,"1"),new Response(a.body,{status:a.status,statusText:a.statusText,headers:l})}}function k(o){try{return decodeURIComponent(o)}catch{return o}}function D(o){return o.replace(/^(https?):\/(?!\/)/i,"$1://")}function A(o,e){return e?o.includes("?")?e==="?"?o:`${o.endsWith("?")||o.endsWith("&")?o:`${o}&`}${e.slice(1)}`:`${o}${e}`:o}function S(o){const e=new Set(P),n=o.get("connection");if(!n)return e;for(const r of n.split(",")){const i=r.trim().toLowerCase();i&&e.add(i)}return e}function L(o){const e=o.toLowerCase();return e.includes(".redocly.app")||e.includes("localhost")}function I(o,e){const n=new URL(o),r=n.pathname===e,i=n.pathname.startsWith(`${e}/`);if(!r&&!i)return null;const c=n.pathname.slice(e.length).replace(/^\/+/,"");if(!c)return null;const h=[c,k(c)];for(const s of h){const f=D(s),d=A(f,n.search);try{const u=new URL(d);if(u.protocol==="http:"||u.protocol==="https:")return u}catch{continue}}return null}const U=g;export{U as CORS_PROXY_STREAM_HEADER,z as corsProxyHandler,I as resolveCorsProxyTarget};
1
+ import _ from"node:dns";import{isIP as T}from"node:net";import{withPathPrefix as D}from"@redocly/theme/core/utils";import{ServerRoutes as $}from"../../../constants/common.js";import{envConfig as w}from"../../config/env-config.js";import{getRequestOrigin as k}from"../utils/get-request-origin.js";const I=new Set(["connection","keep-alive","proxy-authenticate","proxy-connection","proxy-authorization","te","trailer","transfer-encoding","upgrade","host"]),L=new Set(["cookie","cookie2","accept-encoding"]),A=new Set(["set-cookie","set-cookie2","content-encoding","content-length"]),E="x-redocly-proxy-streaming",H="x-http-method-override",y="x-redocly-cookie";function Q(t=D($.CORS_PROXY)){return async e=>{const o=new URL(e.req.url).pathname;if(o===t||o===`${t}/`)return e.text(`Realm CORS proxy endpoint.
2
+ Usage: ${t}/https://api.example.com/path`);const n=F(e.req.url,t);if(!n)return e.text("Invalid proxied URL",400);const i=k(e),d=n.origin===i,f=n.pathname===t||n.pathname.startsWith(`${t}/`);if(d&&!f)return new Response("Please use a direct request",{status:308,headers:{Location:n.toString(),Vary:"origin","Cache-Control":"private"}});const u=await z(n.hostname);if((!w.isDevelopMode||w.isReunite)&&u&&N(u))return e.text("Requests to private network addresses are not allowed",403);const s=new Headers,h=S(e.req.raw.headers);for(const[r,g]of e.req.raw.headers)h.has(r.toLowerCase())||L.has(r.toLowerCase())||s.append(r,g);const a=s.get(y);if(a){const r=e.req.raw.headers.get("cookie")||"";s.set("cookie",r?`${r}; ${a}`:a),s.delete(y)}const C=e.req.raw.headers.get("origin")||"";W(C)&&s.delete("origin");let p=e.req.method;const R=s.get(H);R&&(p=R.toUpperCase(),s.delete(H));const m={method:p,headers:s,redirect:"manual"};p!=="GET"&&p!=="HEAD"&&e.req.raw.body&&(m.body=e.req.raw.body,m.duplex="half");let c;try{c=await fetch(n,m)}catch(r){const g=r instanceof Error?r.message:"unknown error",P=r instanceof Error&&r.cause instanceof Error?`: ${r.cause.message}`:"";return e.text(`Failed to proxy request: ${g}${P}`,502)}const O=c.headers.get("content-type")||"";if(Y(O)&&e.req.raw.headers.get("sec-fetch-mode")==="navigate")return e.text("Direct browser navigation to proxied HTML or JavaScript content is not allowed",403);const l=new Headers(c.headers),q=S(c.headers);for(const r of q)l.delete(r);for(const r of A)l.delete(r);return l.set(E,"1"),new Response(c.body,{status:c.status,statusText:c.statusText,headers:l})}}function x(t){try{return decodeURIComponent(t)}catch{return t}}function M(t){return t.replace(/^(https?):\/(?!\/)/i,"$1://")}function b(t,e){return e?t.includes("?")?e==="?"?t:`${t.endsWith("?")||t.endsWith("&")?t:`${t}&`}${e.slice(1)}`:`${t}${e}`:t}function S(t){const e=new Set(I),o=t.get("connection");if(!o)return e;for(const n of o.split(",")){const i=n.trim().toLowerCase();i&&e.add(i)}return e}function W(t){const e=t.toLowerCase();return e.includes(".redocly.app")||e.includes("localhost")}async function z(t){if(T(t))return t;try{const{address:e}=await _.promises.lookup(t);return e}catch{return null}}function N(t){const e=t.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i);return e?v(e[1]):t.includes(":")?U(t):v(t)}function v(t){const e=t.split(".").map(Number);if(e.length!==4||e.some(i=>isNaN(i)))return!0;const[o,n]=e;return o===0||o===10||o===127||o===172&&n>=16&&n<=31||o===192&&n===168||o===169&&n===254||o===100&&n>=64&&n<=127}function U(t){const e=t.toLowerCase();return e==="::1"||e==="::"||e.startsWith("fc")||e.startsWith("fd")||e.startsWith("fe80")}function Y(t){const e=t.toLowerCase();return e.includes("text/html")||e.includes("javascript")||e.includes("application/xhtml")||e.includes("application/xml")||e.includes("image/svg")}function F(t,e){const o=new URL(t),n=o.pathname===e,i=o.pathname.startsWith(`${e}/`);if(!n&&!i)return null;const d=o.pathname.slice(e.length).replace(/^\/+/,"");if(!d)return null;const f=[d,x(d)];for(const u of f){const s=M(u),h=b(s,o.search);try{const a=new URL(h);if(a.protocol==="http:"||a.protocol==="https:")return a}catch{continue}}return null}const Z=E;export{Z as CORS_PROXY_STREAM_HEADER,Q as corsProxyHandler,N as isPrivateIp,F as resolveCorsProxyTarget};
@@ -1 +1 @@
1
- import{envConfig as c}from"../../../config/env-config.js";import{getClientIp as v}from"../../utils/get-client-ip.js";import{PRODUCT_NAME as d}from"../../../../config/product-gates.js";import{toAttribute as t,getAttributesStringValue as g}from"./otlp.js";const p=c.OTEL_TRACES_URL||"https://otel.cloud.redocly.com/v1/traces";async function T(e){const o=await e.req.json(),r=m(e),s={resourceSpans:o.resourceSpans.map(n=>{const u=g(n.resource.attributes.find(i=>i.key==="session_id"));return u?{...n,resource:{...n.resource,attributes:[...n.resource.attributes,...y(r,u)]},scopeSpans:n.scopeSpans.map(i=>({...i,spans:i.spans.map(a=>({...a,attributes:a.name.startsWith("event.")&&a.name!=="event.undefined"?A(a,r,u):a.attributes}))}))}:n})};return await fetch(p,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)}),e.newResponse(null,200,{})}function m(e){const o=e.get("auth")?.claims?.id||e.get("auth")?.claims?.sub,r=v(e.req.raw)||e.req.raw.context.remoteAddr?.hostname,s=e.req.raw.headers.get("user-agent"),n=e.req.raw.headers.get("accept-language"),u=n?.split(",")[0];return{userId:o,clientIp:r,userAgent:s||void 0,acceptLanguage:n||void 0,locale:u}}function y(e,o){const r=[t("redocly.organization.id",c.ORGANIZATION_ID),t("redocly.organization.slug",c.ORGANIZATION_SLUG),t("redocly.project.id",c.PROJECT_ID),t("redocly.project.slug",c.PROJECT_SLUG),t("redocly.product.type",d.toLowerCase()),t("redocly.client.ip",e.clientIp),t("redocly.client.userAgent",e.userAgent),t("redocly.client.acceptLanguage",e.acceptLanguage),t("redocly.client.locale",e.locale)];return e.userId?r.push(t("redocly.user.id",e.userId)):r.push(t("redocly.anonymous.id",l(o))),r.filter(s=>s!==void 0)}function f(e,o,r){const s=b(e.userId,o),n=new Date(Math.floor(Number(r.startTimeUnixNano)/1e6)).toISOString(),u=r.attributes.find(_=>_.key==="cloudevents.event_data.uri"),i=u&&"stringValue"in u.value?[t("cloudevents.event_data.page.uri",u.value.stringValue)]:[];return[t("cloudevents.event_spec_version","1.0"),t("cloudevents.event_object","event"),t("cloudevents.event_origin","realm-ui"),t("cloudevents.event_source",s.uri),t("cloudevents.event_source_details.id",s.id),t("cloudevents.event_source_details.object",s.object),t("cloudevents.event_source_details.uri",s.uri),t("cloudevents.event_data_content_type","application/json; charset=utf-8"),t("cloudevents.event_organization_id",c.ORGANIZATION_ID),t("cloudevents.event_organization_slug",c.ORGANIZATION_SLUG),t("cloudevents.event_project_id",c.PROJECT_ID),t("cloudevents.event_project_slug",c.PROJECT_SLUG),t("cloudevents.event_product_type",d.toLowerCase()),t("cloudevents.event_session_id",o),t("cloudevents.event_time",n),t("cloudevents.event_client.ip",e.clientIp),t("cloudevents.event_client.user_agent",e.userAgent),t("cloudevents.event_client.accept_language",e.acceptLanguage),t("cloudevents.event_client.locale",e.locale),...i]}function A(e,o,r){return[...e.attributes.filter(n=>{const u="stringValue"in n.value&&n.value.stringValue==="",i=/cloudevents\.event_source_details\..+/.test(n.key);return!(u||i)}),...f(o,r,e)].filter(n=>n!==void 0)}function b(e,o){return e?{id:e,object:"user",uri:`${c.MAIN_API_URL}/users/${e}`}:{id:l(o),object:"anonymous",uri:`${c.MAIN_API_URL}/anonymous/${l(o)}`}}function l(e){return e.replace("ses_","ann_")}export{T as otelTracesHandler,A as toCloudEventAttributes,b as toSource};
1
+ import{envConfig as c}from"../../../config/env-config.js";import{getClientIp as v}from"../../utils/get-client-ip.js";import{toAttribute as t,getAttributesStringValue as _}from"./otlp.js";const g=c.OTEL_TRACES_URL||"https://otel.cloud.redocly.com/v1/traces";async function h(e){const s=await e.req.json(),u=m(e),o={resourceSpans:s.resourceSpans.map(n=>{const r=_(n.resource.attributes.find(i=>i.key==="session_id"));return r?{...n,resource:{...n.resource,attributes:[...n.resource.attributes]},scopeSpans:n.scopeSpans.map(i=>({...i,spans:i.spans.map(a=>({...a,attributes:a.name.startsWith("event.")&&a.name!=="event.undefined"?b(a,u,r):a.attributes}))}))}:n})};return await fetch(g,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)}),e.newResponse(null,200,{})}function m(e){const s=e.get("auth")?.claims?.id||e.get("auth")?.claims?.sub,u=v(e.req.raw)||e.req.raw.context.remoteAddr?.hostname,o=e.req.raw.headers.get("user-agent"),n=e.req.raw.headers.get("accept-language"),r=n?.split(",")[0];return{userId:s,clientIp:u,userAgent:o||void 0,acceptLanguage:n||void 0,locale:r}}function p(e,s,u){const o=f(e.userId,s),n=new Date(Math.floor(Number(u.startTimeUnixNano)/1e6)).toISOString(),r=u.attributes.find(d=>d.key==="cloudevents.event_data.uri"),i=r&&"stringValue"in r.value?[t("cloudevents.event_data.page.uri",r.value.stringValue)]:[];return[t("cloudevents.event_spec_version","1.0"),t("cloudevents.event_object","event"),t("cloudevents.event_origin","realm-ui"),t("cloudevents.event_env",c.redoclyEnv),t("cloudevents.event_source",o.uri),t("cloudevents.event_source_details.id",o.id),t("cloudevents.event_source_details.object",o.object),t("cloudevents.event_source_details.uri",o.uri),t("cloudevents.event_actor.id",o.id),t("cloudevents.event_actor.object",o.object),t("cloudevents.event_actor.uri",o.uri),t("cloudevents.event_data_content_type","application/json; charset=utf-8"),t("cloudevents.event_organization_id",c.ORGANIZATION_ID),t("cloudevents.event_organization_slug",c.ORGANIZATION_SLUG),t("cloudevents.event_project_id",c.PROJECT_ID),t("cloudevents.event_project_slug",c.PROJECT_SLUG),t("cloudevents.event_session_id",s),t("cloudevents.event_time",n),t("cloudevents.event_client_ip",e.clientIp),t("cloudevents.event_user_agent",e.userAgent),...i]}function b(e,s,u){return[...e.attributes.filter(n=>{const r="stringValue"in n.value&&n.value.stringValue==="",i=/cloudevents\.event_source_details\..+/.test(n.key);return!(r||i)}),...p(s,u,e)].filter(n=>n!==void 0)}function f(e,s){return e?{id:e,object:"user",uri:`${c.MAIN_API_URL}/users/${e}`}:{id:l(s),object:"anonymous",uri:`${c.MAIN_API_URL}/anonymous/${l(s)}`}}function l(e){return e.replace("ses_","ann_")}export{h as otelTracesHandler,b as toCloudEventAttributes,f as toSource};
@@ -1 +1 @@
1
- import{setCookie as A}from"hono/cookie";import{withPathPrefix as f}from"@redocly/theme/core/utils";import{DEV_LOGIN_SLUG as E}from"../../constants/common.js";import{CACHE_CONTROL_NO_CACHE_HEADER_VALUE as b}from"../constants/common.js";import{getAuthProviderLoginParams as w,buildLoginUrl as C}from"./auth.js";import{renderPage as y}from"../ssr/index.js";import{telemetry as _}from"../../cli/telemetry/index.js";async function F(r,t,n,o){const{isAuthenticated:i}=r.get("auth"),e=r.req.raw.headers.get("x-forwarded-host"),a=e?"https://"+e:new URL(r.req.url).origin,c=t.getConfig().ssoDirect,u=Object.keys(c||{}),s=o||u[0],m=c?.[s];if(i)return v(r,t,{slug:n},403);const d=s&&m?await w(s,m):void 0,g=d?{...d,extraParams:{...d.extraParams,prompt:"login"}}:void 0,{loginUrl:P,cookies:h={}}=g&&C(g,a,n)||{},p=t.globalData.auth?.devLogin||u.length>1?z(n):P;return Object.keys(h).forEach(l=>{A(r,l,h[l].value,h[l].options)}),p?r.newResponse(null,302,{Location:p}):r.text("Unauthorized",401)}const L={};async function v(r,t,n,o,i){let e=L[o];if(!e){const a={templateId:String(i||o),fsPath:"/",...n,baseSlug:n.slug};e=(await y(a,{},r,t,_)).html,L[o]=e}return r.html(e,o,{"Cache-Control":b})}function z(r){const t=new URLSearchParams({redirectTo:f(r)});return`${f(E)}?${t}`}async function S(r){return r.text("Forbidden",U(r))}function T(r){return r.json({message:"Forbidden"},U(r))}function U(r){const{isAuthenticated:t}=r.get("auth");return t?403:401}function $(r){const t=r?.match(/(?:^|:)(\d{1,3}(?:\.\d{1,3}){3})$/);return t?t[1]:r}export{z as getLoginUrlWithRedirect,v as handleErrorPageRender,F as handleUnauthorized,T as handleUnauthorizedApiRequest,S as handleUnauthorizedAsset,$ as normalizeIpAddress};
1
+ import{setCookie as A}from"hono/cookie";import{withPathPrefix as f}from"@redocly/theme/core/utils";import{DEV_LOGIN_SLUG as E}from"../../constants/common.js";import{CACHE_CONTROL_NO_CACHE_HEADER_VALUE as b}from"../constants/common.js";import{getAuthProviderLoginParams as C,buildLoginUrl as y}from"./auth.js";import{renderPage as _}from"../ssr/index.js";import{telemetry as v}from"../../cli/telemetry/index.js";async function S(r,t,o,n){const{isAuthenticated:a}=r.get("auth"),e=r.req.raw.headers.get("x-forwarded-host"),i=r.req.raw.headers.get("x-forwarded-proto"),U=e?`${i==="http"||i==="https"?i:"https"}://${e}`:new URL(r.req.url).origin,l=t.getConfig().ssoDirect,u=Object.keys(l||{}),s=n||u[0],p=l?.[s];if(a)return z(r,t,{slug:o},403);const d=s&&p?await C(s,p):void 0,g=d?{...d,extraParams:{...d.extraParams,prompt:"login"}}:void 0,{loginUrl:w,cookies:h={}}=g&&y(g,U,o)||{},m=t.globalData.auth?.devLogin||u.length>1?H(o):w;return Object.keys(h).forEach(c=>{A(r,c,h[c].value,h[c].options)}),m?r.newResponse(null,302,{Location:m}):r.text("Unauthorized",401)}const L={};async function z(r,t,o,n,a){let e=L[n];if(!e){const i={templateId:String(a||n),fsPath:"/",...o,baseSlug:o.slug};e=(await _(i,{},r,t,v)).html,L[n]=e}return r.html(e,n,{"Cache-Control":b})}function H(r){const t=new URLSearchParams({redirectTo:f(r)});return`${f(E)}?${t}`}async function T(r){return r.text("Forbidden",P(r))}function k(r){return r.json({message:"Forbidden"},P(r))}function P(r){const{isAuthenticated:t}=r.get("auth");return t?403:401}function G(r){const t=r?.match(/(?:^|:)(\d{1,3}(?:\.\d{1,3}){3})$/);return t?t[1]:r}export{H as getLoginUrlWithRedirect,z as handleErrorPageRender,S as handleUnauthorized,k as handleUnauthorizedApiRequest,T as handleUnauthorizedAsset,G as normalizeIpAddress};
@@ -1,7 +1,7 @@
1
1
  import type { ApiRoutesWorkerParams, ApiRoutesWorkerResponse } from '../types/plugins/api-routes.js';
2
2
  import type { RenderPayload } from '../../types/ssr.js';
3
3
  import type { ScorecardsWorkerParams, ScorecardsWorkerResponse } from '../types/plugins/scorecards.js';
4
- import type { McpToolWorkerParams, McpToolWorkerResponse } from '../plugins/mcp/types.js';
4
+ import type { McpToolExecutionParams, McpToolWorkerResponse } from '../plugins/mcp/types.js';
5
5
  import type { SCORECARDS_WORKER_KEY } from './scorecards-worker-pool.js';
6
6
  import type { API_ROUTES_WORKER_KEY } from './api-routes-worker-pool.js';
7
7
  import type { SSR_WORKER_KEY } from './ssr-worker-pool.js';
@@ -25,7 +25,7 @@ export type WorkerTypeMapping = {
25
25
  response: ScorecardsWorkerResponse;
26
26
  };
27
27
  [MCP_TOOL_WORKER_KEY]: {
28
- params: [McpToolWorkerParams];
28
+ params: [McpToolExecutionParams];
29
29
  response: McpToolWorkerResponse;
30
30
  };
31
31
  };
@@ -1 +1 @@
1
- import s from"workerpool";import{envConfig as l}from"../config/env-config.js";import{fromCurrentDir as n}from"../utils/paths.js";class f{#t=null;#o;constructor(o){this.#o=o,this.#o.lazy||(this.#t=this.#i())}#i(){const{workerScript:o,lazy:e,...i}=this.#o;let t=o;return!t.endsWith(".js")&&!t.endsWith(".mjs")&&(t=n(import.meta.url,`${t}.${l.isDevelopMode?"js":"mjs"}`)),s.pool(t,{...i})}#r(){return this.#t||(this.#t=this.#i()),this.#t}async exec(o,e,i){let r=this.#r().exec(o,e);return i?.timeout&&(r=r.timeout(i.timeout)),await r}async terminate(){this.#t&&(await this.#t.terminate(),this.#t=null)}}export{f as WorkerPool};
1
+ import n from"workerpool";import{basename as a,dirname as s,resolve as l}from"node:path";import{fileURLToPath as h}from"node:url";import{envConfig as m}from"../config/env-config.js";class w{#t=null;#r;constructor(o){this.#r=o,this.#r.lazy||(this.#t=this.#o())}#o(){const{workerScript:o,lazy:t,...r}=this.#r;let e=this.#e(o);return n.pool(e,{...r})}#e(o){let t=o;if(!t.endsWith(".js")&&!t.endsWith(".mjs")&&(t=`${t}.${m.isDevelopMode?"js":"mjs"}`),!t.startsWith("."))return t;const r=s(h(import.meta.url)),e=a(r)==="chunks"?s(r):r;return l(e,t)}#i(){return this.#t||(this.#t=this.#o()),this.#t}async exec(o,t,r){let i=this.#i().exec(o,t);return r?.timeout&&(i=i.timeout(r.timeout)),await i}async terminate(){this.#t&&(await this.#t.terminate(),this.#t=null)}}export{w as WorkerPool};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@redocly/reef",
3
- "version": "0.132.0-next.6",
3
+ "version": "0.132.0-next.8",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "bin": {
@@ -91,14 +91,14 @@
91
91
  "xpath": "0.0.34",
92
92
  "yaml-ast-parser": "0.0.43",
93
93
  "zod": "^3.25.76",
94
- "@redocly/asyncapi-docs": "1.9.0-next.5",
95
- "@redocly/graphql-docs": "1.9.0-next.5",
96
- "@redocly/config": "0.46.0",
97
- "@redocly/openapi-docs": "3.20.0-next.5",
94
+ "@redocly/asyncapi-docs": "1.9.0-next.6",
95
+ "@redocly/config": "0.46.1",
96
+ "@redocly/graphql-docs": "1.9.0-next.6",
97
+ "@redocly/openapi-docs": "3.20.0-next.6",
98
98
  "@redocly/portal-legacy-ui": "0.15.0-next.0",
99
- "@redocly/portal-plugin-mock-server": "0.17.0-next.5",
100
- "@redocly/realm-asyncapi-sdk": "0.10.0-next.0",
101
- "@redocly/theme": "0.64.0-next.3"
99
+ "@redocly/portal-plugin-mock-server": "0.17.0-next.6",
100
+ "@redocly/realm-asyncapi-sdk": "0.10.0-next.1",
101
+ "@redocly/theme": "0.64.0-next.4"
102
102
  },
103
103
  "peerDependencies": {
104
104
  "react": "^19.2.4",
@@ -1,4 +0,0 @@
1
- export declare const cache: Record<string, string>;
2
- export declare function generateDiagramHash(diagram: string): string;
3
- export declare function renderMermaid(nodes: string[], theme?: string): Promise<string[]>;
4
- //# sourceMappingURL=render-mermaid.d.ts.map
@@ -1 +0,0 @@
1
- import{nanoid as R}from"nanoid";import{envConfig as i}from"../../../../config/env-config.js";import{logger as h}from"../../../../tools/notifiers/logger.js";import{sha as g}from"../../../../utils/crypto/sha.js";const s={};function c(t){if(t.toLowerCase().includes("gantt")&&!t.toLowerCase().includes("todaymarker off")){const o=new Date().toISOString().split("T")[0];return g(t+o)}return g(t)}async function O(t,d="default"){if(t.length===0)return[];const r=[];for(let e=0;e<t.length;e++){const n=c(t[e]);s[n]||r.push(t[e])}if(r.length){const e=i.REDOCLY_MERMAID_MICROSERVICE_URL||"https://api.redocly.com/mermaid",n=h.startTiming(),f=R(),m=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json","x-request-id":i.REQUEST_ID||""},body:JSON.stringify({definitions:r,rayId:f,theme:d,organizationId:i.ORGANIZATION_ID})});if(m.status!==200)throw new Error(`Something went wrong during remote rendering. Please, save this Ray ID: ${f} and contact Redocly team.`);h.verboseTime(n,"Rendered mermaid diagrams (%s)",r.length);const l=await m.json();for(let a=0;a<r.length;a++){const p=c(r[a]);s[p]=l[a]}}const o=[];for(let e=0;e<t.length;e++){const n=c(t[e]);o.push(s[n])}return o}export{s as cache,c as generateDiagramHash,O as renderMermaid};
@@ -1,55 +0,0 @@
1
- import type { JSONSchemaType } from '@redocly/ajv';
2
- import type { McpServer } from '@redocly/mcp-typescript-sdk/server/mcp.js';
3
- import type { OpenAPIDefinition } from '@redocly/openapi-docs';
4
- import type { AccessInfo, ApiDescriptionInfo, McpToolWorkerParams, McpToolWorkerResponse, ToolArgsMap } from '../../types.js';
5
- export type DocsMcpToolRegistrationOptions = {
6
- server: McpServer;
7
- baseUrl: string;
8
- outdir: string;
9
- apiDescriptionsMap: Record<string, ApiDescriptionInfo>;
10
- headers?: Record<string, string | string[] | undefined>;
11
- accessInfo: AccessInfo;
12
- products?: string[];
13
- };
14
- /** Keys that can be passed to the tool context (excludes 'server' which is not serializable) */
15
- export type ContextKey = Exclude<keyof DocsMcpToolRegistrationOptions, 'server'>;
16
- export type ApiDefinitionResult = {
17
- success: true;
18
- definition: OpenAPIDefinition;
19
- } | {
20
- success: false;
21
- response: McpToolWorkerResponse;
22
- };
23
- export declare abstract class DocsMcpTool<TName extends keyof ToolArgsMap> {
24
- abstract readonly name: TName;
25
- abstract readonly description: string;
26
- readonly schema: JSONSchemaType<ToolArgsMap[TName]>;
27
- /**
28
- * Array of context keys that this tool requires.
29
- * The base class will extract these from DocsMcpToolRegistrationOptions
30
- * and pass them to executeAction.
31
- */
32
- abstract readonly requiredContext: readonly ContextKey[];
33
- constructor(schema: JSONSchemaType<ToolArgsMap[TName]>);
34
- /**
35
- * Builds the context object by picking only the required keys from options.
36
- */
37
- protected getContext(options: DocsMcpToolRegistrationOptions): McpToolWorkerParams['context'];
38
- register(options: DocsMcpToolRegistrationOptions): void;
39
- /**
40
- * Wraps the tool execution with telemetry and error handling.
41
- * Subclasses should call this method and implement executeAction for the actual logic.
42
- */
43
- execute(args: ToolArgsMap[TName], context: McpToolWorkerParams['context']): Promise<McpToolWorkerResponse>;
44
- /**
45
- * Implement the actual tool logic here. Called by execute() which handles telemetry.
46
- */
47
- protected abstract executeAction(args: ToolArgsMap[TName], context: McpToolWorkerParams['context']): Promise<McpToolWorkerResponse>;
48
- /**
49
- * Helper method for tools that need to load an API definition.
50
- * Handles finding the API by name and loading the definition from the file system.
51
- * Requires 'outdir' and 'accessInfo' in requiredContext.
52
- */
53
- protected getApiDefinition(name: string, context: McpToolWorkerParams['context']): Promise<ApiDefinitionResult>;
54
- }
55
- //# sourceMappingURL=docs-mcp-tool.d.ts.map
@@ -1 +0,0 @@
1
- import{telemetry as o}from"../../../../telemetry/index.js";import{mcpToolWorkers as n,MCP_TOOL_WORKER_KEY as a}from"../../../../workers/mcp-tool-worker-pool.js";import{findApiDescriptionByName as p}from"../utils.js";import{getApiDescriptionFromFs as m}from"./utils.js";function u(i,t,s){return{toolName:i,args:t,context:s}}class g{schema;constructor(t){this.schema=t}getContext(t){const s={};for(const e of this.requiredContext)s[e]=t[e];return{...s,apiDescriptionsMap:t.apiDescriptionsMap}}register(t){const s=async(e,r)=>{const c=u(this.name,e,this.getContext(t));return await n.exec(a,[c],{timeout:6e4})};t.server.tool(this.name,this.description,this.schema,s)}async execute(t,s){try{const e=await this.executeAction(t,s);return e.isError?o.sendMcpErrorMessage([{object:"mcp_server",server_type:"docs",tool:this.name,message:`${e.content.map(({text:r})=>r).join(" ")}`,stack:""}]):o.sendMcpToolCalledMessage([{object:"mcp_server",server_type:"docs",tool:this.name}]),e}catch(e){throw o.sendMcpErrorMessage([{object:"mcp_server",server_type:"docs",tool:this.name,message:e instanceof Error?e.message:String(e),stack:e instanceof Error&&e.stack||""}]),e}}async getApiDefinition(t,s){if(!s.outdir||!s.accessInfo)throw new Error("Missing required context: outdir and accessInfo");const e=p(s.apiDescriptionsMap,t);if(!e)return{success:!1,response:{content:[{type:"text",text:`No API found matching "${t}".`}]}};const r=await m({relativePath:e.relativePath||"",outdir:s.outdir,accessInfo:s.accessInfo});return r?{success:!0,definition:r}:{success:!1,response:{content:[{type:"text",text:`Spec not found from the file system with "${t}".`}]}}}}export{g as DocsMcpTool};
@@ -1,11 +0,0 @@
1
- import type { ApiFunctionsContext, ApiRoutesHandler, PageStaticData } from '@redocly/config';
2
- import type { McpServerInstance, McpServerType } from '../types.js';
3
- export type McpRequestHandlerDependencies = {
4
- createServerInstance: (context: ApiFunctionsContext, staticData: PageStaticData, headers: Record<string, string | string[] | undefined>, request: Request) => Promise<McpServerInstance>;
5
- serverType: McpServerType;
6
- };
7
- /**
8
- * Creates a standardized MCP request handler
9
- */
10
- export declare function createMcpRequestHandler(dependencies: McpRequestHandlerDependencies): ApiRoutesHandler;
11
- //# sourceMappingURL=mcp-request-handler.d.ts.map
@@ -1 +0,0 @@
1
- import{toFetchResponse as p,toReqRes as h}from"fetch-to-node";import{createMethodNotAllowedError as w,withErrorHandling as y}from"./errors.js";function m(s){const{createServerInstance:a,serverType:c}=s;return async(e,d,i)=>{let r;return y(async()=>{const n={};e.headers.forEach((t,l)=>{n[l]=t});const{req:u,res:o}=h(e);switch(e.method){case"GET":return new Response(JSON.stringify({error:"Method Not Allowed",message:`In order to use this MCP server, you need register it in your MCP Client (VS Code, Cursor, Claude Code, etc.) using that URL: ${e.url}`}),{status:405,headers:{"Content-Type":"application/json"}});case"POST":{r=await a(d,i,n,e);const t=await e.json();return await r.transport.handleRequest(u,o,t),p(o)}default:return w()}},c,async()=>{r&&(await r.cleanup(),r=void 0)})}}export{m as createMcpRequestHandler};
@@ -1,17 +0,0 @@
1
- import { McpServer } from '@redocly/mcp-typescript-sdk/server/mcp.js';
2
- import { StreamableHTTPServerTransport } from '@redocly/mcp-typescript-sdk/server/streamableHttp.js';
3
- import type { Implementation } from '@redocly/mcp-typescript-sdk/types.js';
4
- import type { McpServerInstance, McpServerType } from '../types.js';
5
- export declare abstract class BaseMcpServer {
6
- #private;
7
- protected server: McpServer;
8
- protected transport: StreamableHTTPServerTransport;
9
- constructor(config: Implementation);
10
- protected abstract registerTools(): void;
11
- initialize(): Promise<McpServerInstance>;
12
- clearCleanupTimeout(): void;
13
- cleanup(): Promise<void>;
14
- protected abstract getServerType(): McpServerType;
15
- }
16
- export declare function createMcpServerInstance<T extends BaseMcpServer>(serverClass: new (...args: any[]) => T, ...args: any[]): Promise<McpServerInstance>;
17
- //# sourceMappingURL=base-server.d.ts.map
@@ -1 +0,0 @@
1
- import{McpServer as t}from"@redocly/mcp-typescript-sdk/server/mcp.js";import{StreamableHTTPServerTransport as s}from"@redocly/mcp-typescript-sdk/server/streamableHttp.js";import{telemetry as i}from"../../../telemetry/index.js";class p{server;transport;#r;#t=!1;constructor(e){this.server=new t(e,{capabilities:{logging:{}}}),this.transport=new s({sessionIdGenerator:void 0})}async initialize(){return this.registerTools(),await this.server.connect(this.transport),{server:this.server,transport:this.transport,cleanup:this.cleanup.bind(this)}}clearCleanupTimeout(){this.#r&&(clearTimeout(this.#r),this.#r=void 0)}#e;async cleanup(){return this.#e?this.#e:(this.#e=this.#s(),this.#e)}async#s(){if(!this.#t){this.#t=!0,this.clearCleanupTimeout();try{this.transport.close()}catch(e){throw i.sendMcpErrorMessage([{object:"mcp_server",server_type:this.getServerType(),message:e?.message||"Unknown cleanup error",stack:e?.stack||""}]),e}}}}async function h(r,...e){return await new r(...e).initialize()}export{p as BaseMcpServer,h as createMcpServerInstance};