@redocly/redoc-reef 0.141.0-next.16 → 0.141.0-next.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,16 @@
1
1
  # @redocly/redoc-reef
2
2
 
3
+ ## 0.141.0-next.17
4
+
5
+ ### Patch Changes
6
+
7
+ - 59db66ede59: Hardened authorization request handling.
8
+ - eebd6fbddea: Fixed an issue where pages crash with the error “Failed to execute ‘removeChild’ on ‘Node’”.
9
+ - Updated dependencies [8e0ced8aef0]
10
+ - Updated dependencies [eebd6fbddea]
11
+ - @redocly/api-docs@0.6.0-next.17
12
+ - @redocly/theme@0.73.0-next.13
13
+
3
14
  ## 0.141.0-next.16
4
15
 
5
16
  ### Minor Changes
@@ -1 +1 @@
1
- import{logger as t}from"../server/tools/notifiers/logger.js";import{reporter as c}from"../server/tools/notifiers/reporter.js";import{green as w}from"../server/tools/notifiers/helpers/colors.js";import{envConfig as m}from"../server/config/env-config.js";import{resolveCache as R}from"../server/esbuild/plugins/themes-resolver.js";import{getBilledPagesCount as p}from"../server/utils/index.js";import{createClientCompiler as C,createServerCompiler as S}from"../server/esbuild/esbuild.js";import{initPlugins as h,runPlugins as f,writeClientEntries as E}from"../server/plugins/lifecycle.js";import{startDevServer as P}from"../server/web-server/dev-server.js";import{validateAllMarkdowns as g}from"../server/plugins/markdown/compiler.js";import{reportAllErrors as v}from"../server/utils/report-all-errors.js";import{validateAllowedPackages as y}from"../server/utils/validate-allowed-packages.js";import{copyMigrationsFolder as L}from"../server/providers/database/copy-migrations.js";import{listenStdin as T}from"./utils/listen-stdin.js";import{createReactPagesCheck as k}from"./utils/react-pages-check.js";const D=20;async function Y(i,e){t.info("Starting project preview mode."),e.devLogin=i["dev-login"]!==!1,E(e),t.startTiming("initial-js"),await A(e),t.infoTime("initial-js","JavaScript compiled");const{pluginInstances:o,lifecycleContext:n}=await h({contentDir:e.contentDir,outdir:e.outdir,serverOutDir:void 0,devLogin:e.devLogin,setGlobalConfig:e.setGlobalConfig});e.lifecycleContext=n,L(e),await f(o,e,n,{failFast:!0});const d=k(e,n),u=async a=>{const s=performance.now();c.clearErrors(),await y(),d.invalidate(),await f(o,e,n),m.REDOCLY_EXP_DISABLE_MD_VALIDATION?t.info("Skipping markdown validation step"):await g(e,n),a.some(({event:l})=>l==="code-updated")&&d.run(),O().then(async()=>{await v(n);const l=p(e.getAllRoutes()),b=c.summary(` \u{1F440} Last change processed in ${w(Math.round(performance.now()-s)+"ms")}`,l);e.runListeners("errors-updated",void 0,b),e.runListeners("pages-updated",void 0,l),e.runListeners("routes-updated")})};m.REDOCLY_EXP_DISABLE_MD_VALIDATION?t.info("Skipping markdown validation step"):await g(e,n),await v(n);const r=p(e.getAllRoutes());c.summary(" \u{1F440} Watching for changes...",r),e.runListeners("pages-updated",void 0,r),n.fs.watch(async a=>{R.clear(),await u(a)}),t.verbose("Starting development server."),await P(e,n,{port:Number(i.port||4e3),maxPortRetries:m.isReunite?0:D}),d.run(),T()}async function A(i){let e=!0,o=!0;const n=async r=>{r==="client"?e=!0:o=!0,i.runListeners("build-started");const a=e!=o;a&&i.startEsbuildRun(),i.buildRevision>0&&await i.waitForPluginsRun(),r!=="client"&&i.noteRequestHandlersEntryBuildStart(),a&&t.startTiming("rebuild")},d=async r=>{r==="client"?e=!1:(o=!1,i.markRequestHandlersEntryUpdated()),!(e||o)&&(i.finishEsbuildRun(),i.buildRevision++,t.infoTime("rebuild","JavaScript re-compiled"),await i.reloadMarkdocOptions(),i.markUserCodeReady(),i.runListeners("build-updated"),i.lifecycleContext&&i.buildRevision>1&&i.lifecycleContext.fs.emitCodeUpdated())},u=[new Promise((r,a)=>{const s={label:"client",buildStart(){t.verbose("Start compiling client code."),t.startTiming(this.label)},buildEnd(){t.verboseTime(this.label,"Client compiled"),r(!0)},rebuildStart:()=>n("client"),rebuildEnd:()=>d("client")};C(i,i.outdir,"development",s).then(l=>l.watch()).catch(a)}),new Promise((r,a)=>{const s={label:"server",buildStart(){t.verbose("Start compiling server code."),t.startTiming(this.label)},buildEnd(){t.verboseTime(this.label,"Server compiled"),r(!0)},rebuildStart:()=>n("server"),rebuildEnd:()=>d("server")};S(i,i.serverOutDir,"development",s).then(l=>l.watch()).catch(a)})];await Promise.all(u),await i.reloadMarkdocOptions()}function O(){return new Promise(i=>{setTimeout(i,0)})}export{Y as develop};
1
+ import{logger as t}from"../server/tools/notifiers/logger.js";import{reporter as c}from"../server/tools/notifiers/reporter.js";import{green as w}from"../server/tools/notifiers/helpers/colors.js";import{envConfig as m}from"../server/config/env-config.js";import{resolveCache as R}from"../server/esbuild/plugins/themes-resolver.js";import{getBilledPagesCount as p}from"../server/utils/index.js";import{createClientCompiler as C,createServerCompiler as S}from"../server/esbuild/esbuild.js";import{writeServerRebuildTrigger as h}from"../server/esbuild/generate.js";import{initPlugins as E,runPlugins as f,writeClientEntries as P}from"../server/plugins/lifecycle.js";import{startDevServer as y}from"../server/web-server/dev-server.js";import{validateAllMarkdowns as g}from"../server/plugins/markdown/compiler.js";import{reportAllErrors as v}from"../server/utils/report-all-errors.js";import{validateAllowedPackages as L}from"../server/utils/validate-allowed-packages.js";import{copyMigrationsFolder as T}from"../server/providers/database/copy-migrations.js";import{listenStdin as D}from"./utils/listen-stdin.js";import{createReactPagesCheck as k}from"./utils/react-pages-check.js";const A=20;async function $(i,e){t.info("Starting project preview mode."),e.devLogin=i["dev-login"]!==!1,P(e),t.startTiming("initial-js"),await O(e),t.infoTime("initial-js","JavaScript compiled");const{pluginInstances:o,lifecycleContext:n}=await E({contentDir:e.contentDir,outdir:e.outdir,serverOutDir:void 0,devLogin:e.devLogin,setGlobalConfig:e.setGlobalConfig});e.lifecycleContext=n,T(e),await f(o,e,n,{failFast:!0});const d=k(e,n),u=async a=>{const s=performance.now();c.clearErrors(),await L(),d.invalidate(),await f(o,e,n),m.REDOCLY_EXP_DISABLE_MD_VALIDATION?t.info("Skipping markdown validation step"):await g(e,n),a.some(({event:l})=>l==="code-updated")&&d.run(),_().then(async()=>{await v(n);const l=p(e.getAllRoutes()),b=c.summary(` \u{1F440} Last change processed in ${w(Math.round(performance.now()-s)+"ms")}`,l);e.runListeners("errors-updated",void 0,b),e.runListeners("pages-updated",void 0,l),e.runListeners("routes-updated")})};m.REDOCLY_EXP_DISABLE_MD_VALIDATION?t.info("Skipping markdown validation step"):await g(e,n),await v(n);const r=p(e.getAllRoutes());c.summary(" \u{1F440} Watching for changes...",r),e.runListeners("pages-updated",void 0,r),n.fs.watch(async a=>{R.clear(),await u(a)}),t.verbose("Starting development server."),await y(e,n,{port:Number(i.port||4e3),maxPortRetries:m.isReunite?0:A}),d.run(),D()}async function O(i){let e=!0,o=!0;const n=async r=>{r==="client"?e=!0:o=!0,i.runListeners("build-started");const a=e!=o;a&&i.startEsbuildRun(),i.buildRevision>0&&await i.waitForPluginsRun(),r!=="client"&&i.noteRequestHandlersEntryBuildStart(),a&&t.startTiming("rebuild")},d=async r=>{r==="client"?e=!1:(o=!1,i.markRequestHandlersEntryUpdated()||h(i.serverOutDir)),!(e||o)&&(i.finishEsbuildRun(),i.buildRevision++,t.infoTime("rebuild","JavaScript re-compiled"),await i.reloadMarkdocOptions(),i.markUserCodeReady(),i.runListeners("build-updated"),i.lifecycleContext&&i.buildRevision>1&&i.lifecycleContext.fs.emitCodeUpdated())},u=[new Promise((r,a)=>{const s={label:"client",buildStart(){t.verbose("Start compiling client code."),t.startTiming(this.label)},buildEnd(){t.verboseTime(this.label,"Client compiled"),r(!0)},rebuildStart:()=>n("client"),rebuildEnd:()=>d("client")};C(i,i.outdir,"development",s).then(l=>l.watch()).catch(a)}),new Promise((r,a)=>{const s={label:"server",buildStart(){t.verbose("Start compiling server code."),t.startTiming(this.label)},buildEnd(){t.verboseTime(this.label,"Server compiled"),r(!0)},rebuildStart:()=>n("server"),rebuildEnd:()=>d("server")};S(i,i.serverOutDir,"development",s).then(l=>l.watch()).catch(a)})];await Promise.all(u),await i.reloadMarkdocOptions()}function _(){return new Promise(i=>{setTimeout(i,0)})}export{$ as develop};
@@ -1 +1 @@
1
- import*as e from"react";import{MarkdownAdapterProvider as l,RedocExample as u,StoreProvider as E,findExampleEncoding as f,markdocParser as k}from"@redocly/api-docs";import{ErrorMessage as x,OpenApiComponentWrap as A}from"../styled.elements";import{useStore as P}from"../../hooks/use-store";import{usePortalMarkdownAdapter as g}from"./use-markdown-adapter";function y(n){const{descriptionFile:i,pointer:o,options:p,mimeType:a}=n,{store:r,error:m,restricted:s}=P(i),d=g(),t=r?.items,c=e.useMemo(()=>t?f(t,o):void 0,[t,o]);return r?e.createElement(A,{"data-testid":"openapi-example"},e.createElement(E,{options:{...r.options,...p,markdownParser:k},apiStore:r.store},e.createElement(l,{value:d},e.createElement(u,{pointer:o,mimeType:a||"application/json",encoding:c})))):s?null:e.createElement(x,null,m)}export{y as OpenApiExample};
1
+ import*as e from"react";import{MarkdownAdapterProvider as l,RedocExample as u,StoreProvider as f,findExampleContent as E,markdocParser as k}from"@redocly/api-docs";import{ErrorMessage as x,OpenApiComponentWrap as A}from"../styled.elements";import{useStore as P}from"../../hooks/use-store";import{usePortalMarkdownAdapter as w}from"./use-markdown-adapter";function C(n){const{descriptionFile:p,pointer:r,options:a,mimeType:i}=n,{store:t,error:m,restricted:s}=P(p),c=w(),o=t?.items,d=e.useMemo(()=>o?E(o,r):void 0,[o,r]);return t?e.createElement(A,{"data-testid":"openapi-example"},e.createElement(f,{options:{...t.options,...a,markdownParser:k},apiStore:t.store},e.createElement(l,{value:c},e.createElement(u,{pointer:r,mimeType:i||"application/json",content:d})))):s?null:e.createElement(x,null,m)}export{C as OpenApiExample};
@@ -20,8 +20,8 @@ export declare function getApiDescriptionFromFs({ relativePath, outdir, ...acces
20
20
  /** The bundled description with no RBAC filtering; never return it to a caller. */
21
21
  export declare function readApiDescriptionFromFs(relativePath: string, outdir: string): Promise<OpenAPIDefinition | undefined>;
22
22
  /**
23
- * A filtered copy of `definition` holding only what the user can read, or undefined when the user
24
- * can read none of it; the input is not mutated.
23
+ * `definition` filtered to what the user can read, or undefined when the user can read none of it.
24
+ * The input is not mutated, and is returned itself when nothing is hidden.
25
25
  */
26
26
  export declare function filterApiDescriptionByAccess(definition: OpenAPIDefinition, { user, rbac, requiresLogin }: ApiDescriptionAccess): OpenAPIDefinition | undefined;
27
27
  export declare function absolutePath(requestedPath: string): string;
@@ -1 +1 @@
1
- import{withPathPrefix as O}from"@redocly/theme/core/utils";import{SSR_RENDER_MODE as y}from"../constants/common.js";import{logger as b}from"../tools/notifiers/logger.js";import{canAccessResource as L,filterDataByAccessDeep as d,isResourcePubliclyAccessible as _}from"../utils/rbac.js";import{readSharedData as x}from"../utils/index.js";import{render as C}from"./render.js";import{getServerProps as T}from"./server-side-props/get-server-props.js";import{ssrWorkers as $,SSR_WORKER_KEY as j}from"../workers/ssr-worker-pool.js";async function G(e,s,a,r,o,c=!1){const w=b.startTiming(),E=r.routesSharedData.get(e.slug)||{},S=s.sharedDataIds||{},m={...E,...S},{isAuthenticated:g,teams:u,claims:{name:q,picture:I,email:f}}=a?.get("auth")||{claims:{}},t={isAuthenticated:g,email:f,teams:u},R=Object.fromEntries(await Promise.all(Object.entries(m).map(async([H,D])=>[D,await x(D,r.outdir)]))),P=d(R,t,r.config.access?.rbac,r.config.access?.requiresLogin),v=d(r.globalData,t,r.config.access?.rbac,r.config.access?.requiresLogin),p=L(e,t,r.config.access?.rbac,r.config.access?.requiresLogin),A=!!r.compilationErrors?.length?{templateId:"compilation-error",props:{compilationErrors:r.compilationErrors},sharedDataIds:{}}:null,h={page:{templateId:e.templateId,isPublic:_(e,r.config),slug:O(e.slug),versions:d(e.versions,t,r.config.access?.rbac,r.config.access?.requiresLogin),props:s,sharedDataIds:p?m:{},product:e.product,request:{search:a?.req.raw.context.url?.search||"",url:a?.req.raw.context.url?.href||""},userInfo:{isAuthenticated:g,name:q,picture:I,email:f,teams:u},...A},store:{globalData:v,config:r.config,ssr:r.ssr,hasSitemap:r.hasSitemap},sharedData:p?P:{},serverOutDir:r.serverOutDir,outdir:r.outdir,ssrHref:k(a),userAgent:a?.req.raw.headers.get("user-agent")||"",telemetry:o,omitSuspense:c};let i,n,l;return y==="worker"?{html:i,statusCode:n,error:l}=await $.exec(j,[h]):{html:i,statusCode:n,error:l}=await C(h),b.verboseTime(w,`Page rendered ${e.slug}`),{html:i,props:s,statusCode:n,error:l}}function k(e){const s=e?.req.raw.url;if(!s)return"";const a=new URL(s),r=e?.req.raw.headers,o=r?.get("x-forwarded-proto")||a.protocol.replace(":",""),c=r?.get("x-forwarded-host")||a.host;return`${o}://${c}`}export{T as getServerProps,G as renderPage};
1
+ import{withPathPrefix as y}from"@redocly/theme/core/utils";import{SSR_RENDER_MODE as _}from"../constants/common.js";import{logger as S}from"../tools/notifiers/logger.js";import{canAccessResource as b,filterDataByAccessDeep as g,isResourcePubliclyAccessible as x}from"../utils/rbac.js";import{readSharedData as C}from"../utils/index.js";import{render as T}from"./render.js";import{getServerProps as $}from"./server-side-props/get-server-props.js";import{ssrWorkers as j,SSR_WORKER_KEY as k}from"../workers/ssr-worker-pool.js";async function J(r,s,a,e,o,i=!1){const w=S.startTiming(),E=e.routesSharedData.get(r.slug)||{},R=s.sharedDataIds||{},u={...E,...R},{isAuthenticated:m,teams:f,claims:{name:q,picture:I,email:h}}=a?.get("auth")||{claims:{}},t={isAuthenticated:m,email:h,teams:f},p=b(r,t,e.config.access?.rbac,e.config.access?.requiresLogin),P=p&&b({},t,e.config.access?.rbac,e.config.access?.requiresLogin)?await Promise.all(Object.values(u).map(async c=>{const O=g(await C(c,e.outdir),t,e.config.access?.rbac,e.config.access?.requiresLogin);return[c,O]})):[],v=Object.fromEntries(P.filter(([,c])=>c!==void 0)),A=g(e.globalData,t,e.config.access?.rbac,e.config.access?.requiresLogin),L=!!e.compilationErrors?.length?{templateId:"compilation-error",props:{compilationErrors:e.compilationErrors},sharedDataIds:{}}:null,D={page:{templateId:r.templateId,isPublic:x(r,e.config),slug:y(r.slug),versions:g(r.versions,t,e.config.access?.rbac,e.config.access?.requiresLogin),props:s,sharedDataIds:p?u:{},product:r.product,request:{search:a?.req.raw.context.url?.search||"",url:a?.req.raw.context.url?.href||""},userInfo:{isAuthenticated:m,name:q,picture:I,email:h,teams:f},...L},store:{globalData:A,config:e.config,ssr:e.ssr,hasSitemap:e.hasSitemap},sharedData:v,serverOutDir:e.serverOutDir,outdir:e.outdir,ssrHref:B(a),userAgent:a?.req.raw.headers.get("user-agent")||"",telemetry:o,omitSuspense:i};let n,l,d;return _==="worker"?{html:n,statusCode:l,error:d}=await j.exec(k,[D]):{html:n,statusCode:l,error:d}=await T(D),S.verboseTime(w,`Page rendered ${r.slug}`),{html:n,props:s,statusCode:l,error:d}}function B(r){const s=r?.req.raw.url;if(!s)return"";const a=new URL(s),e=r?.req.raw.headers,o=e?.get("x-forwarded-proto")||a.protocol.replace(":",""),i=e?.get("x-forwarded-host")||a.host;return`${o}://${i}`}export{$ as getServerProps,J as renderPage};
@@ -84,7 +84,8 @@ export declare class Store {
84
84
  finishEsbuildRun(): void;
85
85
  markRequestHandlersEntryOutdated(): void;
86
86
  noteRequestHandlersEntryBuildStart(): void;
87
- markRequestHandlersEntryUpdated(): void;
87
+ /** Returns false when the handlers changed after the server build started, so one more build is needed. */
88
+ markRequestHandlersEntryUpdated(): boolean;
88
89
  get contentDir(): string;
89
90
  markUserCodeReady(): void;
90
91
  reloadMarkdocOptions(): Promise<void>;
@@ -1 +1 @@
1
- import T from"@redocly/markdoc";import{writeFileSync as w}from"node:fs";import{readFile as R}from"node:fs/promises";import{join as g}from"node:path";import{parseAndResolveMarkdoc as M}from"./plugins/markdown/compiler.js";import{getPathnameForLocale as k}from"@redocly/theme/core/utils";import{DEFAULT_LOCALE_PLACEHOLDER as m}from"../constants/common.js";import{DEFAULT_TITLE as F,MARKDOC_PARTIALS_DATA_KEY as y,MARKDOC_PARTIALS_DEPS_KEY as L}from"./constants/common.js";import{isObject as H}from"../utils/guards/is-object.js";import{mapObject as N}from"../utils/object/map-object.js";import{getValueDeep as S}from"../utils/object/get-value-deep.js";import{removeTrailingSlash as G}from"../utils/url/remove-trailing-slash.js";import{normalizeRouteSlug as d}from"../utils/path/normalize-route-slug.js";import{isLocalLink as v}from"../utils/path/is-local-link.js";import{reporter as E}from"./tools/notifiers/reporter.js";import{logger as u}from"./tools/notifiers/logger.js";import{sha1 as _}from"./utils/crypto/sha1.js";import{FileNotFoundError as B}from"./utils/fs.js";import{resolveAssetPath as I}from"./utils/resolve-asset-path.js";import{envConfig as j,setEnv as V}from"./config/env-config.js";import{KvService as q}from"./persistence/kv/services/kv-service.js";import{SandboxContext as J}from"./utils/sandbox-context.js";import{isAllowedEnv as U}from"./utils/envs/get-api-route-allowed-env-variables.js";import{ensureDir as x,writeSharedData as K}from"./utils/index.js";import{renderComponents as $}from"./ssr/render.js";import{readStaticData as W,writeStaticData as z}from"./utils/static-data.js";import{getMarkdocOptions as Y}from"./plugins/markdown/markdoc/markdoc-options.js";import{EntitlementsProvider as Z}from"./entitlements/entitlements-provider.js";import{getPlanDeniedMarkdocTags as Q}from"./entitlements/plan-denied-markdoc-tags.js";import{isRouteReserved as X}from"./plugins/get-reserved-routes.js";import{isL10nPath as ee}from"./fs/utils/is-l10n-path.js";import{resolveGlobMapValue as te}from"./utils/globs.js";import{createDefaultStoreConfig as se,resolveConfigEntries as re,resolveStoreConfig as oe}from"./store-config.js";import{findRedirect as ae}from"./utils/redirects/find-redirect.js";import{followRedirectChain as ie}from"./utils/redirects/follow-redirect-chain.js";import{addWildcardRedirectToTree as ne}from"./utils/redirects/add-wildcard-redirect-to-tree.js";import{telemetryTraceStep as le}from"../cli/telemetry/helpers/trace-step.js";const P={routesBySlug:"map",staticFilePaths:"object",apiRoutes:"object",middleware:"object",routesByFsPath:"map",routesSharedData:"map",globalData:"object",ssr:"object",searchFacets:"map",routesPartials:"map",mcpToolHandlers:"map",skills:"map",devLogin:"object"},C="store.json",A="store-config.json",b="PLAN_GATES",ce=["OAUTH_CLIENT_ID","OAUTH_CLIENT_SECRET","ORGANIZATION_SLUG","ORGANIZATION_ID","ORG_ID"],We="userDefinedApiFunctions";class D{routesBySlug=new Map;routeAliases=new Map;staticFilePaths={};replacedEnvVars={};unsetEnvVars=new Set;lifecycleContext;newRoutes=[];#t={};routesByFsPath=new Map;apiRoutes=[];middleware=[];routesSharedData=new Map;sharedDataDeps=new Map;sharedDataMarkdocComponents=new Map;routesDynamicComponents=new Map;routesPartials=new Map;ssr={preBodyTags:[],postBodyTags:[],headTags:[]};searchFacets=new Map;searchEngine;templates=new Map;browserPlugins=new Set;apiRoutesRequestHandlers=new Map;mcpToolHandlers=new Map;skills=new Map;serverPropsGetters=new Map;pagePropsGetters=new Map;listeners=new Map;globalData={};devLogin=!1;#a=void 0;#i={};config=se();configFile;#n;serverMode;serverOutDir;outdir;buildRevision=0;hasSitemap=!1;compilationErrors=[];#l;userCodeReady;#s=Promise.resolve();#c;#d=Promise.resolve();#h;#u=Promise.resolve();#f;#e=!1;#r=0;#p=0;#o=new Map;constructor({outdir:e,contentDir:t,serverMode:s=!1,serverOutDir:r}){this.#n=t,this.outdir=e,this.serverMode=s,this.serverOutDir=r,J.register({serverOutDir:r,readRoots:[e,process.cwd()]}),this.userCodeReady=new Promise(o=>{this.#l=o})}on(e,t){const s=this.listeners.get(e);s?s.add(t):this.listeners.set(e,new Set([t]))}queueEvent=(e,t,...s)=>{this.#o.set(e+String(t),[e,t,...s])};runListeners=(e,t,...s)=>{for(const r of this.listeners.get(e)||new Set)t?r(t,...s):r(...s)};startPluginsRun(){this.clear(),this.#s=new Promise(e=>{this.#c=e})}waitForPluginsLifecycle(){return Promise.all([this.#s,this.#d,this.#u])}waitForPluginsRun(){return this.#s}finishPluginsRun(){this.#c?.();for(const e of this.#o.values())this.runListeners(...e);this.#o.clear()}startEsbuildRun(){this.#d=new Promise(e=>{this.#h=e})}finishEsbuildRun(){this.#h?.()}markRequestHandlersEntryOutdated(){this.#r++,!this.#e&&(this.#e=!0,this.#u=new Promise(e=>{this.#f=e}))}noteRequestHandlersEntryBuildStart(){this.#p=this.#r}markRequestHandlersEntryUpdated(){this.#e&&(this.#r>this.#p||(this.#e=!1,this.#f?.()))}get contentDir(){if(this.serverMode)throw new Error("contentDir should not be used in server mode");return this.#n}markUserCodeReady(){this.#l?.(!0)}async reloadMarkdocOptions(){await le("com.redocly.build.reloadMarkdocOptions",async()=>{const{userTagNames:e,...t}=await Y(this.serverOutDir),s=Q(e),r=Object.fromEntries(Object.entries(t.tags).filter(([o])=>!(o in s)));this.#a={...t,tags:r},this.#i=s})}get markdocOptions(){return{...this.#a,partials:this.getGlobalConfig(y),themeConfig:this.config.markdown,planDeniedTags:this.#i}}setGlobalData=e=>{const t=this.globalData,s={...this.globalData,...e};this.globalData=s,JSON.stringify(s)!==JSON.stringify(t)&&this.queueEvent("global-data-updated",void 0,s)};getGlobalData=()=>this.globalData;getKv=async()=>q.getInstance({baseDbDir:this.serverOutDir});parseMarkdoc=async({input:e,context:t,deps:s,resource:r})=>{const{data:{info:o,ast:a},compoundHash:l}=await M(e,this.markdocOptions,{actions:this,context:t},r);for(const i of o.sharedDataDeps||[]){for(const n of s?.routeSlugs||[])this.addRouteSharedData(n,i,i);for(const n of s?.sharedDataIds||[]){const c=this.sharedDataDeps.get(n)||new Set;c.add(i),this.sharedDataDeps.set(n,c)}}for(const i of o.dynamicMarkdocComponents||[]){for(const n of s?.routeSlugs||[]){const c=this.routesDynamicComponents.get(n)||new Set;c.add(i),this.routesDynamicComponents.set(n,c)}for(const n of s?.sharedDataIds||[]){const c=this.sharedDataMarkdocComponents.get(n)||new Set;c.add(i),this.sharedDataMarkdocComponents.set(n,c)}}if(s?.routeSlugs&&o.partials?.length)for(const i of s.routeSlugs){const n=this.routesPartials.get(i)||[];for(const c of o.partials)n.includes(c)||n.push(c);this.routesPartials.set(i,n)}return{info:o,ast:a,compoundHash:l}};async loadApiDocuments(e){return(await e.cache.load(".","api-docs")).data}setSearchEngine(e){this.searchEngine=e}setSearchFacets=e=>{this.searchFacets=e};setStaticFilePaths=e=>{this.staticFilePaths=e};setGlobalConfig=e=>{const t=Object.keys(e);for(const a of t)for(const l in this.replacedEnvVars)if(l===a||l.startsWith(`${a}:`)){const i=l.split(":"),{error:n,value:c}=S(e,i);(n||c!==this.replacedEnvVars[l].replaced)&&delete this.replacedEnvVars[l]}const{config:s,unsetEnvVars:r,replacedValues:o}=re(e);for(const a of r)this.unsetEnvVars.add(a);Object.assign(this.replacedEnvVars,o),Object.assign(this.config,s)};getConfig=()=>this.config;getGlobalConfig=e=>this.config[e];getSearchFacets=()=>this.searchFacets;addRedirect=(e,t,s={})=>{if(!Z.instance().canAccessFeature("redirects")&&e!=="/")return;this.config.redirects||(this.config.redirects={});const a=d(e).toLowerCase();this.config.redirects[a]=t;const{trackOriginalSource:l=!0}=s,i=this.getGlobalConfig("originalRedirectSources");l&&Array.isArray(i)&&!i.includes(a)&&i.push(a),a.endsWith("*")&&ne(this.config.wildcardRedirectsTree,a)};getRedirect=e=>{const t=d(e).toLowerCase(),s=ae(t,this.config.redirects,this.config.wildcardRedirectsTree,this.staticFilePaths);if(!s)return null;if(v(s.to)){const r=d(s.to).toLowerCase();if(!r.endsWith("*")&&ie(r,[t],this.config.redirects,this.config.wildcardRedirectsTree).type==="cycle")return null}return{to:s.to,type:s.type}};createSharedData=async(e,t,s)=>{if(s&&this.#t[e]===s)return e;const r=JSON.stringify(t),o=s??_(r);return this.#t[e]===o||(this.#t[e]=o,await K(e,r,this.outdir),this.queueEvent("shared-data-updated",e)),e};addRouteSharedData=(e,t,s)=>{const r=G(e),o=this.routesSharedData.get(r)||{};o[t]=s,this.routesSharedData.set(r,o),u.verbose(`Adding shared data to ${e}, ${t}, ${s}`)};getRouteSharedDataByFsPath=e=>{const t=this.routesByFsPath.get(e);return t?this.routesSharedData.get(t)||{}:{}};getPartialsForRoute=e=>{const t=this.getGlobalConfig(y)||{},s=this.routesPartials.get(e);if(!s||s.length===0)return{};const r=this.getGlobalConfig(L)||{},o=new Set(s),a=Array.from(s);for(let i=0;i<a.length;i++){const n=a[i],c=r[n]?.partials??[];for(const h of c)o.has(h)||(o.add(h),a.push(h))}const l={};for(const i of o)t[i]&&(l[i]=t[i]);return l};addRoute=e=>{const s={...te(e.fsPath,this.config.metadataGlobs),...e.metadata||{}};this.newRoutes.push({...e,metadata:s}),u.verbose("Created route %s",e.slug)};addRouteSharedDataToAllLocales=(e,t,s)=>{const r=[m,...this.lifecycleContext?.fs.localeFolders||[]].map(o=>({code:o,name:o}));for(const o of r){const a=k(e,m,o.code,r);this.addRouteSharedData(a,t,s)}};addApiRoute=e=>{this.apiRoutes.push(e),u.verbose("Created API route %s",e.slug)};addMcpTools=(e,t)=>{for(const s of t){const r=this.mcpToolHandlers.get(s.name);r&&r.importPath!==e&&u.warn('MCP tool "%s" from %s overwrites the tool registered from %s',s.name,e,r.importPath);const o=s.hasAvailabilityGate??(r?.importPath===e?r.hasAvailabilityGate:void 0);this.mcpToolHandlers.set(s.name,{...s,importPath:e,hasAvailabilityGate:o}),u.verbose("Created MCP tool %s",s.name)}};getMcpTools=()=>Array.from(this.mcpToolHandlers.values());markGatedMcpTools=e=>{for(const t of e){const s=this.mcpToolHandlers.get(t);s&&this.mcpToolHandlers.set(t,{...s,hasAvailabilityGate:!0})}};addSkills=e=>{for(const t of e)this.skills.set(t.slug,t),u.verbose("Discovered skill %s",t.slug)};getSkills=()=>Array.from(this.skills.values());removeMcpTools=e=>{for(const t of e)this.mcpToolHandlers.delete(t)};addMiddleware=e=>{this.middleware.push(e),u.verbose("Created middleware %s",e.id)};setResourceResponseHeaders=(e,t)=>{this.config.responseHeaders||(this.config.responseHeaders={});const s=new Set(t.map(a=>a.name.toLowerCase())),o=[...(this.config.responseHeaders[e]??[]).filter(a=>!s.has(a.name.toLowerCase())),...t];this.config.responseHeaders[e]=o};getRouteByFsPath=e=>{const t=this.routesByFsPath.get(e);return t?this.getRouteBySlug(t):void 0};getRouteBySlug=(e,t={})=>{const{followRedirect:s=!0}=t,r=this.getRedirect(e);if(s&&r)return this.routesBySlug.get(d(r.to));const o=s?this.routeAliases.get(d(e).toLowerCase()):void 0;return this.routesBySlug.get(o??e)};addRouteAlias=(e,t)=>{this.routeAliases.set(d(e).toLowerCase(),d(t))};hasRouteOrRedirectBySlug=e=>{if(this.routesBySlug.has(e)||this.routeAliases.has(d(e).toLowerCase())||X(e,this.getConfig()))return!0;const t=this.getRedirect(e);if(!t)return!1;if(!v(t.to))return!0;const s=d(t.to);return this.routesBySlug.has(s)};getRoutesByTemplateId=e=>this.newRoutes.filter(t=>t.templateId===e);getAllRoutesForLocale=(e=m)=>{const t=Array.from(this.routesBySlug.values()),s=e.toLowerCase();return t.filter(r=>e===m?!ee(r.fsPath):r.slug.startsWith(`/${s}`))};getAllRoutes=()=>Array.from(this.routesBySlug.values());getAllApiRoutes=()=>this.apiRoutes;getAllMiddleware=()=>this.middleware;getTemplate=e=>this.templates.get(e);getRequestHandler=e=>this.apiRoutesRequestHandlers.get(e);createTemplate=(e,t)=>(this.templates.set(e,t),e);addBrowserPlugin=e=>{this.browserPlugins.add(e)};copyAsset=async(e,t)=>{const s=this.lifecycleContext?.fs;if(!s)throw new Error(`Cannot copy asset ${e}: the content file system is not ready`);try{const r=await I(e,s,{fromFileRelativePath:t,contentDir:this.contentDir,outdir:this.outdir});if(!r)throw new Error(`Cannot copy asset ${e}`);return r}catch(r){if(r instanceof B)return null;throw r}};createRequestHandler=(e,t)=>(this.apiRoutesRequestHandlers.set(e,t),e);clearRequestHandlersByPrefix=e=>{for(const t of this.apiRoutesRequestHandlers.keys())t.startsWith(e)&&this.apiRoutesRequestHandlers.delete(t)};registerServerPropsGetter=(e,t)=>(this.serverPropsGetters.set(e,t),e);registerPagePropsGetter=(e,t)=>{this.pagePropsGetters.set(e,t)};async writeRouteStaticData(e,t){const s=await this.resolveRouteStaticData(e,t,!1);s&&z(e.slug,s,this.outdir)}async resolveRouteStaticData(e,t,s){if(this.serverMode)return W(e.slug,this.outdir);const r={...this,contentDir:this.contentDir,parseMarkdoc:({input:c,context:h,resource:f})=>this.parseMarkdoc({input:c,context:h,deps:{routeSlugs:[e.slug]},resource:f})},o=await e.getStaticData?.(e,r)||{},a=new Set(this.routesDynamicComponents.get(e.slug)),l=this.routesSharedData.get(e.slug)||{};for(const c of Object.values(l)){const h=this.sharedDataMarkdocComponents.get(c);h&&h.forEach(p=>a.add(p));const f=this.sharedDataDeps.get(c);f&&f.forEach(p=>this.addRouteSharedData(e.slug,p,p))}const i=this.getGlobalConfig("seo"),n=o?.frontmatter||{};return{...o,frontmatter:{...n,seo:{...n?.seo,title:n?.seo?.title||await e.getNavText?.()}},props:{...o.props,dynamicMarkdocComponents:Array.from(a),metadata:{...o?.props?.metadata,...e.metadata},seo:{title:F,...i,...o.props?.seo,siteUrl:i?.siteUrl},compilationErrors:this.compilationErrors},lastModified:s||!e.fsPath?null:await this.lifecycleContext?.fs.getLastModified(e.fsPath)}}addSsrComponents(e,t){if(!e?.length)return;const s=typeof e[0]=="string"?e.join(""):$(e);s&&(t==="head"?this.ssr.headTags.push(s):t==="preBody"?this.ssr.preBodyTags.push(s):this.ssr.postBodyTags.push(s))}clear=()=>{this.routesByFsPath.clear(),this.templates.clear(),this.newRoutes=[],this.routesBySlug.clear(),this.routeAliases.clear(),this.apiRoutes=[],this.middleware=[],this.routesSharedData.clear(),this.sharedDataDeps.clear(),this.sharedDataMarkdocComponents.clear(),this.routesDynamicComponents.clear(),this.routesPartials.clear(),this.skills.clear(),this.config.redirects={},this.config.wildcardRedirectsTree={},this.config.directoryPermissions={},this.ssr={preBodyTags:[],postBodyTags:[],headTags:[]}};#g(){const e=[];for(const[s,r]of Object.entries(P))switch(r){case"map":{const o=Array.from(this[s].entries());e.push([s,o]);break}case"object":e.push([s,this[s]]);break;default:throw new Error("Invalid format")}const t=Object.fromEntries(e);return t[b]=j.PLAN_GATES,t}static#m(e,t){const s=new D(t);for(const[o,a]of Object.entries(P))switch(a){case"map":s[o]=new Map(e[o]);break;case"object":s[o]=e[o];break;default:throw new Error("Invalid format")}const r=e[b];return r&&V("PLAN_GATES",r),s}async writeServerFiles(){x(this.serverOutDir),w(g(this.serverOutDir,C),JSON.stringify(this.#g())),w(g(this.serverOutDir,A),JSON.stringify(await this.getConfigWithEnvPlaceholders()))}static async fromServerFiles(e){const t=g(e.serverOutDir,A),{config:s,env:r}=oe(JSON.parse(await R(t,"utf8")));s[y]=de(s[y]);const o=JSON.parse(await R(g(e.serverOutDir,C),"utf8")),a=D.#m(o,e);a.config=s;const l=Object.fromEntries(Object.entries(r).filter(([i])=>U(i)));return a.configFile={path:t,env:l,config:{...s}},a}async getConfigWithEnvPlaceholders(){const e=JSON.parse(JSON.stringify(this.config));for(const t in this.replacedEnvVars){const{original:s}=this.replacedEnvVars[t],r=t.split(":"),o=r.pop(),{error:a,value:l}=S(e,r);if(a||!H(l)&&!Array.isArray(l)){await E.panicOnBuild(`Failed to replace env var with env name for ${t}`);continue}l[o]=s}return e}async reportUnsetEnvVars(){if(this.unsetEnvVars.size===0)return;const e=Array.from(this.unsetEnvVars).filter(s=>!ce.includes(s));if(e.length===0)return;const t=`Failed to resolve config. The following environment variables are not set: ${e.join(", ")}`;await E.panicOnBuildContentError(t)}}function de(O){return N(O,e=>T.Ast.fromJSON(JSON.stringify(e)))}export{D as Store,We as USER_DEFINED_API_FUNCTIONS_COUNTER_KEY};
1
+ import T from"@redocly/markdoc";import{writeFileSync as w}from"node:fs";import{readFile as R}from"node:fs/promises";import{join as g}from"node:path";import{parseAndResolveMarkdoc as M}from"./plugins/markdown/compiler.js";import{getPathnameForLocale as k}from"@redocly/theme/core/utils";import{DEFAULT_LOCALE_PLACEHOLDER as m}from"../constants/common.js";import{DEFAULT_TITLE as F,MARKDOC_PARTIALS_DATA_KEY as y,MARKDOC_PARTIALS_DEPS_KEY as L}from"./constants/common.js";import{isObject as H}from"../utils/guards/is-object.js";import{mapObject as N}from"../utils/object/map-object.js";import{getValueDeep as S}from"../utils/object/get-value-deep.js";import{removeTrailingSlash as G}from"../utils/url/remove-trailing-slash.js";import{normalizeRouteSlug as d}from"../utils/path/normalize-route-slug.js";import{isLocalLink as v}from"../utils/path/is-local-link.js";import{reporter as E}from"./tools/notifiers/reporter.js";import{logger as u}from"./tools/notifiers/logger.js";import{sha1 as _}from"./utils/crypto/sha1.js";import{FileNotFoundError as B}from"./utils/fs.js";import{resolveAssetPath as I}from"./utils/resolve-asset-path.js";import{envConfig as j,setEnv as V}from"./config/env-config.js";import{KvService as q}from"./persistence/kv/services/kv-service.js";import{SandboxContext as J}from"./utils/sandbox-context.js";import{isAllowedEnv as U}from"./utils/envs/get-api-route-allowed-env-variables.js";import{ensureDir as x,writeSharedData as K}from"./utils/index.js";import{renderComponents as $}from"./ssr/render.js";import{readStaticData as W,writeStaticData as z}from"./utils/static-data.js";import{getMarkdocOptions as Y}from"./plugins/markdown/markdoc/markdoc-options.js";import{EntitlementsProvider as Z}from"./entitlements/entitlements-provider.js";import{getPlanDeniedMarkdocTags as Q}from"./entitlements/plan-denied-markdoc-tags.js";import{isRouteReserved as X}from"./plugins/get-reserved-routes.js";import{isL10nPath as ee}from"./fs/utils/is-l10n-path.js";import{resolveGlobMapValue as te}from"./utils/globs.js";import{createDefaultStoreConfig as se,resolveConfigEntries as re,resolveStoreConfig as oe}from"./store-config.js";import{findRedirect as ae}from"./utils/redirects/find-redirect.js";import{followRedirectChain as ie}from"./utils/redirects/follow-redirect-chain.js";import{addWildcardRedirectToTree as ne}from"./utils/redirects/add-wildcard-redirect-to-tree.js";import{telemetryTraceStep as le}from"../cli/telemetry/helpers/trace-step.js";const P={routesBySlug:"map",staticFilePaths:"object",apiRoutes:"object",middleware:"object",routesByFsPath:"map",routesSharedData:"map",globalData:"object",ssr:"object",searchFacets:"map",routesPartials:"map",mcpToolHandlers:"map",skills:"map",devLogin:"object"},C="store.json",A="store-config.json",b="PLAN_GATES",ce=["OAUTH_CLIENT_ID","OAUTH_CLIENT_SECRET","ORGANIZATION_SLUG","ORGANIZATION_ID","ORG_ID"],We="userDefinedApiFunctions";class D{routesBySlug=new Map;routeAliases=new Map;staticFilePaths={};replacedEnvVars={};unsetEnvVars=new Set;lifecycleContext;newRoutes=[];#t={};routesByFsPath=new Map;apiRoutes=[];middleware=[];routesSharedData=new Map;sharedDataDeps=new Map;sharedDataMarkdocComponents=new Map;routesDynamicComponents=new Map;routesPartials=new Map;ssr={preBodyTags:[],postBodyTags:[],headTags:[]};searchFacets=new Map;searchEngine;templates=new Map;browserPlugins=new Set;apiRoutesRequestHandlers=new Map;mcpToolHandlers=new Map;skills=new Map;serverPropsGetters=new Map;pagePropsGetters=new Map;listeners=new Map;globalData={};devLogin=!1;#a=void 0;#i={};config=se();configFile;#n;serverMode;serverOutDir;outdir;buildRevision=0;hasSitemap=!1;compilationErrors=[];#l;userCodeReady;#s=Promise.resolve();#c;#d=Promise.resolve();#h;#u=Promise.resolve();#f;#e=!1;#r=0;#p=0;#o=new Map;constructor({outdir:e,contentDir:t,serverMode:s=!1,serverOutDir:r}){this.#n=t,this.outdir=e,this.serverMode=s,this.serverOutDir=r,J.register({serverOutDir:r,readRoots:[e,process.cwd()]}),this.userCodeReady=new Promise(o=>{this.#l=o})}on(e,t){const s=this.listeners.get(e);s?s.add(t):this.listeners.set(e,new Set([t]))}queueEvent=(e,t,...s)=>{this.#o.set(e+String(t),[e,t,...s])};runListeners=(e,t,...s)=>{for(const r of this.listeners.get(e)||new Set)t?r(t,...s):r(...s)};startPluginsRun(){this.clear(),this.#s=new Promise(e=>{this.#c=e})}waitForPluginsLifecycle(){return Promise.all([this.#s,this.#d,this.#u])}waitForPluginsRun(){return this.#s}finishPluginsRun(){this.#c?.();for(const e of this.#o.values())this.runListeners(...e);this.#o.clear()}startEsbuildRun(){this.#d=new Promise(e=>{this.#h=e})}finishEsbuildRun(){this.#h?.()}markRequestHandlersEntryOutdated(){this.#r++,!this.#e&&(this.#e=!0,this.#u=new Promise(e=>{this.#f=e}))}noteRequestHandlersEntryBuildStart(){this.#p=this.#r}markRequestHandlersEntryUpdated(){return this.#e?this.#r>this.#p?!1:(this.#e=!1,this.#f?.(),!0):!0}get contentDir(){if(this.serverMode)throw new Error("contentDir should not be used in server mode");return this.#n}markUserCodeReady(){this.#l?.(!0)}async reloadMarkdocOptions(){await le("com.redocly.build.reloadMarkdocOptions",async()=>{const{userTagNames:e,...t}=await Y(this.serverOutDir),s=Q(e),r=Object.fromEntries(Object.entries(t.tags).filter(([o])=>!(o in s)));this.#a={...t,tags:r},this.#i=s})}get markdocOptions(){return{...this.#a,partials:this.getGlobalConfig(y),themeConfig:this.config.markdown,planDeniedTags:this.#i}}setGlobalData=e=>{const t=this.globalData,s={...this.globalData,...e};this.globalData=s,JSON.stringify(s)!==JSON.stringify(t)&&this.queueEvent("global-data-updated",void 0,s)};getGlobalData=()=>this.globalData;getKv=async()=>q.getInstance({baseDbDir:this.serverOutDir});parseMarkdoc=async({input:e,context:t,deps:s,resource:r})=>{const{data:{info:o,ast:a},compoundHash:l}=await M(e,this.markdocOptions,{actions:this,context:t},r);for(const i of o.sharedDataDeps||[]){for(const n of s?.routeSlugs||[])this.addRouteSharedData(n,i,i);for(const n of s?.sharedDataIds||[]){const c=this.sharedDataDeps.get(n)||new Set;c.add(i),this.sharedDataDeps.set(n,c)}}for(const i of o.dynamicMarkdocComponents||[]){for(const n of s?.routeSlugs||[]){const c=this.routesDynamicComponents.get(n)||new Set;c.add(i),this.routesDynamicComponents.set(n,c)}for(const n of s?.sharedDataIds||[]){const c=this.sharedDataMarkdocComponents.get(n)||new Set;c.add(i),this.sharedDataMarkdocComponents.set(n,c)}}if(s?.routeSlugs&&o.partials?.length)for(const i of s.routeSlugs){const n=this.routesPartials.get(i)||[];for(const c of o.partials)n.includes(c)||n.push(c);this.routesPartials.set(i,n)}return{info:o,ast:a,compoundHash:l}};async loadApiDocuments(e){return(await e.cache.load(".","api-docs")).data}setSearchEngine(e){this.searchEngine=e}setSearchFacets=e=>{this.searchFacets=e};setStaticFilePaths=e=>{this.staticFilePaths=e};setGlobalConfig=e=>{const t=Object.keys(e);for(const a of t)for(const l in this.replacedEnvVars)if(l===a||l.startsWith(`${a}:`)){const i=l.split(":"),{error:n,value:c}=S(e,i);(n||c!==this.replacedEnvVars[l].replaced)&&delete this.replacedEnvVars[l]}const{config:s,unsetEnvVars:r,replacedValues:o}=re(e);for(const a of r)this.unsetEnvVars.add(a);Object.assign(this.replacedEnvVars,o),Object.assign(this.config,s)};getConfig=()=>this.config;getGlobalConfig=e=>this.config[e];getSearchFacets=()=>this.searchFacets;addRedirect=(e,t,s={})=>{if(!Z.instance().canAccessFeature("redirects")&&e!=="/")return;this.config.redirects||(this.config.redirects={});const a=d(e).toLowerCase();this.config.redirects[a]=t;const{trackOriginalSource:l=!0}=s,i=this.getGlobalConfig("originalRedirectSources");l&&Array.isArray(i)&&!i.includes(a)&&i.push(a),a.endsWith("*")&&ne(this.config.wildcardRedirectsTree,a)};getRedirect=e=>{const t=d(e).toLowerCase(),s=ae(t,this.config.redirects,this.config.wildcardRedirectsTree,this.staticFilePaths);if(!s)return null;if(v(s.to)){const r=d(s.to).toLowerCase();if(!r.endsWith("*")&&ie(r,[t],this.config.redirects,this.config.wildcardRedirectsTree).type==="cycle")return null}return{to:s.to,type:s.type}};createSharedData=async(e,t,s)=>{if(s&&this.#t[e]===s)return e;const r=JSON.stringify(t),o=s??_(r);return this.#t[e]===o||(this.#t[e]=o,await K(e,r,this.outdir),this.queueEvent("shared-data-updated",e)),e};addRouteSharedData=(e,t,s)=>{const r=G(e),o=this.routesSharedData.get(r)||{};o[t]=s,this.routesSharedData.set(r,o),u.verbose(`Adding shared data to ${e}, ${t}, ${s}`)};getRouteSharedDataByFsPath=e=>{const t=this.routesByFsPath.get(e);return t?this.routesSharedData.get(t)||{}:{}};getPartialsForRoute=e=>{const t=this.getGlobalConfig(y)||{},s=this.routesPartials.get(e);if(!s||s.length===0)return{};const r=this.getGlobalConfig(L)||{},o=new Set(s),a=Array.from(s);for(let i=0;i<a.length;i++){const n=a[i],c=r[n]?.partials??[];for(const h of c)o.has(h)||(o.add(h),a.push(h))}const l={};for(const i of o)t[i]&&(l[i]=t[i]);return l};addRoute=e=>{const s={...te(e.fsPath,this.config.metadataGlobs),...e.metadata||{}};this.newRoutes.push({...e,metadata:s}),u.verbose("Created route %s",e.slug)};addRouteSharedDataToAllLocales=(e,t,s)=>{const r=[m,...this.lifecycleContext?.fs.localeFolders||[]].map(o=>({code:o,name:o}));for(const o of r){const a=k(e,m,o.code,r);this.addRouteSharedData(a,t,s)}};addApiRoute=e=>{this.apiRoutes.push(e),u.verbose("Created API route %s",e.slug)};addMcpTools=(e,t)=>{for(const s of t){const r=this.mcpToolHandlers.get(s.name);r&&r.importPath!==e&&u.warn('MCP tool "%s" from %s overwrites the tool registered from %s',s.name,e,r.importPath);const o=s.hasAvailabilityGate??(r?.importPath===e?r.hasAvailabilityGate:void 0);this.mcpToolHandlers.set(s.name,{...s,importPath:e,hasAvailabilityGate:o}),u.verbose("Created MCP tool %s",s.name)}};getMcpTools=()=>Array.from(this.mcpToolHandlers.values());markGatedMcpTools=e=>{for(const t of e){const s=this.mcpToolHandlers.get(t);s&&this.mcpToolHandlers.set(t,{...s,hasAvailabilityGate:!0})}};addSkills=e=>{for(const t of e)this.skills.set(t.slug,t),u.verbose("Discovered skill %s",t.slug)};getSkills=()=>Array.from(this.skills.values());removeMcpTools=e=>{for(const t of e)this.mcpToolHandlers.delete(t)};addMiddleware=e=>{this.middleware.push(e),u.verbose("Created middleware %s",e.id)};setResourceResponseHeaders=(e,t)=>{this.config.responseHeaders||(this.config.responseHeaders={});const s=new Set(t.map(a=>a.name.toLowerCase())),o=[...(this.config.responseHeaders[e]??[]).filter(a=>!s.has(a.name.toLowerCase())),...t];this.config.responseHeaders[e]=o};getRouteByFsPath=e=>{const t=this.routesByFsPath.get(e);return t?this.getRouteBySlug(t):void 0};getRouteBySlug=(e,t={})=>{const{followRedirect:s=!0}=t,r=this.getRedirect(e);if(s&&r)return this.routesBySlug.get(d(r.to));const o=s?this.routeAliases.get(d(e).toLowerCase()):void 0;return this.routesBySlug.get(o??e)};addRouteAlias=(e,t)=>{this.routeAliases.set(d(e).toLowerCase(),d(t))};hasRouteOrRedirectBySlug=e=>{if(this.routesBySlug.has(e)||this.routeAliases.has(d(e).toLowerCase())||X(e,this.getConfig()))return!0;const t=this.getRedirect(e);if(!t)return!1;if(!v(t.to))return!0;const s=d(t.to);return this.routesBySlug.has(s)};getRoutesByTemplateId=e=>this.newRoutes.filter(t=>t.templateId===e);getAllRoutesForLocale=(e=m)=>{const t=Array.from(this.routesBySlug.values()),s=e.toLowerCase();return t.filter(r=>e===m?!ee(r.fsPath):r.slug.startsWith(`/${s}`))};getAllRoutes=()=>Array.from(this.routesBySlug.values());getAllApiRoutes=()=>this.apiRoutes;getAllMiddleware=()=>this.middleware;getTemplate=e=>this.templates.get(e);getRequestHandler=e=>this.apiRoutesRequestHandlers.get(e);createTemplate=(e,t)=>(this.templates.set(e,t),e);addBrowserPlugin=e=>{this.browserPlugins.add(e)};copyAsset=async(e,t)=>{const s=this.lifecycleContext?.fs;if(!s)throw new Error(`Cannot copy asset ${e}: the content file system is not ready`);try{const r=await I(e,s,{fromFileRelativePath:t,contentDir:this.contentDir,outdir:this.outdir});if(!r)throw new Error(`Cannot copy asset ${e}`);return r}catch(r){if(r instanceof B)return null;throw r}};createRequestHandler=(e,t)=>(this.apiRoutesRequestHandlers.set(e,t),e);clearRequestHandlersByPrefix=e=>{for(const t of this.apiRoutesRequestHandlers.keys())t.startsWith(e)&&this.apiRoutesRequestHandlers.delete(t)};registerServerPropsGetter=(e,t)=>(this.serverPropsGetters.set(e,t),e);registerPagePropsGetter=(e,t)=>{this.pagePropsGetters.set(e,t)};async writeRouteStaticData(e,t){const s=await this.resolveRouteStaticData(e,t,!1);s&&z(e.slug,s,this.outdir)}async resolveRouteStaticData(e,t,s){if(this.serverMode)return W(e.slug,this.outdir);const r={...this,contentDir:this.contentDir,parseMarkdoc:({input:c,context:h,resource:f})=>this.parseMarkdoc({input:c,context:h,deps:{routeSlugs:[e.slug]},resource:f})},o=await e.getStaticData?.(e,r)||{},a=new Set(this.routesDynamicComponents.get(e.slug)),l=this.routesSharedData.get(e.slug)||{};for(const c of Object.values(l)){const h=this.sharedDataMarkdocComponents.get(c);h&&h.forEach(p=>a.add(p));const f=this.sharedDataDeps.get(c);f&&f.forEach(p=>this.addRouteSharedData(e.slug,p,p))}const i=this.getGlobalConfig("seo"),n=o?.frontmatter||{};return{...o,frontmatter:{...n,seo:{...n?.seo,title:n?.seo?.title||await e.getNavText?.()}},props:{...o.props,dynamicMarkdocComponents:Array.from(a),metadata:{...o?.props?.metadata,...e.metadata},seo:{title:F,...i,...o.props?.seo,siteUrl:i?.siteUrl},compilationErrors:this.compilationErrors},lastModified:s||!e.fsPath?null:await this.lifecycleContext?.fs.getLastModified(e.fsPath)}}addSsrComponents(e,t){if(!e?.length)return;const s=typeof e[0]=="string"?e.join(""):$(e);s&&(t==="head"?this.ssr.headTags.push(s):t==="preBody"?this.ssr.preBodyTags.push(s):this.ssr.postBodyTags.push(s))}clear=()=>{this.routesByFsPath.clear(),this.templates.clear(),this.newRoutes=[],this.routesBySlug.clear(),this.routeAliases.clear(),this.apiRoutes=[],this.middleware=[],this.routesSharedData.clear(),this.sharedDataDeps.clear(),this.sharedDataMarkdocComponents.clear(),this.routesDynamicComponents.clear(),this.routesPartials.clear(),this.skills.clear(),this.config.redirects={},this.config.wildcardRedirectsTree={},this.config.directoryPermissions={},this.ssr={preBodyTags:[],postBodyTags:[],headTags:[]}};#g(){const e=[];for(const[s,r]of Object.entries(P))switch(r){case"map":{const o=Array.from(this[s].entries());e.push([s,o]);break}case"object":e.push([s,this[s]]);break;default:throw new Error("Invalid format")}const t=Object.fromEntries(e);return t[b]=j.PLAN_GATES,t}static#m(e,t){const s=new D(t);for(const[o,a]of Object.entries(P))switch(a){case"map":s[o]=new Map(e[o]);break;case"object":s[o]=e[o];break;default:throw new Error("Invalid format")}const r=e[b];return r&&V("PLAN_GATES",r),s}async writeServerFiles(){x(this.serverOutDir),w(g(this.serverOutDir,C),JSON.stringify(this.#g())),w(g(this.serverOutDir,A),JSON.stringify(await this.getConfigWithEnvPlaceholders()))}static async fromServerFiles(e){const t=g(e.serverOutDir,A),{config:s,env:r}=oe(JSON.parse(await R(t,"utf8")));s[y]=de(s[y]);const o=JSON.parse(await R(g(e.serverOutDir,C),"utf8")),a=D.#m(o,e);a.config=s;const l=Object.fromEntries(Object.entries(r).filter(([i])=>U(i)));return a.configFile={path:t,env:l,config:{...s}},a}async getConfigWithEnvPlaceholders(){const e=JSON.parse(JSON.stringify(this.config));for(const t in this.replacedEnvVars){const{original:s}=this.replacedEnvVars[t],r=t.split(":"),o=r.pop(),{error:a,value:l}=S(e,r);if(a||!H(l)&&!Array.isArray(l)){await E.panicOnBuild(`Failed to replace env var with env name for ${t}`);continue}l[o]=s}return e}async reportUnsetEnvVars(){if(this.unsetEnvVars.size===0)return;const e=Array.from(this.unsetEnvVars).filter(s=>!ce.includes(s));if(e.length===0)return;const t=`Failed to resolve config. The following environment variables are not set: ${e.join(", ")}`;await E.panicOnBuildContentError(t)}}function de(O){return N(O,e=>T.Ast.fromJSON(JSON.stringify(e)))}export{D as Store,We as USER_DEFINED_API_FUNCTIONS_COUNTER_KEY};
@@ -43,18 +43,23 @@ export declare function canAccessAsset(pathname: string, rbacConfig: RbacConfig,
43
43
  teams?: string[];
44
44
  }): boolean;
45
45
  export declare function getAuthDetailsFromCookies(ssoConfig: SsoConfig, cookies: Record<string, string>): Promise<AuthDetails>;
46
+ type FilterUser = {
47
+ isAuthenticated?: boolean;
48
+ email?: string;
49
+ teams?: string[];
50
+ };
46
51
  /**
47
- * Maps the input deep and removes objects that have a 'permission' prop
48
- * but do not match the input permissions list
52
+ * Removes, at any depth, the objects the user cannot access and strips RBAC annotations.
53
+ * Never mutates `input`, which must not change after the first call; callers must not mutate the
54
+ * result, which may be cached shared data.
55
+ * Every user denied nothing gets one shared object for the same `input`: `input` itself when it
56
+ * has nothing to strip. A user denied something gets a copy that shares no array or object with
57
+ * `input` or with another result, except `x-parsed-md-*` values, so a cache keyed by object
58
+ * identity never serves data filtered for one user to another.
49
59
  * @param input can be object, array, string or any other value
50
60
  * @param user - user object with email and teams
51
- * @returns
52
61
  */
53
- export declare function filterDataByAccessDeep(input: any, user?: {
54
- isAuthenticated?: boolean;
55
- email?: string;
56
- teams?: string[];
57
- }, rbacConfig?: RbacConfig, requiresLogin?: boolean): any;
62
+ export declare function filterDataByAccessDeep(input: any, user?: FilterUser, rbacConfig?: RbacConfig, requiresLogin?: boolean): any;
58
63
  export declare function parseTeamClaimToArray(claimValue: unknown): string[];
59
64
  /**
60
65
  * Extends RBAC config rules to include all supported languages
@@ -166,4 +171,5 @@ export declare function getRbacTeamsListForResource(resource: {
166
171
  }, rbacConfig: RbacConfig): string[];
167
172
  export declare function extractTeamsFromScopeItems(scopeItems: RbacScopeItems | undefined): string[];
168
173
  export declare function expandTeamsForRead(rbacConfig: RbacConfig, teamNames: string[]): string[];
174
+ export {};
169
175
  //# sourceMappingURL=rbac.d.ts.map
@@ -1 +1 @@
1
- import _ from"path";import O from"picomatch";import"../node-crypto-polyfill.js";import{REDOCLY_TEAMS_RBAC as T,REDOCLY_ROUTE_RBAC as E}from"@redocly/config";import{MCP_ROUTE as M,PUBLIC_MCP_ROUTE as k}from"@redocly/theme/core/constants/mcp";import{ServerRoutes as w}from"../../constants/api.js";import{DEFAULT_ANONYMOUS_VISITOR_TEAM as S,PUBLIC_RBAC_SCOPE_ITEM as d,RBAC_ALL_OTHER_TEAMS as p,DEFAULT_RBAC_SCOPE as D,GRAPHQL_SPEC_SLUG as B}from"../../constants/common.js";import{DEPRECATED_PUBLIC_API_DEFINITIONS_FOLDER as x,PUBLIC_API_DEFINITIONS_FOLDER as g,PUBLIC_ASSETS_FOLDER as b,RUNTIME_RESOURCES_DIR as $,SCORECARD_CLASSIC_FOLDER as W,SITEMAP_FILE_NAME as v,LLMS_TXT_FILE_NAME as Y}from"../constants/common.js";import{MCP_CREDENTIALS_ROUTE as G}from"../constants/mcp.js";import{ANONYMOUS_AUTH_DETAILS as H}from"../constants/rbac.js";import{removeTrailingSlash as L}from"../../utils/url/remove-trailing-slash.js";import{removeLeadingSlash as z}from"../../utils/url/remove-leading-slash.js";import{parsePathVersions as K}from"../../utils/path/parse-path-versions.js";import{reporter as V}from"../tools/notifiers/reporter.js";import{bold as J}from"../tools/notifiers/helpers/colors.js";import{shaDirPathShort as Q}from"../utils/crypto/sha-dir-path-short.js";import{isTruthy as X}from"../../utils/guards/is-truthy.js";import{isPathInFolder as C}from"../../utils/path/is-path-in-folder.js";import{canExpandConfig as Z,expandRbacConfig as q,getTeamFolderDefaults as tt,parseTeamFoldersTemplate as et,parseTeamNameTemplate as rt}from"./rbac-expand.js";import{getUserParamsFromCookies as nt}from"../web-server/auth.js";import{getDeeperGlobPattern as ot}from"./globs.js";import{hasScopeAccess as j}from"./rbac/has-scope-access.js";import{EntitlementsProvider as st}from"../entitlements/entitlements-provider.js";const N=["NONE","READ","TRIAGE","WRITE","MAINTAIN","ADMIN"],ct=new Set(["x-parsed-md-description","x-parsed-md-summary"]),at="@api",it=new Set(Object.values(w).map(t=>L(t.split(":")[0])));function bt(t,e){const n=N.indexOf(t.toUpperCase()),r=N.indexOf(e.toUpperCase());return n>r?t:e}const P={};function F(t,e){if(!t?.content)return d;const n=t.content,{slug:r,fsPath:o}=e;if(!r&&!o)return d;const s=f=>{const R=`slug:${f}`,u=P[R]??O(f);P[R]=u;const y=`fsPath:${f}`,I=P[y]??O(z(f));return P[y]=I,!!(r&&u(r))||!!(o&&I(o))};if(mt(r||o||"")&&Object.keys(n).filter(u=>s(u)).length===0)return n[D]||d;const i=Object.keys(n).filter(f=>s(f));if(i.length==0)return d;const l=i.map(f=>O.scan(f,{tokens:!0,parts:!0}));let h=l[0];for(let f=1;f<l.length;f++)h=ot(h,l[f]);return n[h.input]}function $t(t,e){return A(t,H,e.access?.rbac||{},e.access?.requiresLogin||!1)}function Wt(t){const e={[D]:d,...t?.content};return Object.entries(e).some(([n,r])=>!n.split("/").includes(at)&&j(r,[S]))}function A(t,e={},n={},r=!1){if(t.slug&&typeof t.slug=="string"&&it.has(L(t.slug))||(t.slug===M||t.slug===k||t.slug===G)&&st.instance().canAccessFeature("mcp"))return!0;if(r&&Object.keys(n).length===0)return!!e.isAuthenticated;const o=q(n,e.teams||[]),s=t[T]||F(o,t[E]||{});return Object.keys(s||{}).length===0?!1:Object.keys(s).length===1&&s[p]&&s[p].toLowerCase()!=="none"?!0:j(s,e?.teams||[],e?.email)}function vt(t,e,n,r,o){if(!t.startsWith(g)&&!t.startsWith(x))return!0;if(o){const l={[T]:o.rbac,[E]:{slug:o.slug,fsPath:o.sourcePath}};return A(l,r,e,n)}const s=t.replace(new RegExp(`^${g}/`),"").replace(new RegExp(`^${x}/`),"").replace(new RegExp(`^${B}/`),""),a=s==="."?"":s,i={[E]:{slug:t,fsPath:a},slug:t};return A(i,r,e,n)}function Yt(t,e,n,r,o){if(!C(t,b))return[`/${v}`,`/${Y}`].includes(t)||[$,W].some(y=>C(t,y));const s=t.match(/\..{64}\.([A-Fa-f0-9]{8})\.[^.]+$/)?.[1];if(!s)return!0;const c=r[s];if(!c)return!0;const{base:a,ext:i}=_.parse(t),l=a.split(".")[0],h=i.split(".").join(""),R=c==="."?"":c,u={[E]:{slug:t,fsPath:_.posix.join(R,`${l}.${h}`)},slug:t};return A(u,o,e,n)}async function Gt(t,e){const{isAuthenticated:n=!1,idpAccessToken:r,federatedAccessToken:o,federatedIdToken:s,...c}=await nt(t,e),{teams:a=[]}=c;let i;return n?i=a.filter(l=>l!==S):i=[S],{isAuthenticated:n,idpAccessToken:r,teams:i,claims:c}}function U(t,e,n={},r=!1){if(!t)return t;if(Array.isArray(t)){const o=[];for(const s of t){const c=U(s,e,n,r);c!==void 0&&o.push(c)}return o}if(typeof t=="object"){if(!A(t,e,n,r))return;let o=!1;const s={};for(const c in t){if(c===T||c===E)continue;if(ct.has(c)){s[c]=t[c];continue}const a=U(t[c],e,n,r);if(!t.link&&(c==="items"||c==="menu"&&t.type==="tab")&&Array.isArray(a)&&a.length===0&&t[c].length!==0){o=!0;continue}a!==void 0&&(s[c]=a),c==="paths"&&ft(a)&&lt(a)}return o?void 0:s}return t}function Ht(t){return typeof t=="string"?t.split(" ").filter(Boolean):Array.isArray(t)?t.map(e=>e.toString()):[]}function zt(t,e){if(!e)return;const n=e.content;if(!n)return e;const r=Object.entries(n).flatMap(([s,c])=>s===D?[[s,c]]:[[s,c]].concat(t.localeFolders.map(a=>[s.startsWith("/")?`/${a.toLocaleLowerCase()}${s}`:_.posix.join(t.localizationFolder,a,s),c]))),o=Object.fromEntries(r);return{...e,content:o}}async function Kt(t,e){if(!e)return{};const n={},r=new Set(t.scan().flatMap(({relativePath:o})=>{const{versionFolderPath:s}=K(o)||{},c=_.dirname(o);return s?[s,c]:c}));for(const o of r)n[Q(o)]=o;return n}const m=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function ft(t){return m(t)&&Object.keys(t).length>0}function lt(t){for(const e of Object.keys(t)){const n=t[e];m(n)&&Object.keys(n).length===0&&delete t[e]}}function mt(t){return t?t.split("/").filter(Boolean).some(n=>n.startsWith(".")):!1}const ut=t=>{if(t&&m(t)&&("content"in t&&m(t.content)||"platform"in t&&m(t.platform)||"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(n=>Object.values(n).every(r=>typeof r=="string"))}return!1},Vt=async t=>{if(t){if(Object.keys(t).length===0)return{};if(ut(t))return pt(t);await V.panicOnContentError(`You are using an incorrect format of ${J("rbac:")} configuration. See: https://redocly.com/docs/realm/access`)}},pt=t=>{const e={...t};if(e.content){const n={};for(const r in e.content)if(e.content[r]!==void 0){const o=L(r);n[o]=e.content[r]}e.content=n}return e};function Jt(t,e){const n=t.fsPath,r=t.slug,o=[],s=Z(e)&&(n||r)?et(e,[n,r].filter(X)):null;if(s){const a=e?.teamNamePatterns?.map(i=>i.replace("{teamPathSegment}",s.teamPathSegment).replace("{projectRole}","read"))??[];o.push(...a)}const c=F(s?{content:{...tt(e),...e.content}}:e,t);return o.push(...ht(c)),Rt(e,o)}function ht(t){if(!t)return[];const e=[],n=p in t?{authenticated:t[p],anonymous:t[p]}:{};for(const[r,o]of Object.entries({...n,...t}))o.toLowerCase()!=="none"&&r!==p&&e.push(r);return e}function Rt(t,e){return e.map(r=>rt(t,r)??{teamName:r}).map(r=>r.projectRole&&r.projectRole!=="READ"?r.teamName?.toLowerCase().replace(r.projectRole?.toLowerCase?.()??"","read")??"":r.teamName?.toLowerCase()??"")}export{N as PROJECT_ROLES_ORDERED_BY_ACCESS_LEVEL,zt as applyL10nToRbacConfig,Wt as areAnyPagesOpenToAnonymous,Yt as canAccessAsset,A as canAccessResource,vt as canDownloadApiDefinition,Rt as expandTeamsForRead,ht as extractTeamsFromScopeItems,U as filterDataByAccessDeep,Gt as getAuthDetailsFromCookies,bt as getHigherRole,Jt as getRbacTeamsListForResource,F as getScopeItemsForResource,ut as isRbacConfigValid,$t as isResourcePubliclyAccessible,pt as normalizeRbacConfig,Vt as parseRbacConfig,Ht as parseTeamClaimToArray,Kt as resolveDirectoryHashes};
1
+ import O from"path";import _ from"picomatch";import"../node-crypto-polyfill.js";import{REDOCLY_TEAMS_RBAC as g,REDOCLY_ROUTE_RBAC as E}from"@redocly/config";import{MCP_ROUTE as w,PUBLIC_MCP_ROUTE as B}from"@redocly/theme/core/constants/mcp";import{ServerRoutes as W}from"../../constants/api.js";import{DEFAULT_ANONYMOUS_VISITOR_TEAM as T,PUBLIC_RBAC_SCOPE_ITEM as R,RBAC_ALL_OTHER_TEAMS as p,DEFAULT_RBAC_SCOPE as S,GRAPHQL_SPEC_SLUG as $}from"../../constants/common.js";import{DEPRECATED_PUBLIC_API_DEFINITIONS_FOLDER as j,PUBLIC_API_DEFINITIONS_FOLDER as N,PUBLIC_ASSETS_FOLDER as Y,RUNTIME_RESOURCES_DIR as H,SCORECARD_CLASSIC_FOLDER as z,SITEMAP_FILE_NAME as G,LLMS_TXT_FILE_NAME as K}from"../constants/common.js";import{MCP_CREDENTIALS_ROUTE as V}from"../constants/mcp.js";import{ANONYMOUS_AUTH_DETAILS as q}from"../constants/rbac.js";import{removeTrailingSlash as D}from"../../utils/url/remove-trailing-slash.js";import{removeLeadingSlash as J}from"../../utils/url/remove-leading-slash.js";import{parsePathVersions as Q}from"../../utils/path/parse-path-versions.js";import{reporter as X}from"../tools/notifiers/reporter.js";import{bold as v}from"../tools/notifiers/helpers/colors.js";import{shaDirPathShort as Z}from"../utils/crypto/sha-dir-path-short.js";import{isTruthy as tt}from"../../utils/guards/is-truthy.js";import{isPathInFolder as F}from"../../utils/path/is-path-in-folder.js";import{canExpandConfig as et,expandRbacConfig as rt,getTeamFolderDefaults as nt,parseTeamFoldersTemplate as ot,parseTeamNameTemplate as st}from"./rbac-expand.js";import{getUserParamsFromCookies as ct}from"../web-server/auth.js";import{getDeeperGlobPattern as it}from"./globs.js";import{hasScopeAccess as U}from"./rbac/has-scope-access.js";import{EntitlementsProvider as at}from"../entitlements/entitlements-provider.js";const b=["NONE","READ","TRIAGE","WRITE","MAINTAIN","ADMIN"],M=new Set(["x-parsed-md-description","x-parsed-md-summary"]),ft="@api",lt=new Set(Object.values(W).map(t=>D(t.split(":")[0])));function $t(t,e){const r=b.indexOf(t.toUpperCase()),n=b.indexOf(e.toUpperCase());return r>n?t:e}const P={};function k(t,e){if(!t?.content)return R;const r=t.content,{slug:n,fsPath:s}=e;if(!n&&!s)return R;const o=i=>{const d=`slug:${i}`,u=P[d]??_(i);P[d]=u;const A=`fsPath:${i}`,C=P[A]??_(J(i));return P[A]=C,!!(n&&u(n))||!!(s&&C(s))};if(pt(n||s||"")&&Object.keys(r).filter(u=>o(u)).length===0)return r[S]||R;const a=Object.keys(r).filter(i=>o(i));if(a.length==0)return R;const l=a.map(i=>_.scan(i,{tokens:!0,parts:!0}));let h=l[0];for(let i=1;i<l.length;i++)h=it(h,l[i]);return r[h.input]}function Yt(t,e){return y(t,q,e.access?.rbac||{},e.access?.requiresLogin||!1)}function Ht(t){const e={[S]:R,...t?.content};return Object.entries(e).some(([r,n])=>!r.split("/").includes(ft)&&U(n,[T]))}function y(t,e={},r={},n=!1){if(t.slug&&typeof t.slug=="string"&&lt.has(D(t.slug))||(t.slug===w||t.slug===B||t.slug===V)&&at.instance().canAccessFeature("mcp"))return!0;if(n&&Object.keys(r).length===0)return!!e.isAuthenticated;const s=rt(r,e.teams||[]),o=t[g]||k(s,t[E]||{});return Object.keys(o||{}).length===0?!1:Object.keys(o).length===1&&o[p]&&o[p].toLowerCase()!=="none"?!0:U(o,e?.teams||[],e?.email)}function zt(t,e,r,n,s){if(!t.startsWith(N)&&!t.startsWith(j))return!0;if(s){const l={[g]:s.rbac,[E]:{slug:s.slug,fsPath:s.sourcePath}};return y(l,n,e,r)}const o=t.replace(new RegExp(`^${N}/`),"").replace(new RegExp(`^${j}/`),"").replace(new RegExp(`^${$}/`),""),f=o==="."?"":o,a={[E]:{slug:t,fsPath:f},slug:t};return y(a,n,e,r)}function Gt(t,e,r,n,s){if(!F(t,Y))return[`/${G}`,`/${K}`].includes(t)||[H,z].some(A=>F(t,A));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:f,ext:a}=O.parse(t),l=f.split(".")[0],h=a.split(".").join(""),d=c==="."?"":c,u={[E]:{slug:t,fsPath:O.posix.join(d,`${l}.${h}`)},slug:t};return y(u,s,e,r)}async function Kt(t,e){const{isAuthenticated:r=!1,idpAccessToken:n,federatedAccessToken:s,federatedIdToken:o,...c}=await ct(t,e),{teams:f=[]}=c;let a;return r?a=f.filter(l=>l!==T):a=[T],{isAuthenticated:r,idpAccessToken:n,teams:a,claims:c}}const L=new WeakMap;function Vt(t,e,r={},n=!1){const s={user:e,rbacConfig:r,requiresLogin:n,denied:!1},o=x(t,s);return s.denied?I(o):o===t?t:(L.has(t)||L.set(t,o),L.get(t))}function x(t,e){if(!t)return t;if(Array.isArray(t)){let r;for(let n=0;n<t.length;n++){const s=t[n],o=x(s,e);!r&&(o!==s||o===void 0)&&(r=t.slice(0,n)),r&&o!==void 0&&r.push(o)}return r??t}if(typeof t=="object"){if(!y(t,e.user,e.rbacConfig,e.requiresLogin)){e.denied=!0;return}const r=Object.getPrototypeOf(t);let n=r!==Object.prototype&&r!==null;const s={};for(const o in t){if(o===g||o===E){n=!0;continue}if(M.has(o)){s[o]=t[o];continue}let c=x(t[o],e);if(!t.link&&(o==="items"||o==="menu"&&t.type==="tab")&&Array.isArray(c)&&c.length===0&&t[o].length!==0)return;o==="paths"&&mt(c)&&(c=ut(c)),c===void 0?n=!0:(n||=c!==t[o],s[o]=c)}return n?s:t}return t}function qt(t){return typeof t=="string"?t.split(" ").filter(Boolean):Array.isArray(t)?t.map(e=>e.toString()):[]}function Jt(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]].concat(t.localeFolders.map(f=>[o.startsWith("/")?`/${f.toLocaleLowerCase()}${o}`:O.posix.join(t.localizationFolder,f,o),c]))),s=Object.fromEntries(n);return{...e,content:s}}async function Qt(t,e){if(!e)return{};const r={},n=new Set(t.scan().flatMap(({relativePath:s})=>{const{versionFolderPath:o}=Q(s)||{},c=O.dirname(s);return o?[o,c]:c}));for(const s of n)r[Z(s)]=s;return r}const m=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function mt(t){return m(t)&&Object.keys(t).length>0}function I(t){if(Array.isArray(t))return t.map(I);if(!t||typeof t!="object")return t;const e={};for(const r in t)e[r]=M.has(r)?t[r]:I(t[r]);return e}function ut(t){const e=r=>m(r)&&Object.keys(r).length===0;return Object.values(t).some(e)?Object.fromEntries(Object.entries(t).filter(([,r])=>!e(r))):t}function pt(t){return t?t.split("/").filter(Boolean).some(r=>r.startsWith(".")):!1}const ht=t=>{if(t&&m(t)&&("content"in t&&m(t.content)||"platform"in t&&m(t.platform)||"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},Xt=async t=>{if(t){if(Object.keys(t).length===0)return{};if(ht(t))return dt(t);await X.panicOnContentError(`You are using an incorrect format of ${v("rbac:")} configuration. See: https://redocly.com/docs/realm/access`)}},dt=t=>{const e={...t};if(e.content){const r={};for(const n in e.content)if(e.content[n]!==void 0){const s=D(n);r[s]=e.content[n]}e.content=r}return e};function vt(t,e){const r=t.fsPath,n=t.slug,s=[],o=et(e)&&(r||n)?ot(e,[r,n].filter(tt)):null;if(o){const f=e?.teamNamePatterns?.map(a=>a.replace("{teamPathSegment}",o.teamPathSegment).replace("{projectRole}","read"))??[];s.push(...f)}const c=k(o?{content:{...nt(e),...e.content}}:e,t);return s.push(...Et(c)),Rt(e,s)}function Et(t){if(!t)return[];const e=[],r=p in t?{authenticated:t[p],anonymous:t[p]}:{};for(const[n,s]of Object.entries({...r,...t}))s.toLowerCase()!=="none"&&n!==p&&e.push(n);return e}function Rt(t,e){return e.map(n=>st(t,n)??{teamName:n}).map(n=>n.projectRole&&n.projectRole!=="READ"?n.teamName?.toLowerCase().replace(n.projectRole?.toLowerCase?.()??"","read")??"":n.teamName?.toLowerCase()??"")}export{b as PROJECT_ROLES_ORDERED_BY_ACCESS_LEVEL,Jt as applyL10nToRbacConfig,Ht as areAnyPagesOpenToAnonymous,Gt as canAccessAsset,y as canAccessResource,zt as canDownloadApiDefinition,Rt as expandTeamsForRead,Et as extractTeamsFromScopeItems,Vt as filterDataByAccessDeep,Kt as getAuthDetailsFromCookies,$t as getHigherRole,vt as getRbacTeamsListForResource,k as getScopeItemsForResource,ht as isRbacConfigValid,Yt as isResourcePubliclyAccessible,dt as normalizeRbacConfig,Xt as parseRbacConfig,qt as parseTeamClaimToArray,Qt as resolveDirectoryHashes};
@@ -9,7 +9,6 @@ export type McpContextPayload = {
9
9
  mcpSessionId: string;
10
10
  mcpCodeChallenge?: string | null;
11
11
  mcpCodeChallengeMethod?: string | null;
12
- mcpClientName?: string | null;
13
12
  timestamp: number;
14
13
  };
15
14
  export declare const SUPPORTED_MCP_GRANT_TYPES: readonly ['authorization_code', 'refresh_token'];
@@ -1 +1 @@
1
- import{getCookie as v}from"hono/cookie";import{createHash as G,timingSafeEqual as se}from"node:crypto";import{ulid as ae}from"ulid";import{isRedoclySso as ce,isOidcProviderConfig as O,createMcpAuthorizationCode as de,verifyMcpAuthorizationCode as pe,createMcpRefreshToken as B,verifyMcpRefreshToken as ue,createMcpSessionResource as M,oidcRefreshTokenGrant as le,getOidcMetadata as _e,getUserParamsFromCookies as fe,idTokenIsForThisProject as he}from"../../auth.js";import{isMcpContentProtected as U}from"../../../plugins/mcp/auth/auth-handlers.js";import{resolveSiteBranding as me}from"../../../plugins/mcp/handlers/credentials-page/site-branding.js";import{SUPPORTED_MCP_SCOPES as E}from"../../../plugins/mcp/constants.js";import{AUTH_URL as ge,JWT_SECRET_KEY as m,MCP_ACCESS_TOKEN_TTL_SEC as b,MCP_CLAIMS_ONLY_SESSION_LIFETIME_SEC as K,MCP_REFRESH_SESSION_LIFETIME_SEC as Ce}from"../../../constants/common.js";import{ServerRoutes as I}from"../../../../constants/api.js";import{AuthCookieNames as A}from"../../../../constants/common.js";import{withPathPrefix as w}from"@redocly/theme/core/utils";import{telemetry as y}from"../../../telemetry/index.js";import{envConfig as q}from"../../../config/env-config.js";import{hasProjectDatabase as j}from"../../../providers/database/has-project-database.js";import*as C from"../../jwt/jwt.js";import{InternalTokenTypes as L,McpAccessTokenMarker as N}from"../../jwt/token-types.js";import{AlgorithmTypes as R,JwtAlgorithmNotImplemented as Te,JwtTokenExpired as ke,JwtTokenInvalid as Se,JwtTokenNotBefore as Ie,JwtTokenSignatureMismatched as we}from"../../jwt/types.js";import{getRequestOrigin as D}from"../../utils/get-request-origin.js";import{encryptClaimValue as J}from"../../../utils/crypto/encrypt-claim-value.js";import{decryptAesGcm as Me}from"../../../utils/crypto/decrypt-aes-gcm.js";import{encryptAesGcm as V}from"../../../utils/crypto/encrypt-aes-gcm.js";import{fetchClientMetadataDocument as Ee,isClientMetadataDocumentUrl as z,isLoopbackRedirect as W,isRedirectUriRegistered as ye}from"./mcp-client-metadata.js";import{CONSENT_PAGE_HEADERS as Y,MCP_CONSENT_TTL_SEC as Ae,consentInvalidPage as Re,consentPage as Pe}from"./mcp-consent-page.js";import{MCP_CONSENT_MEMORY_DAYS as ve,hasConsent as Oe,redeemAuthorizationCode as Ue,redeemRefreshToken as Le,saveConsent as Ne}from"./mcp-oauth-store.js";const s=(r,e,t=200,n)=>r.json(e,t,{"Content-Type":"application/json",...n??{}}),$=new Set(["S256"]),F=["authorization_code","refresh_token"];function De(r,e,t){if(!r||!$.has(e||""))return!1;const n=G("sha256").update(t).digest("base64url"),i=Buffer.from(n),a=Buffer.from(r);return i.length!==a.length?!1:se(i,a)}async function He(r){const e=Math.floor(Date.now()/1e3);return C.sign({type:L.MCP_CONTEXT,...r,iat:e,exp:e+600},m,R.HS256)}async function be(r){await C.verify(r,m,R.HS256);const{payload:e}=C.decode(r);if(e.type!==L.MCP_CONTEXT)throw new Error("Invalid context token type");return e}function gr(r){return async e=>{if(!U(r))return s(e,{error:"not_found"},404);if(e.req.method!=="GET")return s(e,{error:"Method not allowed"},405,{Allow:"GET"});const t=D(e);return s(e,{resource:`${t}${w("/mcp")}`,authorization_servers:[t],bearer_methods_supported:["header"],resource_documentation:`${t}${I.MCP_OAUTH_AUTHORIZATION_SERVER}`,scopes_supported:[...E],bearer_token_types_supported:["Bearer"]},200,{"Access-Control-Allow-Origin":"*"})}}function Cr(r){return async e=>{if(!U(r))return s(e,{error:"not_found"},404);const t=D(e);return s(e,{issuer:t,authorization_endpoint:`${t}${w(I.MCP_AUTHORIZATION)}`,token_endpoint:`${t}${w(I.MCP_TOKEN_PORTAL)}`,scopes_supported:[...E],registration_endpoint:`${t}${w(I.MCP_DYNAMIC_CLIENT_REGISTRATION)}`,response_types_supported:["code"],grant_types_supported:[...F],subject_types_supported:["public"],id_token_signing_alg_values_supported:["RS256"],code_challenge_methods_supported:["S256"],token_endpoint_auth_methods_supported:["none"],client_id_metadata_document_supported:!0},200,{"Access-Control-Allow-Origin":"*"})}}function Tr(r){return async e=>{if(!U(r))return s(e,{error:"not_found"},404);if(e.req.method!=="POST")return s(e,{error:"Method not allowed"},405);try{return s(e,{client_id:q.OAUTH_CLIENT_ID||"",client_name:"MCP Client",redirect_uris:[],grant_types:[...F],response_types:["code"],scope:E.join(" "),subject_type:"public",token_endpoint_auth_method:"none",created_at:new Date().toISOString(),updated_at:new Date().toISOString()},201,{"Access-Control-Allow-Origin":"*"})}catch(t){return s(e,{error:"invalid_request",error_description:t?.message||"Unable to register client"},500,{"Access-Control-Allow-Origin":"*"})}}}const qe=new Set(["http:","https:","ws:","wss:","ftp:","file:"]),je=new Set(["javascript:","data:","blob:","about:","vbscript:","intent:","chrome:","view-source:","ms-msdt:","ms-appx-web:"]),ze=2048,$e=/[\s\p{Cc}]/u;function Z(r){return r?Ce:K}function X(r){if(!r||r.length>ze||r.includes("#")||$e.test(r))return;const e=URL.parse(r);if(e){if(e.protocol==="https:"||W(e))return r.toLowerCase().startsWith(`${e.protocol}//`)?e:void 0;if(!(qe.has(e.protocol)||je.has(e.protocol)))return e}}function Q(r){const e=r||{},t=Object.keys(e),n=t.find(a=>O(e[a])&&ce(e[a])),i=t.find(a=>O(e[a]));return n||i||t[0]}function kr(r){return async e=>{if(!U(r))return s(e,{error:"not_found"},404);const t=new URL(e.req.url),{searchParams:n}=t,i=n.get("redirect_uri"),a=n.get("client_id"),c=n.get("code_challenge"),o=n.get("code_challenge_method"),p=ae();if(!i||!X(i))return s(e,{error:"invalid_request",error_description:"redirect_uri must be an https URL, a loopback http URL, or a private-use scheme"},400);if(!c)return s(e,{error:"invalid_request",error_description:"code_challenge is required"},400);if(!$.has(o||""))return s(e,{error:"invalid_request",error_description:`Unsupported code_challenge_method. Supported: ${[...$].join(", ")}`},400);let d;if(z(a))try{const u=await Ee(a);if(d=u.client_name,!ye(i,u.redirect_uris))return s(e,{error:"invalid_request",error_description:"redirect_uri is not registered for this client"},400)}catch(u){const h=u instanceof Error?u.message:String(u);return s(e,{error:"invalid_client",error_description:`Unable to resolve client metadata document: ${h}`},400)}y.sendMcpAuthorizationStartedMessage([{...M(p),redirect_uri:i||null}]);const l=D(e),k={isMcpFlow:!0,originalRedirectUri:i,mcpClientId:a,mcpState:n.get("state"),mcpSessionId:p,mcpCodeChallenge:c,mcpCodeChallengeMethod:o,mcpClientName:d,timestamp:Date.now()};try{const u=await He(k),h=new URL(w(I.IDP_LOGIN),l);h.searchParams.set("redirectTo",`${I.MCP_CALLBACK}/${u}`);const _=Q(r.getConfig().ssoDirect);return _?(h.searchParams.set("idpId",_),e.redirect(h.toString())):s(e,{error:"not_found"},404)}catch(u){const h=u instanceof Error?u.message:String(u),_=u instanceof Error?u.stack:String(u);y.sendMcpAuthorizationFailedMessage([{...M(p),error:h,error_details:_}]);const S=new URL(w(`${ge}/oauth2/auth`));return S.search=n.toString(),e.redirect(S.toString())}}}async function x(r){const e=Math.floor(Date.now()/1e3),t=r.ttlSec?e+r.ttlSec:Math.min(typeof r.claims.exp=="number"?r.claims.exp:1/0,e+b);return{accessToken:await C.sign({...r.claims,[N.CLAIM]:N.VALUE,...r.idpId?{idpId:r.idpId}:{},...r.idpAccessTokenEnc?{idp_access_token:r.idpAccessTokenEnc}:{},...r.ttlSec?{iat:e}:{},exp:t},m,R.HS256,r.kid),expiresIn:Math.max(t-e,0)}}async function Fe(r,e,t){const n=T=>s(r,{error:"invalid_grant",error_description:T},400),i=r.get("logger"),a=t.get("refresh_token"),c=t.get("client_id")||void 0;if(!a)return s(r,{error:"invalid_request",error_description:"refresh_token is required"},400);let o;try{o=await ue(a)}catch(T){return i?.warn("MCP refresh token rejected: %s",T instanceof Error?T.message:String(T)),n("Invalid refresh token")}if(c&&c!==o.client_id)return n("Client mismatch");const p=o.idp_id?e.getConfig().ssoDirect?.[o.idp_id]:void 0;let d,l,k=o.idp_access_token_enc,u=o.idp_refresh_token_enc;if(o.idp_refresh_token_enc){let T;try{T=Me(o.idp_refresh_token_enc,m)}catch{return n("Invalid refresh token")}if(!o.idp_id||!O(p))return n("Unknown identity provider");let f;try{const g=await _e(o.idp_id,p);if(!g?.token_endpoint)return n("Identity provider has no token endpoint");f=await le(g.token_endpoint,T,p)}catch(g){return i?.warn("MCP refresh failed to reach the IdP token endpoint: %s",g instanceof Error?g.message:String(g)),s(r,{error:"server_error",error_description:"Failed to refresh session"},500)}if(f.error||!(f.id_token||f.access_token))return i?.warn("MCP refresh rejected by IdP: %s",f.error||"empty token response"),n("Refresh rejected by identity provider");if(f.refresh_token&&(u=V(f.refresh_token,m)),f.access_token&&(k=J(f.access_token,m)),f.id_token){try{const g=C.decode(f.id_token);d=g.payload,l=g.header.kid}catch{return n("Invalid token response from identity provider")}if(d.iss!==o.claims.iss||d.sub!==o.claims.sub)return i?.warn("MCP refresh rejected: the id_token names another issuer or subject"),n("Invalid refresh token")}}const h=Math.min(O(p)&&p.tokenExpirationTime||b,b),_=d??o.claims;if(!he(_,p))return i?.warn("MCP refresh rejected: the id_token was issued for another project"),n("Invalid refresh token");const S=d||typeof _.iat!="number"?o.session_exp:Math.min(o.session_exp,_.iat+K);if(S<=Math.floor(Date.now()/1e3))return i?.warn("MCP refresh rejected: the claims snapshot is older than the claims-only window"),n("Refresh token expired");if(j()&&!await Le(await e.getKv(),a,o.exp))return i?.warn("MCP refresh rejected: the refresh token was already used"),n("Refresh token already used");const P=await x({claims:_,kid:l,idpId:o.idp_id,idpAccessTokenEnc:k,ttlSec:d?void 0:h}),ie=await B({clientId:o.client_id,idpId:o.idp_id,claims:_,idpAccessTokenEnc:k,idpRefreshTokenEnc:u,sessionExp:S});return s(r,{access_token:P.accessToken,token_type:"Bearer",expires_in:P.expiresIn,refresh_token:ie,scope:E.join(" ")},200,{"Cache-Control":"no-store",Pragma:"no-cache"})}function Sr(r){return async e=>{if(e.req.method!=="POST")return s(e,{error:"Method not allowed"},405);try{const t=await e.req.formData(),n=t.get("grant_type"),i=t.get("code"),a=t.get("redirect_uri")||void 0,c=t.get("code_verifier")||void 0;if(!F.includes(n))return s(e,{error:"invalid_request",error_description:"Invalid grant type"},400);if(n==="refresh_token")return await Fe(e,r,t);if(!i)return s(e,{error:"invalid_request",error_description:"Missing authorization code"},400);try{const o=await pe(i);if(a&&a!==o.redirect_uri)return s(e,{error:"invalid_grant",error_description:"redirect_uri mismatch"},400);if(!c)return s(e,{error:"invalid_grant",error_description:"code_verifier required"},400);if(!De(o.code_challenge,o.code_challenge_method,c))return s(e,{error:"invalid_grant",error_description:"code_verifier mismatch"},400);if(q.OAUTH_CLIENT_ID&&o.client_id&&!z(o.client_id)&&o.client_id!==q.OAUTH_CLIENT_ID)return s(e,{error:"invalid_client",error_description:"Client mismatch"},400);const p=o.id_token;if(typeof p!="string"||p.length===0)return s(e,{error:"invalid_grant",error_description:"Missing id_token in authorization code"},400);const d=await ee(p,r.getConfig().ssoDirect);if(!d)return s(e,{error:"invalid_grant",error_description:"Invalid authorization code"},400);if(j()&&!await Ue(await r.getKv(),i,o.exp))return s(e,{error:"invalid_grant",error_description:"Authorization code already used"},400);const l=o.idp_access_token_enc,{accessToken:k,expiresIn:u}=await x({claims:d.payload,kid:d.kid,idpId:o.idp_id,idpAccessTokenEnc:l}),_=Math.floor(Date.now()/1e3)+Z(!!o.idp_refresh_token_enc),S=await B({clientId:o.client_id,idpId:o.idp_id,claims:d.payload,idpAccessTokenEnc:l,idpRefreshTokenEnc:o.idp_refresh_token_enc,sessionExp:_}),P={access_token:k,token_type:"Bearer",expires_in:u,refresh_token:S,scope:E.join(" ")};return s(e,P,200,{"Cache-Control":"no-store",Pragma:"no-cache"})}catch(o){return e.get("logger")?.warn("MCP token exchange failed: %s",o instanceof Error?o.message:String(o)),s(e,{error:"invalid_grant",error_description:"Invalid authorization code"},400)}}catch(t){const n=t instanceof Error?t.message:String(t);return s(e,{error:"server_error",error_description:"Failed to process token request",error_details:n},500)}}}async function ee(r,e){const t=await fe(e||{},{[A.AUTHORIZATION]:r});if(t.isAuthenticated!==!0)return;const{payload:n,header:i}=C.decode(r);if(n[N.CLAIM]!==N.VALUE)return{payload:n,kid:i.kid,idpId:typeof t.idpId=="string"?t.idpId:void 0}}function H(r){return G("sha256").update(r).digest("base64url")}async function Ge(r){const e=Math.floor(Date.now()/1e3);return C.sign({type:L.MCP_CONSENT,session_hash:H(r.sessionToken),context_hash:H(r.contextToken),iat:e,exp:e+Ae},m,R.HS256)}async function Be(r,e){try{await C.verify(r,m,R.HS256)}catch{return!1}const{payload:t}=C.decode(r);return t.type===L.MCP_CONSENT&&t.session_hash===H(e.sessionToken)&&t.context_hash===H(e.contextToken)}function re(r,e){return async t=>{const n=new URL(t.req.url);let i=n.searchParams.get("context");if(!i&&n.pathname.startsWith(w(`${I.MCP_CALLBACK}/`))){const c=n.pathname.split("/");i=c[c.length-1]}if(!i)return t.text("Missing context parameter",400);let a=null;try{const c=await be(i);a=c.mcpSessionId||null;const o=c.originalRedirectUri,p=X(o);if(!c.isMcpFlow||!o||!p)throw new Error("Invalid MCP context");const d=v(t,A.AUTHORIZATION),l=d?await ee(d,r.getConfig().ssoDirect):void 0;return!d||!l?(y.sendMcpAuthorizationFailedMessage([{...M(a),error:"Authentication required",error_details:null}]),t.text("Authentication required",401)):await e(t,{contextToken:i,mcpContext:c,redirectUri:o,redirectUrl:p,sessionToken:d,session:l})}catch(c){const o=Ve(c);return y.sendMcpAuthorizationFailedMessage([{...M(a),...o}]),t.text(`Invalid MCP callback: ${o.error}`,400)}}}async function te(r,e,{mcpContext:t,redirectUri:n,redirectUrl:i,sessionToken:a,session:c}){const o=v(r,A.IDP_ACCESS_TOKEN),p=v(r,A.IDP_REFRESH_TOKEN),d=await de({idToken:a,idpId:c.idpId??Q(e.getConfig().ssoDirect),idpAccessTokenEnc:o?J(o,m):void 0,idpRefreshTokenEnc:p?V(p,m):void 0,clientId:t.mcpClientId||"",redirectUri:n,codeChallenge:t.mcpCodeChallenge||void 0,codeChallengeMethod:t.mcpCodeChallengeMethod||void 0,ttlSec:600}),l=new URL(i);return l.searchParams.set("code",d),t.mcpState&&l.searchParams.set("state",t.mcpState),y.sendMcpAuthorizationCompletedMessage([{...M(t.mcpSessionId||null),redirect_uri:n}]),r.redirect(l.toString())}function Ke(r,{mcpContext:e,redirectUrl:t}){const n=new URL(t);return n.searchParams.set("error","access_denied"),e.mcpState&&n.searchParams.set("state",e.mcpState),y.sendMcpAuthorizationFailedMessage([{...M(e.mcpSessionId||null),error:"access_denied",error_details:null}]),r.redirect(n.toString())}function Je({payload:r}){return[r.email,r.name,r.sub].find(e=>typeof e=="string"&&e.length>0)}function ne({mcpContext:r,redirectUri:e,session:t}){const{sub:n}=t.payload;if(!(!j()||typeof n!="string"||n.length===0))return{idpId:t.idpId,subject:n,clientId:r.mcpClientId||"",redirectUri:e}}function oe(r,e){const{seo:t,colorMode:n}=e.getConfig(),{logo:i}=e.getGlobalData();return{...me({seo:t,logo:i,colorMode:n}),host:new URL(D(r)).host}}function Ir(r){return re(r,async(e,t)=>{const n=ne(t);if(W(t.redirectUrl)||n&&await Oe(await r.getKv(),n))return te(e,r,t);const{mcpClientId:i,mcpClientName:a}=t.mcpContext,c=Pe({site:oe(e,r),user:Je(t.session),clientName:a||void 0,clientIdHost:z(i)?new URL(i).host:void 0,redirectUrl:t.redirectUrl,scopes:E,accessLifetimeDays:Z(!!v(e,A.IDP_REFRESH_TOKEN))/(1440*60),rememberDays:n?ve:void 0,consentToken:await Ge(t)});return new Response(c,{status:200,headers:Y})})}function wr(r){return re(r,async(e,t)=>{const n=await e.req.formData(),i=n.get("consent");if(typeof i!="string"||!await Be(i,t))return new Response(Re(oe(e,r)),{status:403,headers:Y});if(n.get("decision")==="allow"){const a=ne(t);return a&&await Ne(await r.getKv(),a),te(e,r,t)}return Ke(e,t)})}function Ve(r){return r instanceof Error&&[Te,ke,Se,Ie,we].some(e=>r instanceof e)?{error:r.name,error_details:null}:r instanceof Error?{error:r.message,error_details:r.stack??null}:{error:String(r),error_details:null}}export{F as SUPPORTED_MCP_GRANT_TYPES,He as createMcpContextToken,kr as mcpAuthorizationHandler,Ir as mcpCallbackHandler,wr as mcpConsentHandler,Tr as mcpDynamicClientRegistrationHandler,Cr as mcpOAuthAuthorizationServerHandler,gr as mcpOAuthProtectedResourceHandler,Sr as mcpTokenPortalHandler,Q as resolveMcpIdpId,be as verifyAndParseMcpContextToken,De as verifyPkce};
1
+ import{getCookie as v}from"hono/cookie";import{createHash as G,timingSafeEqual as se}from"node:crypto";import{ulid as ae}from"ulid";import{isRedoclySso as ce,isOidcProviderConfig as O,createMcpAuthorizationCode as de,verifyMcpAuthorizationCode as pe,createMcpRefreshToken as B,verifyMcpRefreshToken as ue,createMcpSessionResource as I,oidcRefreshTokenGrant as le,getOidcMetadata as _e,getUserParamsFromCookies as fe,idTokenIsForThisProject as he}from"../../auth.js";import{isMcpContentProtected as U}from"../../../plugins/mcp/auth/auth-handlers.js";import{resolveSiteBranding as me}from"../../../plugins/mcp/handlers/credentials-page/site-branding.js";import{SUPPORTED_MCP_SCOPES as E}from"../../../plugins/mcp/constants.js";import{AUTH_URL as ge,JWT_SECRET_KEY as m,MCP_ACCESS_TOKEN_TTL_SEC as b,MCP_CLAIMS_ONLY_SESSION_LIFETIME_SEC as K,MCP_REFRESH_SESSION_LIFETIME_SEC as Ce}from"../../../constants/common.js";import{ServerRoutes as S}from"../../../../constants/api.js";import{AuthCookieNames as y}from"../../../../constants/common.js";import{withPathPrefix as w}from"@redocly/theme/core/utils";import{telemetry as M}from"../../../telemetry/index.js";import{envConfig as j}from"../../../config/env-config.js";import{hasProjectDatabase as q}from"../../../providers/database/has-project-database.js";import*as C from"../../jwt/jwt.js";import{InternalTokenTypes as L,McpAccessTokenMarker as D}from"../../jwt/token-types.js";import{AlgorithmTypes as A,JwtAlgorithmNotImplemented as Te,JwtTokenExpired as ke,JwtTokenInvalid as Se,JwtTokenNotBefore as we,JwtTokenSignatureMismatched as Ie}from"../../jwt/types.js";import{getRequestOrigin as N}from"../../utils/get-request-origin.js";import{encryptClaimValue as J}from"../../../utils/crypto/encrypt-claim-value.js";import{decryptAesGcm as Ee}from"../../../utils/crypto/decrypt-aes-gcm.js";import{encryptAesGcm as V}from"../../../utils/crypto/encrypt-aes-gcm.js";import{fetchClientMetadataDocument as Me,isClientMetadataDocumentUrl as z,isLoopbackRedirect as W,isRedirectUriRegistered as ye}from"./mcp-client-metadata.js";import{CONSENT_PAGE_HEADERS as Y,MCP_CONSENT_TTL_SEC as Ae,consentInvalidPage as Re,consentPage as Pe}from"./mcp-consent-page.js";import{MCP_CONSENT_MEMORY_DAYS as ve,hasConsent as Oe,redeemAuthorizationCode as Ue,redeemRefreshToken as Le,saveConsent as De}from"./mcp-oauth-store.js";const s=(r,e,t=200,n)=>r.json(e,t,{"Content-Type":"application/json",...n??{}}),$=new Set(["S256"]),F=["authorization_code","refresh_token"];function Ne(r,e,t){if(!r||!$.has(e||""))return!1;const n=G("sha256").update(t).digest("base64url"),i=Buffer.from(n),a=Buffer.from(r);return i.length!==a.length?!1:se(i,a)}async function He(r){const e=Math.floor(Date.now()/1e3);return C.sign({type:L.MCP_CONTEXT,...r,iat:e,exp:e+600},m,A.HS256)}async function be(r){await C.verify(r,m,A.HS256);const{payload:e}=C.decode(r);if(e.type!==L.MCP_CONTEXT)throw new Error("Invalid context token type");return e}function gr(r){return async e=>{if(!U(r))return s(e,{error:"not_found"},404);if(e.req.method!=="GET")return s(e,{error:"Method not allowed"},405,{Allow:"GET"});const t=N(e);return s(e,{resource:`${t}${w("/mcp")}`,authorization_servers:[t],bearer_methods_supported:["header"],resource_documentation:`${t}${S.MCP_OAUTH_AUTHORIZATION_SERVER}`,scopes_supported:[...E],bearer_token_types_supported:["Bearer"]},200,{"Access-Control-Allow-Origin":"*"})}}function Cr(r){return async e=>{if(!U(r))return s(e,{error:"not_found"},404);const t=N(e);return s(e,{issuer:t,authorization_endpoint:`${t}${w(S.MCP_AUTHORIZATION)}`,token_endpoint:`${t}${w(S.MCP_TOKEN_PORTAL)}`,scopes_supported:[...E],registration_endpoint:`${t}${w(S.MCP_DYNAMIC_CLIENT_REGISTRATION)}`,response_types_supported:["code"],grant_types_supported:[...F],subject_types_supported:["public"],id_token_signing_alg_values_supported:["RS256"],code_challenge_methods_supported:["S256"],token_endpoint_auth_methods_supported:["none"],client_id_metadata_document_supported:!0},200,{"Access-Control-Allow-Origin":"*"})}}function Tr(r){return async e=>{if(!U(r))return s(e,{error:"not_found"},404);if(e.req.method!=="POST")return s(e,{error:"Method not allowed"},405);try{return s(e,{client_id:j.OAUTH_CLIENT_ID||"",client_name:"MCP Client",redirect_uris:[],grant_types:[...F],response_types:["code"],scope:E.join(" "),subject_type:"public",token_endpoint_auth_method:"none",created_at:new Date().toISOString(),updated_at:new Date().toISOString()},201,{"Access-Control-Allow-Origin":"*"})}catch(t){return s(e,{error:"invalid_request",error_description:t?.message||"Unable to register client"},500,{"Access-Control-Allow-Origin":"*"})}}}const je=new Set(["http:","https:","ws:","wss:","ftp:","file:"]),qe=new Set(["javascript:","data:","blob:","about:","vbscript:","intent:","chrome:","view-source:","ms-msdt:","ms-appx-web:"]),ze=2048,$e=/[\s\p{Cc}]/u;function Z(r){return r?Ce:K}function X(r){if(!r||r.length>ze||r.includes("#")||$e.test(r))return;const e=URL.parse(r);if(e){if(e.protocol==="https:"||W(e))return r.toLowerCase().startsWith(`${e.protocol}//`)?e:void 0;if(!(je.has(e.protocol)||qe.has(e.protocol)))return e}}function Q(r){const e=r||{},t=Object.keys(e),n=t.find(a=>O(e[a])&&ce(e[a])),i=t.find(a=>O(e[a]));return n||i||t[0]}function kr(r){return async e=>{if(!U(r))return s(e,{error:"not_found"},404);const t=new URL(e.req.url),{searchParams:n}=t,i=n.get("redirect_uri"),a=n.get("client_id"),d=n.get("code_challenge"),o=n.get("code_challenge_method"),c=ae();if(!i||!X(i))return s(e,{error:"invalid_request",error_description:"redirect_uri must be an https URL, a loopback http URL, or a private-use scheme"},400);if(!d)return s(e,{error:"invalid_request",error_description:"code_challenge is required"},400);if(!$.has(o||""))return s(e,{error:"invalid_request",error_description:`Unsupported code_challenge_method. Supported: ${[...$].join(", ")}`},400);M.sendMcpAuthorizationStartedMessage([{...I(c),redirect_uri:i||null}]);const p=N(e),u={isMcpFlow:!0,originalRedirectUri:i,mcpClientId:a,mcpState:n.get("state"),mcpSessionId:c,mcpCodeChallenge:d,mcpCodeChallengeMethod:o,timestamp:Date.now()};try{const l=await He(u),f=new URL(w(S.IDP_LOGIN),p);f.searchParams.set("redirectTo",`${S.MCP_CALLBACK}/${l}`);const k=Q(r.getConfig().ssoDirect);return k?(f.searchParams.set("idpId",k),e.redirect(f.toString())):s(e,{error:"not_found"},404)}catch(l){const f=l instanceof Error?l.message:String(l),k=l instanceof Error?l.stack:String(l);M.sendMcpAuthorizationFailedMessage([{...I(c),error:f,error_details:k}]);const h=new URL(w(`${ge}/oauth2/auth`));return h.search=n.toString(),e.redirect(h.toString())}}}async function x(r){const e=Math.floor(Date.now()/1e3),t=r.ttlSec?e+r.ttlSec:Math.min(typeof r.claims.exp=="number"?r.claims.exp:1/0,e+b);return{accessToken:await C.sign({...r.claims,[D.CLAIM]:D.VALUE,...r.idpId?{idpId:r.idpId}:{},...r.idpAccessTokenEnc?{idp_access_token:r.idpAccessTokenEnc}:{},...r.ttlSec?{iat:e}:{},exp:t},m,A.HS256,r.kid),expiresIn:Math.max(t-e,0)}}async function Fe(r,e,t){const n=T=>s(r,{error:"invalid_grant",error_description:T},400),i=r.get("logger"),a=t.get("refresh_token"),d=t.get("client_id")||void 0;if(!a)return s(r,{error:"invalid_request",error_description:"refresh_token is required"},400);let o;try{o=await ue(a)}catch(T){return i?.warn("MCP refresh token rejected: %s",T instanceof Error?T.message:String(T)),n("Invalid refresh token")}if(d&&d!==o.client_id)return n("Client mismatch");const c=o.idp_id?e.getConfig().ssoDirect?.[o.idp_id]:void 0;let p,u,l=o.idp_access_token_enc,f=o.idp_refresh_token_enc;if(o.idp_refresh_token_enc){let T;try{T=Ee(o.idp_refresh_token_enc,m)}catch{return n("Invalid refresh token")}if(!o.idp_id||!O(c))return n("Unknown identity provider");let _;try{const g=await _e(o.idp_id,c);if(!g?.token_endpoint)return n("Identity provider has no token endpoint");_=await le(g.token_endpoint,T,c)}catch(g){return i?.warn("MCP refresh failed to reach the IdP token endpoint: %s",g instanceof Error?g.message:String(g)),s(r,{error:"server_error",error_description:"Failed to refresh session"},500)}if(_.error||!(_.id_token||_.access_token))return i?.warn("MCP refresh rejected by IdP: %s",_.error||"empty token response"),n("Refresh rejected by identity provider");if(_.refresh_token&&(f=V(_.refresh_token,m)),_.access_token&&(l=J(_.access_token,m)),_.id_token){try{const g=C.decode(_.id_token);p=g.payload,u=g.header.kid}catch{return n("Invalid token response from identity provider")}if(p.iss!==o.claims.iss||p.sub!==o.claims.sub)return i?.warn("MCP refresh rejected: the id_token names another issuer or subject"),n("Invalid refresh token")}}const k=Math.min(O(c)&&c.tokenExpirationTime||b,b),h=p??o.claims;if(!he(h,c))return i?.warn("MCP refresh rejected: the id_token was issued for another project"),n("Invalid refresh token");const R=p||typeof h.iat!="number"?o.session_exp:Math.min(o.session_exp,h.iat+K);if(R<=Math.floor(Date.now()/1e3))return i?.warn("MCP refresh rejected: the claims snapshot is older than the claims-only window"),n("Refresh token expired");if(q()&&!await Le(await e.getKv(),a,o.exp))return i?.warn("MCP refresh rejected: the refresh token was already used"),n("Refresh token already used");const P=await x({claims:h,kid:u,idpId:o.idp_id,idpAccessTokenEnc:l,ttlSec:p?void 0:k}),ie=await B({clientId:o.client_id,idpId:o.idp_id,claims:h,idpAccessTokenEnc:l,idpRefreshTokenEnc:f,sessionExp:R});return s(r,{access_token:P.accessToken,token_type:"Bearer",expires_in:P.expiresIn,refresh_token:ie,scope:E.join(" ")},200,{"Cache-Control":"no-store",Pragma:"no-cache"})}function Sr(r){return async e=>{if(e.req.method!=="POST")return s(e,{error:"Method not allowed"},405);try{const t=await e.req.formData(),n=t.get("grant_type"),i=t.get("code"),a=t.get("redirect_uri")||void 0,d=t.get("code_verifier")||void 0;if(!F.includes(n))return s(e,{error:"invalid_request",error_description:"Invalid grant type"},400);if(n==="refresh_token")return await Fe(e,r,t);if(!i)return s(e,{error:"invalid_request",error_description:"Missing authorization code"},400);try{const o=await pe(i);if(a&&a!==o.redirect_uri)return s(e,{error:"invalid_grant",error_description:"redirect_uri mismatch"},400);if(!d)return s(e,{error:"invalid_grant",error_description:"code_verifier required"},400);if(!Ne(o.code_challenge,o.code_challenge_method,d))return s(e,{error:"invalid_grant",error_description:"code_verifier mismatch"},400);if(j.OAUTH_CLIENT_ID&&o.client_id&&!z(o.client_id)&&o.client_id!==j.OAUTH_CLIENT_ID)return s(e,{error:"invalid_client",error_description:"Client mismatch"},400);const c=o.id_token;if(typeof c!="string"||c.length===0)return s(e,{error:"invalid_grant",error_description:"Missing id_token in authorization code"},400);const p=await ee(c,r.getConfig().ssoDirect);if(!p)return s(e,{error:"invalid_grant",error_description:"Invalid authorization code"},400);if(q()&&!await Ue(await r.getKv(),i,o.exp))return s(e,{error:"invalid_grant",error_description:"Authorization code already used"},400);const u=o.idp_access_token_enc,{accessToken:l,expiresIn:f}=await x({claims:p.payload,kid:p.kid,idpId:o.idp_id,idpAccessTokenEnc:u}),h=Math.floor(Date.now()/1e3)+Z(!!o.idp_refresh_token_enc),R=await B({clientId:o.client_id,idpId:o.idp_id,claims:p.payload,idpAccessTokenEnc:u,idpRefreshTokenEnc:o.idp_refresh_token_enc,sessionExp:h}),P={access_token:l,token_type:"Bearer",expires_in:f,refresh_token:R,scope:E.join(" ")};return s(e,P,200,{"Cache-Control":"no-store",Pragma:"no-cache"})}catch(o){return e.get("logger")?.warn("MCP token exchange failed: %s",o instanceof Error?o.message:String(o)),s(e,{error:"invalid_grant",error_description:"Invalid authorization code"},400)}}catch(t){const n=t instanceof Error?t.message:String(t);return s(e,{error:"server_error",error_description:"Failed to process token request",error_details:n},500)}}}async function ee(r,e){const t=await fe(e||{},{[y.AUTHORIZATION]:r});if(t.isAuthenticated!==!0)return;const{payload:n,header:i}=C.decode(r);if(n[D.CLAIM]!==D.VALUE)return{payload:n,kid:i.kid,idpId:typeof t.idpId=="string"?t.idpId:void 0}}function H(r){return G("sha256").update(r).digest("base64url")}async function Ge(r){const e=Math.floor(Date.now()/1e3);return C.sign({type:L.MCP_CONSENT,session_hash:H(r.sessionToken),context_hash:H(r.contextToken),iat:e,exp:e+Ae},m,A.HS256)}async function Be(r,e){try{await C.verify(r,m,A.HS256)}catch{return!1}const{payload:t}=C.decode(r);return t.type===L.MCP_CONSENT&&t.session_hash===H(e.sessionToken)&&t.context_hash===H(e.contextToken)}function re(r,e){return async t=>{const n=new URL(t.req.url);let i=n.searchParams.get("context");if(!i&&n.pathname.startsWith(w(`${S.MCP_CALLBACK}/`))){const d=n.pathname.split("/");i=d[d.length-1]}if(!i)return t.text("Missing context parameter",400);let a=null;try{const d=await be(i);a=d.mcpSessionId||null;const o=d.originalRedirectUri,c=X(o);if(!d.isMcpFlow||!o||!c)throw new Error("Invalid MCP context");const p=v(t,y.AUTHORIZATION),u=p?await ee(p,r.getConfig().ssoDirect):void 0;return!p||!u?(M.sendMcpAuthorizationFailedMessage([{...I(a),error:"Authentication required",error_details:null}]),t.text("Authentication required",401)):await e(t,{contextToken:i,mcpContext:d,redirectUri:o,redirectUrl:c,sessionToken:p,session:u})}catch(d){const o=Ve(d);return M.sendMcpAuthorizationFailedMessage([{...I(a),...o}]),t.text(`Invalid MCP callback: ${o.error}`,400)}}}async function te(r,e,{mcpContext:t,redirectUri:n,redirectUrl:i,sessionToken:a,session:d}){const o=v(r,y.IDP_ACCESS_TOKEN),c=v(r,y.IDP_REFRESH_TOKEN),p=await de({idToken:a,idpId:d.idpId??Q(e.getConfig().ssoDirect),idpAccessTokenEnc:o?J(o,m):void 0,idpRefreshTokenEnc:c?V(c,m):void 0,clientId:t.mcpClientId||"",redirectUri:n,codeChallenge:t.mcpCodeChallenge||void 0,codeChallengeMethod:t.mcpCodeChallengeMethod||void 0,ttlSec:600}),u=new URL(i);return u.searchParams.set("code",p),t.mcpState&&u.searchParams.set("state",t.mcpState),M.sendMcpAuthorizationCompletedMessage([{...I(t.mcpSessionId||null),redirect_uri:n}]),r.redirect(u.toString())}function Ke(r,{mcpContext:e,redirectUrl:t}){const n=new URL(t);return n.searchParams.set("error","access_denied"),e.mcpState&&n.searchParams.set("state",e.mcpState),M.sendMcpAuthorizationFailedMessage([{...I(e.mcpSessionId||null),error:"access_denied",error_details:null}]),r.redirect(n.toString())}function Je({payload:r}){return[r.email,r.name,r.sub].find(e=>typeof e=="string"&&e.length>0)}function ne({mcpContext:r,redirectUri:e,session:t}){const{sub:n}=t.payload;if(!(!q()||typeof n!="string"||n.length===0))return{idpId:t.idpId,subject:n,clientId:r.mcpClientId||"",redirectUri:e}}function oe(r,e){const{seo:t,colorMode:n}=e.getConfig(),{logo:i}=e.getGlobalData();return{...me({seo:t,logo:i,colorMode:n}),host:new URL(N(r)).host}}function wr(r){return re(r,async(e,t)=>{const{mcpClientId:n}=t.mcpContext;let i;if(z(n)){const o=await Me(n).catch(c=>{const p=c instanceof Error?c.message:String(c);throw new Error(`Unable to resolve client metadata document: ${p}`)});if(!ye(t.redirectUri,o.redirect_uris))throw new Error("redirect_uri is not registered for this client");i=o.client_name}const a=ne(t);if(W(t.redirectUrl)||a&&await Oe(await r.getKv(),a))return te(e,r,t);const d=Pe({site:oe(e,r),user:Je(t.session),clientName:i,clientIdHost:z(n)?new URL(n).host:void 0,redirectUrl:t.redirectUrl,scopes:E,accessLifetimeDays:Z(!!v(e,y.IDP_REFRESH_TOKEN))/(1440*60),rememberDays:a?ve:void 0,consentToken:await Ge(t)});return new Response(d,{status:200,headers:Y})})}function Ir(r){return re(r,async(e,t)=>{const n=await e.req.formData(),i=n.get("consent");if(typeof i!="string"||!await Be(i,t))return new Response(Re(oe(e,r)),{status:403,headers:Y});if(n.get("decision")==="allow"){const a=ne(t);return a&&await De(await r.getKv(),a),te(e,r,t)}return Ke(e,t)})}function Ve(r){return r instanceof Error&&[Te,ke,Se,we,Ie].some(e=>r instanceof e)?{error:r.name,error_details:null}:r instanceof Error?{error:r.message,error_details:r.stack??null}:{error:String(r),error_details:null}}export{F as SUPPORTED_MCP_GRANT_TYPES,He as createMcpContextToken,kr as mcpAuthorizationHandler,wr as mcpCallbackHandler,Ir as mcpConsentHandler,Tr as mcpDynamicClientRegistrationHandler,Cr as mcpOAuthAuthorizationServerHandler,gr as mcpOAuthProtectedResourceHandler,Sr as mcpTokenPortalHandler,Q as resolveMcpIdpId,be as verifyAndParseMcpContextToken,Ne as verifyPkce};
@@ -1 +1 @@
1
- import{readFileSync as a}from"node:fs";import{MARKDOC_PARTIALS_DATA_KEY as f}from"../constants/common.js";import{resolveStoreConfig as l}from"../store-config.js";let s;function m(n,e){if(!e)return{entries:n};const o=e.config;return{file:{path:e.path,env:e.env},entries:Object.fromEntries(Object.entries(n).filter(([t,r])=>o[t]!==r))}}function j(n){const{file:e,entries:o}=n;if(!e)return o;const t=d(e),r=Object.fromEntries(Object.keys(t).map(i=>[i,()=>structuredClone(t[i])]));return r[f]=()=>u(e)[f],O(r,o)}function d(n){const e=JSON.stringify([n.path,n.env]);if(s?.key!==e){const{[f]:o,...t}=u(n);s={key:e,config:t}}return s.config}function u({path:n,env:e}){let o;try{o=JSON.parse(a(n,"utf8"))}catch(t){throw new Error(`Could not read the store config file "${n}": ${String(t)}`)}return l(o,t=>e[t]).config}function O(n,e){const o={},t=(r,i)=>{Object.defineProperty(o,r,{value:i,writable:!0,enumerable:!0,configurable:!0})};for(const[r,i]of Object.entries(n)){if(Object.hasOwn(e,r)){t(r,e[r]);continue}Object.defineProperty(o,r,{enumerable:!0,configurable:!0,get:()=>{const c=i();return t(r,c),c},set:c=>t(r,c)})}for(const[r,i]of Object.entries(e))Object.hasOwn(o,r)||t(r,i);return o}export{j as readWorkerConfig,m as toWorkerConfig};
1
+ import{readFileSync as a}from"node:fs";import{MARKDOC_PARTIALS_DATA_KEY as f}from"../constants/common.js";import{resolveStoreConfig as l}from"../store-config.js";let s;function m(n,e){if(!e)return{entries:n};const o=e.config;return{file:{path:e.path,env:e.env},entries:Object.fromEntries(Object.entries(n).filter(([t,r])=>o[t]!==r))}}function j(n){const{file:e,entries:o}=n;if(!e)return o;const t=d(e),r=Object.fromEntries(Object.keys(t).map(i=>[i,()=>structuredClone(t[i])]));return r[f]=()=>u(e)[f],O(r,o)}function d(n){const e=JSON.stringify([n.path,n.env]);if(s?.key!==e){const{[f]:o,...t}=u(n);s={key:e,config:t}}return s.config}function u({path:n,env:e}){let o;try{o=JSON.parse(a(n,"utf8"))}catch(t){throw new Error(`Could not read the store config file "${n}": ${String(t)}`)}return l(o,t=>e[t]).config}function O(n,e){const o={},t=(r,i)=>{Object.defineProperty(o,r,{value:i,writable:!0,enumerable:!0,configurable:!0})};for(const[r,i]of Object.entries(n)){if(Object.hasOwn(e,r)){t(r,e[r]);continue}Object.defineProperty(o,r,{enumerable:!0,configurable:!0,get:()=>{const c=i();return t(r,c),c},set:c=>{t(r,c)}})}for(const[r,i]of Object.entries(e))Object.hasOwn(o,r)||t(r,i);return o}export{j as readWorkerConfig,m as toWorkerConfig};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@redocly/redoc-reef",
3
- "version": "0.141.0-next.16",
3
+ "version": "0.141.0-next.17",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "bin": {
@@ -33,14 +33,14 @@
33
33
  "@opentelemetry/sdk-trace-web": "2.8.0",
34
34
  "@opentelemetry/semantic-conventions": "1.40.0",
35
35
  "@redocly/ajv": "8.18.0",
36
- "@redocly/api-docs": "0.6.0-next.16",
36
+ "@redocly/api-docs": "0.6.0-next.17",
37
37
  "@redocly/config": "0.75.0",
38
38
  "@redocly/markdoc": "0.7.1",
39
39
  "@redocly/openapi-core": "2.78.0",
40
40
  "@redocly/portal-legacy-ui": "0.19.0",
41
41
  "@redocly/portal-plugin-mock-server": "0.26.0-next.4",
42
42
  "@redocly/realm-asyncapi-sdk": "0.18.0-next.1",
43
- "@redocly/theme": "0.73.0-next.12",
43
+ "@redocly/theme": "0.73.0-next.13",
44
44
  "@shikijs/transformers": "3.21.0",
45
45
  "@tanstack/react-query": "5.62.3",
46
46
  "@tanstack/react-table": "8.21.3",