@redocly/redoc-reef 0.140.0-next.1 → 0.140.0-next.3
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 +228 -203
- package/dist/server/constants/common.d.ts +3 -0
- package/dist/server/constants/common.js +1 -1
- package/dist/server/plugins/api-docs/spec-download.api.js +1 -1
- package/dist/server/plugins/scorecard-classic/index.js +1 -1
- package/dist/server/plugins/scorecard-classic/shared-utils.js +1 -1
- package/dist/server/plugins/scorecard-classic/template/views.js +1 -1
- package/dist/server/plugins/search/engines/typesense/index.js +1 -1
- package/dist/server/utils/decode-request-path.d.ts +2 -0
- package/dist/server/utils/decode-request-path.js +1 -0
- package/dist/server/utils/llmstxt/resolve-llms-txt-md.js +1 -1
- package/dist/server/utils/rbac.js +1 -1
- package/dist/server/web-server/auth.d.ts +1 -0
- package/dist/server/web-server/auth.js +3 -3
- package/dist/server/web-server/routes/auth.js +1 -1
- package/dist/server/web-server/routes/dynamic-route.js +1 -1
- package/dist/server/web-server/routes/helpers/process-redirects.js +1 -1
- package/dist/server/web-server/routes/mcp-routes/mcp-consent-page.d.ts +2 -2
- package/dist/server/web-server/routes/mcp-routes/mcp-consent-page.js +18 -18
- package/dist/server/web-server/routes/mcp-routes/mcp-oauth.js +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{writeFileSync as
|
|
1
|
+
import{writeFileSync as D}from"node:fs";import L from"path";import{SCORECARD_CLASSIC_FOLDER as P,SCORECARD_OUTPUT_FILE_NAME as w}from"../../constants/common.js";import{mapObject as E}from"../../../utils/object/map-object.js";import{envConfig as j}from"../../config/env-config.js";import{removeLeadingSlash as _}from"../../../utils/url/remove-leading-slash.js";import{combineUrls as O}from"@redocly/theme/core/utils";import{logger as F}from"../../tools/notifiers/logger.js";import{getRouteSlugToCatalogSlugMap as N}from"../../utils/catalog-classic/get-route-slug-to-catalog-slug-map.js";import{getCatalogSharedDataId as q}from"../../utils/catalog-classic/get-catalog-shared-data-id.js";import{deepEqual as I}from"../../../utils/object/deep-equal.js";import{ensureDir as U}from"../../utils/index.js";import{getTemplatePath as k}from"./get-template-path.js";import{getAllRuleNames as M}from"./lint.js";import{getScorecardConfig as T}from"./get-scorecard-config.js";import{getScorecardSlug as W}from"./shared-utils.js";import{scorecardConfigLoader as B}from"./loaders/scorecard-config.js";import{scorecardLoader as J}from"./loaders/scorecard.js";import{computeScorecard as $}from"./compute-scorecard.js";import{telemetryTraceStep as x}from"../../../cli/telemetry/helpers/trace-step.js";const G="scorecardClassic";let u={},R={};async function ge({id:b,requiredEntitlements:A,loadersPrefix:v=""}){let p=null,y=null,h=!1;return{id:b??"scorecardClassic",requiredEntitlements:A??["scorecard"],loaders:{[`${v}scorecard-config`]:B,[`${v}scorecard`]:J},async processContent(r,l){await x("com.redocly.build.plugin.scorecardClassic",async C=>{const a=r.createTemplate(G,k("./template/index.js")),g=await l.getConfig(),m=T(g),f=g?.reunite??{},i=[()=>p===null,()=>!I(u,m),()=>!I(R,f)].some(e=>e());u=m,C?.setAttribute("config",JSON.stringify(u||{})),R=f;const n=g.catalogClassic??{},c=u.levels||[];if(c.length<1)throw Error("Invalid configuration of levels config");i&&(p=await $({actions:r,context:l,scorecardConfig:u,reuniteConfig:R}));const{data:{configs:t}}=await l.cache.load("",`${v}scorecard-config`),{perLevel:d,all:s}=M(t);y={levelNames:c.map(e=>e.name),rules:s,rulesPerLevel:d};for(const[e,o]of Object.entries(n)){const S=O(o.slug,"scorecard/");r.addRoute({duplicateInAllLocales:!0,slug:S,fsPath:O(o.slug,"scorecard/"),templateId:a,hasClientRoutes:!0,excludeFromSidebar:!0,serverPropsGetterIds:[],sharedData:[{id:"scorecard",key:"scorecard"},{key:"catalog",id:q(e)}],getNavText:()=>Promise.resolve(o.title||"API design scorecard"),getStaticData:async()=>({props:{catalogId:e,catalogConfig:{...o,items:void 0},scorecardConfig:u,scorecardInfo:y}})})}})},afterRoutesCreated:async(r,l)=>{const C=await l.getConfig(),a=C.catalogClassic??{},g=T(C);if(Object.keys(a).length){const i=Object.keys(a).length>1?await N(r,l,a):null,n={};for(const[c,t]of Object.entries(p||{})){const d=r.getRouteByFsPath(c),s=d?.slug;if(s){if(d&&!g.ignoreMetadata){const e=i?i.get(s)??Object.values(a)[0].slug:Object.values(a)[0].slug,o=O(e,"scorecard/");d.metadata={...d.metadata,scorecardStatus:t.status,scorecardLevel:t.scorecardLevel,scorecardLevelIdx:t.scorecardLevelIdx,scorecardLevels:E(t.levels,S=>({uniqueErrors:S.uniqueErrors,uniqueWarnings:S.uniqueWarnings})),scoreCardSlug:o+"apis/"+encodeURIComponent(_(s))}}if(n[s]={...t,levels:E(t.levels,e=>({...e,problems:e.problems.map(o=>({ruleId:o.ruleId,severity:o.severity}))}))},!h){const e=L.resolve(r.outdir,P,W(s));D(U(e),JSON.stringify(t))}}}await r.createSharedData("scorecard",n)}const m={};for(const[i,n]of Object.entries(p||{})){const c=r.getRouteByFsPath(i)?.slug;c&&(m[c]=n)}const f=j.REDOCLY_METADATA_OUTPUT_FOLDER;!h&&f&&(F.info("Writing scorecard data..."),D(L.join(f,w),JSON.stringify({scorecardData:m,...y}))),h=!0}}}export{ge as scorecardClassicPlugin};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
function
|
|
1
|
+
import{removeTrailingSlash as o}from"../../../utils/url/remove-trailing-slash.js";function s(r){const e={error:new Set,warn:new Set};for(const n of r)e[n.severity]?.add(n.ruleId);return{errors:e.error.size,warnings:e.warn.size}}function i(r){return r==="/"?"index.json":o(r).substring(1)+".json"}export{i as getScorecardSlug,s as getUniqueProblemsCount};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import*as e from"react";import{useCallback as H,useMemo as b,useState as G,useEffect as _}from"react";import{useLocation as T}from"react-router";import{Flex as U}from"@redocly/portal-legacy-ui";import{Button as x}from"@redocly/theme/components/Button/Button";import{AddIcon as I}from"@redocly/theme/icons/AddIcon/AddIcon";import{SubtractIcon as K}from"@redocly/theme/icons/SubtractIcon/SubtractIcon";import{ArrowLeftIcon as D}from"@redocly/theme/icons/ArrowLeftIcon/ArrowLeftIcon";import{getScorecardColorVariable as z,withoutPathPrefix as O}from"@redocly/theme/core/utils";import{Link as w}from"../../../../client/app/Link";import J from"../../../../client/app/CircularProgress";import{isDefined as R}from"../../../../utils/guards/is-defined.js";import{removeLeadingSlash as N}from"../../../../utils/url/remove-leading-slash.js";import{StatusByLevelWidget as Q}from"./StatusByLevelWidget";import{OTHER_TEAMS_LABEL as X,NON_CONFORMANT as Y}from"./utils";import{LevelIndicator as Z}from"./LevelIndicator";import{AppPageWrapper as V,CardValue as v,CardsWrapper as j,CatalogDescription as ee,ModeSwitcherTab as te,ModeSwitcherTabs as re,CardRow as B,ProblemsByStatusCardBody as W,ScoreCardStatusCardBody as F,TableWrap as ne,LevelComplianceCardTitle as le,ContentWithDotWrap as C,ScorecardCard as A,ScorecardCardTitle as L,LinkButton as ae}from"./index.styles";import{ApiLevel as M,InstanceStatus as k,LevelStatus as
|
|
1
|
+
import*as e from"react";import{useCallback as H,useMemo as b,useState as G,useEffect as _}from"react";import{useLocation as T}from"react-router";import{Flex as U}from"@redocly/portal-legacy-ui";import{Button as x}from"@redocly/theme/components/Button/Button";import{AddIcon as I}from"@redocly/theme/icons/AddIcon/AddIcon";import{SubtractIcon as K}from"@redocly/theme/icons/SubtractIcon/SubtractIcon";import{ArrowLeftIcon as D}from"@redocly/theme/icons/ArrowLeftIcon/ArrowLeftIcon";import{getScorecardColorVariable as z,withoutPathPrefix as O}from"@redocly/theme/core/utils";import{Link as w}from"../../../../client/app/Link";import J from"../../../../client/app/CircularProgress";import{isDefined as R}from"../../../../utils/guards/is-defined.js";import{removeLeadingSlash as N}from"../../../../utils/url/remove-leading-slash.js";import{StatusByLevelWidget as Q}from"./StatusByLevelWidget";import{OTHER_TEAMS_LABEL as X,NON_CONFORMANT as Y}from"./utils";import{LevelIndicator as Z}from"./LevelIndicator";import{AppPageWrapper as V,CardValue as v,CardsWrapper as j,CatalogDescription as ee,ModeSwitcherTab as te,ModeSwitcherTabs as re,CardRow as B,ProblemsByStatusCardBody as W,ScoreCardStatusCardBody as F,TableWrap as ne,LevelComplianceCardTitle as le,ContentWithDotWrap as C,ScorecardCard as A,ScorecardCardTitle as L,LinkButton as ae}from"./index.styles";import{ApiLevel as M,InstanceStatus as k,LevelStatus as q,RuleStatus as $}from"./components";import{Grid as S}from"./Grid/Grid";import{useDetailedScorecard as se}from"./useDetailedScorecard";import{Gauge as ce,GaugeValue as oe}from"./Gauge";function Ie(p){const u=T(),{data:d,levelNames:i,hasPublishedAt:n,hasTeam:s,teamLabel:l}=p,f=H((a,o,E)=>{const g=a.getValue(E)?new Date(a.getValue(E)).getTime():0,t=o.getValue(E)?new Date(o.getValue(E)).getTime():0;return g>t?1:-1},[]),m=b(()=>[{id:"title",header:"API",accessorKey:"api.title",size:200,cell:({getValue:a,row:o})=>e.createElement(w,{to:O(u.pathname)+"/apis/"+encodeURIComponent(N(o.original.api.link))},a())},n?{header:"Published at",accessorKey:"api.publishedAt",sortingFn:f,cell:({getValue:a})=>{const o=a();return o?new Date(o).toLocaleDateString():"-"}}:void 0,s?{header:l,accessorKey:"api.team"}:void 0,{id:"level",header:"Level",accessorKey:"scorecard.scorecardLevel",cell:({getValue:a,row:o})=>e.createElement(M,{level:a(),colorVariable:z(o.original?.scorecard.scorecardLevelIdx,i.length+1)})},...i.map(a=>({id:a,header:`${a}`,accessorKey:"scorecard.levels",cell:({getValue:o,row:E})=>{const g=o(),t=E.original.api.link;return g?.[a]?e.createElement(Z,{key:t,uniqueErrors:g[a].uniqueErrors,uniqueWarnings:g[a].uniqueWarnings,id:t}):null}}))].filter(R),[f,i,u.pathname,n,s,l]);return e.createElement(S,{columns:m,data:d,sortBy:[{id:"title",desc:!1}]})}function Ke(p){const u=T(),{data:d}=p,i=b(()=>[{header:"Rules",accessorKey:"ruleId",cell:({getValue:n})=>e.createElement(w,{to:O(u.pathname)+"/rules/"+encodeURIComponent(n())},n())},{id:"status",header:"Status",accessorKey:"status",size:200,cell:({row:n})=>e.createElement($,{errors:n.original.errorApisCount,warnings:n.original.warningApisCount})},{header:"Problem APIs",size:200,accessorKey:"apis",cell:({getValue:n})=>n().length,sortDescFirst:!0},{header:"Problem count",size:200,accessorKey:"count",sortDescFirst:!0}],[u.pathname]);return e.createElement(S,{columns:i,data:d,sortBy:[{id:"status",desc:!0}]})}function De(p){const{data:u,levelNames:d,filters:i,setActiveTab:n,teamLabel:s,teamProperty:l}=p,f=b(()=>[{id:"team",header:`API ${s}`,accessorKey:"team",size:200,cell:({getValue:m})=>e.createElement(ae,{onClick:()=>{n("apis"),i.find(a=>a.property===l)?.selectOption(m())}},m())},...[Y,...d].map(m=>({id:m,header:`${m}`,accessorFn:a=>a.levels[m]?.apis}))],[i,d,n,s,l]);return e.createElement(S,{columns:f,data:u,sortBy:[{id:"team",desc:!1}],groupHeaderTitle:"APIs by level"})}function ie(p){const{data:u,title:d}=p,i=b(()=>[{id:"expand",maxSize:40,size:40,header:()=>null,enableSorting:!1,cell:({row:n})=>n.getCanExpand()?e.createElement(x,{onClick:n.getToggleExpandedHandler(),variant:"text",size:"medium",icon:n.getIsExpanded()?e.createElement(K,null):e.createElement(I,null)}):null},{header:"Rules",accessorKey:"ruleId",cell:({getValue:n,row:s})=>s.getCanExpand()?e.createElement("span",{onClick:s.getToggleExpandedHandler()},n()):null},{header:"Status",accessorKey:"status",size:200,cell:({getValue:n})=>{const s=n();return e.createElement($,{errors:s?.errorsCount,warnings:s?.warningsCount})},enableSorting:!1},{header:"Problem count",accessorKey:"problemsCount",size:200,sortDescFirst:!0}],[]);return e.createElement(S,{columns:i,data:u,sortBy:[{id:"ruleId",desc:!1}],empty:e.createElement(e.Fragment,null,"\u2705 This API is compliant with ",e.createElement("strong",null,d)," level rules"),subRowKey:"problems"})}function ze(p){const{catalogSlug:u,slug:d,data:i,hasTeam:n,hasPublishedAt:s,teamLabel:l}=p,{apis:f,apisCount:m,warningApisCount:a,errorApisCount:o,levels:E,count:g}=i,t=f.length===0,h=t?void 0:{id:"expand",maxSize:40,size:40,header:()=>null,enableSorting:!1,cell:({row:r})=>r.getCanExpand()?e.createElement(x,{onClick:r.getToggleExpandedHandler(),variant:"text",size:"medium",icon:r.getIsExpanded()?e.createElement(K,null):e.createElement(I,null)}):null},P=b(()=>[h,{header:"API",accessorKey:"title"},s?{header:"Published at",accessorKey:"publishedAt",cell:({getValue:r})=>{const c=r();return c?new Date(c).toLocaleDateString():"-"}}:void 0,n?{header:l,accessorKey:"team",cell:({getValue:r})=>r()||X}:void 0,{header:"Problem count",size:200,accessorKey:"count",cell:({getValue:r})=>r()||0,sortDescFirst:!0}].filter(R),[n,s,l,t]),y=b(()=>Object.entries(i.teams).sort((r,c)=>c[1]-r[1]),[i.teams]);return e.createElement(V,null,e.createElement(x,{icon:e.createElement(D,null),iconPosition:"left",variant:"ghost",size:"large",to:`${u}scorecard`},"Back to dashboard"),e.createElement("h1",null,"Rule ",d),e.createElement(j,null,e.createElement(A,null,e.createElement(L,null,"Rule status"),e.createElement(F,null,e.createElement("div",null,e.createElement(v,null,m),e.createElement("br",null),"APIs"),e.createElement("div",null,e.createElement(C,null,e.createElement(v,{style:{textAlign:"right"}},m-a-o),e.createElement(k,{severity:"Pass"})),e.createElement(C,null,e.createElement(v,{style:{textAlign:"right"}},a),e.createElement(k,{severity:"Warn"})),e.createElement(C,null,e.createElement(v,{style:{textAlign:"right"}},o),e.createElement(k,{severity:"Error"}))))),e.createElement(A,null,e.createElement(L,null,"Problems by level"),e.createElement(W,null,Object.entries(E).map(([r,c])=>e.createElement(B,{key:r},e.createElement("span",null,r),e.createElement(ce,{chunks:[{share:c.errors/g*100,colorVariable:"--scorecard-color-error"},{share:c.warnings/g*100,colorVariable:"--scorecard-color-warning"}]}),e.createElement(oe,null,c.errors+c.warnings))))),e.createElement(A,null,e.createElement(L,null,`Problems by ${l}`),e.createElement(W,null,y.slice(0,4).map(([r,c])=>e.createElement(B,{key:r},e.createElement("span",{style:{flex:1,textAlign:"left"}},r),e.createElement(v,null,c)))))),e.createElement(S,{columns:P,data:f,sortBy:[{id:"title",desc:!1}],subRowKey:"problems",slug:d}))}function Oe(p){const{slug:u,api:d,teamLabel:i,catalogSlug:n}=p,{api:s}=d||{},{scorecard:l,isLoading:f}=se(u),m=l?.levels||{},[a,o]=G(Object.keys(m)[0]),E=b(()=>s?.publishedAt instanceof Date?s?.publishedAt.toLocaleDateString():s?.publishedAt,[s]);_(()=>{if(l){const t=l.levels||{};o(Object.keys(t)[0])}},[l]);const g=b(()=>{if(!l?.levels)return{};const t={};for(const h of Object.keys(l.levels)){const P=l.levels[h].problems.reduce((y,r)=>(y[r.ruleId]||(y[r.ruleId]=[]),y[r.ruleId].push(r),y),{});t[h]=Object.entries(P).map(([y,r])=>({ruleId:y,problems:[...r.filter(c=>c.severity==="error"),...r.filter(c=>c.severity==="warn")],problemsCount:r.length,status:{errorsCount:r.filter(c=>c.severity==="error").length,warningsCount:r.filter(c=>c.severity==="warn").length}}))}return t},[l?.levels]);return f?e.createElement(U,{justifyContent:"center",mt:"2em"},e.createElement(J,null)):l?e.createElement(V,null,e.createElement(x,{icon:e.createElement(D,null),iconPosition:"left",variant:"ghost",size:"large",to:`${n}scorecard`},"Back to dashboard"),e.createElement("h1",null,s?.title||u),e.createElement(ee,null,E&&e.createElement(e.Fragment,null,"Published at: ",E,e.createElement("br",null)),e.createElement(w,{to:u,external:!0},"Documentation")),e.createElement(j,null,e.createElement(A,null,e.createElement(le,null,e.createElement("span",null,"Scorecard level"),e.createElement(M,{level:l.scorecardLevel,colorVariable:z(l.scorecardLevelIdx,Object.keys(m).length)})),e.createElement(F,null,e.createElement("div",null,"Compliance by level"),e.createElement("div",null,Object.entries(l.levels).map(([t,h])=>e.createElement(C,{key:t},e.createElement(v,{style:{width:"100px",textAlign:"right"}},t),e.createElement(q,{errors:h.errors,warnings:h.warnings})))))),e.createElement(Q,{title:"Rules compliance",levels:Object.entries(l.levels).map(([t,h])=>({errors:h.uniqueErrors,warnings:h.uniqueWarnings,total:p.rulesPerLevel[t].length,name:t}))}),e.createElement(A,null,e.createElement(L,null,i),e.createElement(v,{style:{fontWeight:"normal"}},s?.team))),e.createElement(re,{style:{justifyContent:"flex-start"},"data-component-name":"Scorecard/ModeSwitcherTabs"},Object.keys(l.levels).map(t=>e.createElement(te,{"data-component-name":"Scorecard/ModeSwitcherTab",key:t,isActive:a===t,onClick:()=>o(t)},e.createElement(C,null,e.createElement("span",null,t)," ",e.createElement(q,{errors:l.levels[t].errors,warnings:l.levels[t].warnings}))))),Object.keys(m).map(t=>e.createElement(ne,{key:t,isActive:a===t},e.createElement(ie,{title:t,data:g[t]})))):e.createElement("div",null,"Scorecard not found")}export{Ie as ApiListView,Oe as ApiPage,ie as ApiView,ze as RuleView,Ke as RulesView,De as TeamsView};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{appendFile as T}from"node:fs/promises";import{existsSync as P}from"node:fs";import b from"node:path";import{Client as q}from"typesense";import{SEARCH_GROUP_FACET_FIELD as F,SEARCH_PRODUCT_FIELD as L,SEARCH_RBAC_FIELD as d,SEARCH_VERSION_FIELD as h}from"../../../../../constants/common.js";import{DISABLE_DEEP_LINK_IF_FIELDS_EXIST as v,HIGHLIGHTED_TEXT_MAX_LENGTH as C,SEARCH_DATA_EXPORT_FOLDER as R,SEARCH_DOCUMENT_METADATA_KEY as j,SEARCH_GROUP_LIMIT as O,SEARCH_MAX_FACET_VALUES as y,SEARCH_MAX_INMEMORY_DOCUMENTS_COUNT as k}from"../../../../constants/plugins/search.js";import{telemetryTraceStep as N}from"../../../../telemetry/helpers/trace-step.js";import{envConfig as _}from"../../../../config/env-config.js";import{logger as I}from"../../../../tools/notifiers/logger.js";import{ensureDir as E}from"../../../../utils/index.js";class X{#e=null;#i="";#t=[{name:"title",type:"string",facet:!1,optional:!0},{name:"text",type:"string",facet:!1,optional:!0},{name:"path",type:"string[]",facet:!1,optional:!0},{name:"isAdditionalOperation",type:"bool",facet:!1,optional:!0,queryable:!1},{name:"deprecated",type:"bool",facet:!1,optional:!0,queryable:!1},{name:"parameters",type:"object[]",facet:!1,optional:!0},{name:"parameters.name",type:"string[]",facet:!1,optional:!0,queryable:!1},{name:"parameters.description",type:"string[]",facet:!1,optional:!0,queryable:!1},{name:"parameters.place",type:"string[]",facet:!1,optional:!0,queryable:!1},{name:"parameters.path",type:"string[]",facet:!1,optional:!0,queryable:!1},{name:L,type:"string",facet:!0,optional:!0},{name:h,type:"object",facet:!0,optional:!0},{name:d,type:"string[]",facet:!0},{name:"metadata_curated",type:"bool",facet:!1,optional:!0,queryable:!1},{name:"metadata_keywords_excludes",type:"string[]",facet:!1,optional:!0,queryable:!1},{name:"metadata_keywords_includes",type:"string[]",facet:!1,optional:!0,queryable:!1}];#s=new Map;#r={ORGANIZATION_ID:_.ORGANIZATION_ID??"",PROJECT_ID:_.PROJECT_ID??"",TYPESENSE_API_URL:_.TYPESENSE_API_URL??"",TYPESENSE_API_KEY:_.TYPESENSE_API_KEY??""};constructor(){if(!_.isBuildMode){for(const[e,t]of Object.entries(this.#r))if(!t)throw new Error(`Cannot initialize search index. ${e} is not set`);this.#i=`${this.#r.ORGANIZATION_ID}_${this.#r.PROJECT_ID}_`,this.#e=new q({nodes:[{url:this.#r.TYPESENSE_API_URL}],apiKey:this.#r.TYPESENSE_API_KEY,connectionTimeoutSeconds:5})}}async initIndexSchema(e){this.#b(e)}async addDocuments(e,t){const{locale:s,outDir:a}=t,n=e.map(r=>{const i={...r},c=r[j];return c&&(c.curated&&(i.metadata_curated=c.curated),c.excludes&&(i.metadata_keywords_excludes=c.excludes),c.includes&&(i.metadata_keywords_includes=c.includes)),i}),o=this.#s.get(s)??[];this.#s.set(s,o.concat(n)),o.length+e.length>=k&&await this.exportDocuments(a)}async search(e,t){return await N("com.redocly.search.performed",async s=>{s?.setAttribute("id","searchQueryId"),s?.setAttribute("object","searchQuery"),s?.setAttribute("uri","urn:redocly:realm:api:searchQuery:searchQueryId");const{query:a,locale:n,filter:o,loadMore:r}=e,i=this.#f(n),c={collection:i,q:a||"*",query_by:this.#h(),max_facet_values:y};if(s?.setAttribute("collectionName",i),s?.setAttribute("locale",n),this.#e)if(r){const{groupKey:l,offset:u}=r,f={offset:u,filter_by:this.#n(t,o),facet_by:"*",per_page:O};return s?.setAttribute("isLoadMore",!0),s?.setAttribute("filter",f.filter_by),this.#d(await this.#e.collections(i).documents().search({...c,...f}),l)}else{const l=this.#n(t,o);s?.setAttribute("filter",l);const u=await this.#e.multiSearch.perform({searches:this.#F(t,o)},c),f=this.#c(u,this.#o());f&&I.warn("Search facet requests failed: %s",f);const p=this.#y(u),m=(p[F]??[]).map(A=>A.value);s?.setAttribute("groups",m.join(",")),m.length===y&&I.warn("Search category facet list reached the limit of %s; results for some categories may be missing",y);const D=[...new Set(this.#m(o))].slice(0,y),g=D.length?D:m;if(!g.length)return{facets:p,documents:{},groupCounts:{}};const S=await this.#e.multiSearch.perform({searches:g.map(A=>({filter_by:`${l} && (${F}:=${this.#a(A)})`,per_page:O}))},c),$=this.#c(S,g);return $&&I.warn("Search category requests failed: %s",$),this.#_(S,g,p,o)}else return{facets:{},documents:{}}})}#d(e,t){const s={facets:{},documents:{[t]:[]},groupCounts:typeof e.found=="number"?{[t]:e.found}:{}};if(e.hits&&e.hits.length)for(const a of e.hits)s.documents[t].push({document:this.#l(a),highlight:this.#u(a)});return s}#y(e){const t={};if("results"in e){for(const s of e.results)if(s.facet_counts&&s.facet_counts.length)for(const a of s.facet_counts)t[a.field_name]=a.counts.map(n=>({value:n.value,count:n.count}))}return t}#c(e,t){return"results"in e?e.results.map((s,a)=>({result:s,label:t[a]})).filter(({result:s})=>"error"in s).map(({result:s,label:a})=>`${a}: ${s.error}`).join("; "):""}#_(e,t,s,a){const n={},o={facets:s,documents:{},groupCounts:n};for(const r of this.#m(a))o.documents[r]=[];return"results"in e&&e.results.forEach((r,i)=>{const c=t[i];typeof r.found=="number"&&(n[c]=r.found);const l=r.hits??[];l.length&&(o.documents[c]=l.map(u=>({document:this.#l(u),highlight:this.#u(u)})))}),o}#l(e){return this.#g(e)}#u(e){const t={},s=[];for(const[a,n]of Object.entries(e.highlight??{}))if(Array.isArray(n)){if(a==="path"){const o=n,r=[];for(const i of o)r.push(i.snippet);t.path=r}else if(a==="parameters"){const o=n;for(const r of o){let i=!1;for(const[c,l]of Object.entries(r))if(c!=="deepLink")if(Array.isArray(l))for(const u of l)u.matched_tokens?.length&&(i=!0);else l.matched_tokens?.length&&(i=!0);if(i){const c={name:r.name?.snippet||"",description:r.description?.snippet||"",place:r.place?.snippet||"",path:r.path?.map(l=>l?.snippet)||[]};t.parameters=[c];break}}}}else t[a]=n.snippet,s.push(a);for(const[a,n]of Object.entries(e.document))!s.includes(a)&&typeof n=="string"&&(t[a]=n.length>C?`${n.substring(0,C)}...`:n);return t.parameters||(t.parameters=[]),t}#g(e){let t;const s=Object.keys(e.highlight??{});for(const n of v)if(s.some(o=>o===n))return e.document;const a=e.highlight?.parameters;if(a){for(const n of a)for(const[o,r]of Object.entries(n))if(o!=="deepLink"){if(Array.isArray(r)){for(const i of r)if(i.matched_tokens?.length){t=n.deepLink?.snippet??t;break}}else if(r.matched_tokens?.length){t=n.deepLink?.snippet??t;break}}}if(t){const n=t.split("#")[1];return{...e.document,url:`${e.document.url}#${n}`}}return e.document}async exportDocuments(e){const t='{"documents":[',s=E(b.join(e,R));for(const[a,n]of this.#s){if(n.length===0)continue;const o=E(b.join(s,`${a}.json`)),r=!P(o),i=JSON.stringify(n).substring(1).slice(0,-1),c=r?t+i:","+i;await T(o,c,{encoding:"utf8"}),this.#s.set(a,[])}}async exportIndexes(e){const t=E(b.join(e,R));for(const s of this.#s.keys()){const a=E(b.join(t,`${s}.json`)),n=`],"schemaFields":${JSON.stringify(this.#t)}}`;await T(a,n,{encoding:"utf8"})}}async import(e){}async countFacets(e,t){return await N("com.redocly.search.facets",async s=>{s?.setAttribute("id","searchFacetsId"),s?.setAttribute("object","searchFacets"),s?.setAttribute("uri","urn:redocly:realm:api:searchFacets:searchFacetsId");const{locale:a,query:n,facetQuery:o,filter:r,field:i}=e,c=this.#f(a),l={q:n||"*",query_by:this.#h(),facet_by:"*",facet_query:this.#A(o,i),filter_by:this.#n(t,r,i),max_facet_values:y};if(s?.setAttribute("collectionName",c),s?.setAttribute("query",l.q),s?.setAttribute("facetQuery",l.facet_query),s?.setAttribute("filter",l.filter_by),this.#e){const u={},f=await this.#e.collections(c).documents().search(l);if(f.facet_counts&&f.facet_counts.length)for(const p of f.facet_counts)u[p.field_name]=p.counts.map(m=>({value:m.value,count:m.count,isCounterVisible:!!n||(r?.length||0)>0}));return u}else return{}})}#f(e){return`${this.#i}${e}`}#b(e){for(const[t,{queryable:s}]of e)this.#t.find(a=>a.name===t)||this.#t.push({queryable:s,name:t,type:"string",facet:!0,optional:!0})}#h(){return this.#t.filter(e=>e.facet?e.queryable:e.queryable!==!1).map(e=>e.name).join(",")}#a(e){return`\`${e.replaceAll("`","")}\``}#n(e,t,s){const a=e.teams.filter(r=>!r.includes("`")&&!r.includes("*")).map(r=>this.#a(r)),n=a.length?`${d}:=[${a.join(", ")}]`:`${d}:=[\`anonymous\`] && ${d}:!=[\`anonymous\`]`,o=(t??[]).filter(r=>r.field!==s&&r.field!==h&&r.values.length&&this.#p(r.field)).map(r=>{const i=r.values.map(c=>this.#a(c));return`${r.field}:=[${i.join(", ")}]`});return[n,...o,this.#E(t)].map(r=>`(${r})`).join(" && ")}#p(e){return this.#o().includes(e)}#o(){return this.#t.filter(e=>e.facet&&e.name!==d&&e.name===e.name.trim()).map(e=>e.name)}#E(e){const t=e?.find(r=>r.field===h);if(t?.values.length!==2)return`${h}.isDefault:true`;const[s,a]=t.values.map(r=>this.#a(r)),n=`(${h}.folderId:! ${s} && ${h}.isDefault:true)`,o=`(${h}.folderId: ${s} && ${h}.version:=${a})`;return`${n} || ${o}`}#A(e,t){return e&&t&&this.#p(t)?`${t}:${e}`:""}#m(e){const t=[];if(e&&e.length)for(const s of e)s.field===F&&t.push(...s.values);return t}#F(e,t){const s=[];for(const a of this.#o()){const n={facet_by:a,filter_by:this.#n(e,t,a)};s.push(n)}return s}cleanupFacetValues(e){const t=e.getSearchFacets();t.forEach(s=>{s.values=[]}),e.setSearchFacets(t)}}export{X as Typesense};
|
|
1
|
+
import{appendFile as T}from"node:fs/promises";import{existsSync as P}from"node:fs";import b from"node:path";import{Client as q}from"typesense";import{SEARCH_GROUP_FACET_FIELD as F,SEARCH_PRODUCT_FIELD as L,SEARCH_RBAC_FIELD as d,SEARCH_VERSION_FIELD as h}from"../../../../../constants/common.js";import{DISABLE_DEEP_LINK_IF_FIELDS_EXIST as v,HIGHLIGHTED_TEXT_MAX_LENGTH as C,SEARCH_DATA_EXPORT_FOLDER as R,SEARCH_DOCUMENT_METADATA_KEY as j,SEARCH_GROUP_LIMIT as O,SEARCH_MAX_FACET_VALUES as y,SEARCH_MAX_INMEMORY_DOCUMENTS_COUNT as k}from"../../../../constants/plugins/search.js";import{telemetryTraceStep as N}from"../../../../telemetry/helpers/trace-step.js";import{envConfig as _}from"../../../../config/env-config.js";import{logger as I}from"../../../../tools/notifiers/logger.js";import{ensureDir as E}from"../../../../utils/index.js";class X{#e=null;#i="";#t=[{name:"title",type:"string",facet:!1,optional:!0},{name:"text",type:"string",facet:!1,optional:!0},{name:"path",type:"string[]",facet:!1,optional:!0},{name:"isAdditionalOperation",type:"bool",facet:!1,optional:!0,queryable:!1},{name:"deprecated",type:"bool",facet:!1,optional:!0,queryable:!1},{name:"parameters",type:"object[]",facet:!1,optional:!0},{name:"parameters.name",type:"string[]",facet:!1,optional:!0,queryable:!1},{name:"parameters.description",type:"string[]",facet:!1,optional:!0,queryable:!1},{name:"parameters.place",type:"string[]",facet:!1,optional:!0,queryable:!1},{name:"parameters.path",type:"string[]",facet:!1,optional:!0,queryable:!1},{name:L,type:"string",facet:!0,optional:!0},{name:h,type:"object",facet:!0,optional:!0},{name:d,type:"string[]",facet:!0},{name:"metadata_curated",type:"bool",facet:!1,optional:!0,queryable:!1},{name:"metadata_keywords_excludes",type:"string[]",facet:!1,optional:!0,queryable:!1},{name:"metadata_keywords_includes",type:"string[]",facet:!1,optional:!0,queryable:!1}];#s=new Map;#r={ORGANIZATION_ID:_.ORGANIZATION_ID??"",PROJECT_ID:_.PROJECT_ID??"",TYPESENSE_API_URL:_.TYPESENSE_API_URL??"",TYPESENSE_API_KEY:_.TYPESENSE_API_KEY??""};constructor(){if(!_.isBuildMode){for(const[e,t]of Object.entries(this.#r))if(!t)throw new Error(`Cannot initialize search index. ${e} is not set`);this.#i=`${this.#r.ORGANIZATION_ID}_${this.#r.PROJECT_ID}_`,this.#e=new q({nodes:[{url:this.#r.TYPESENSE_API_URL}],apiKey:this.#r.TYPESENSE_API_KEY,connectionTimeoutSeconds:5})}}async initIndexSchema(e){this.#b(e)}async addDocuments(e,t){const{locale:s,outDir:a}=t,n=e.map(r=>{const i={...r},c=r[j];return c&&(c.curated&&(i.metadata_curated=c.curated),c.excludes&&(i.metadata_keywords_excludes=c.excludes),c.includes&&(i.metadata_keywords_includes=c.includes)),i}),o=this.#s.get(s)??[];this.#s.set(s,o.concat(n)),o.length+e.length>=k&&await this.exportDocuments(a)}async search(e,t){return await N("com.redocly.search.performed",async s=>{s?.setAttribute("id","searchQueryId"),s?.setAttribute("object","searchQuery"),s?.setAttribute("uri","urn:redocly:realm:api:searchQuery:searchQueryId");const{query:a,locale:n,filter:o,loadMore:r}=e,i=this.#f(n),c={collection:i,q:a||"*",query_by:this.#h(),max_facet_values:y};if(s?.setAttribute("collectionName",i),s?.setAttribute("locale",n),this.#e)if(r){const{groupKey:l,offset:u}=r,f={offset:u,filter_by:this.#n(t,o),facet_by:"*",per_page:O};return s?.setAttribute("isLoadMore",!0),s?.setAttribute("filter",f.filter_by),this.#d(await this.#e.collections(i).documents().search({...c,...f}),l)}else{const l=this.#n(t,o);s?.setAttribute("filter",l);const u=await this.#e.multiSearch.perform({searches:this.#F(t,o)},c),f=this.#c(u,this.#o());f&&I.warn("Search facet requests failed: %s",f);const p=this.#y(u),m=(p[F]??[]).map(A=>A.value);s?.setAttribute("groups",m.join(",")),m.length===y&&I.warn("Search category facet list reached the limit of %s; results for some categories may be missing",y);const D=[...new Set(this.#m(o))].slice(0,y),g=D.length?D:m;if(!g.length)return{facets:p,documents:{},groupCounts:{}};const S=await this.#e.multiSearch.perform({searches:g.map(A=>({filter_by:`${l} && (${F}:=${this.#a(A)})`,per_page:O}))},c),$=this.#c(S,g);return $&&I.warn("Search category requests failed: %s",$),this.#_(S,g,p,o)}else return{facets:{},documents:{}}})}#d(e,t){const s={facets:{},documents:{[t]:[]},groupCounts:typeof e.found=="number"?{[t]:e.found}:{}};if(e.hits&&e.hits.length)for(const a of e.hits)s.documents[t].push({document:this.#l(a),highlight:this.#u(a)});return s}#y(e){const t={};if("results"in e){for(const s of e.results)if(s.facet_counts&&s.facet_counts.length)for(const a of s.facet_counts)t[a.field_name]=a.counts.map(n=>({value:n.value,count:n.count}))}return t}#c(e,t){return"results"in e?e.results.map((s,a)=>({result:s,label:t[a]})).filter(({result:s})=>"error"in s).map(({result:s,label:a})=>`${a}: ${s.error}`).join("; "):""}#_(e,t,s,a){const n={},o={facets:s,documents:{},groupCounts:n};for(const r of this.#m(a))o.documents[r]=[];return"results"in e&&e.results.forEach((r,i)=>{const c=t[i];typeof r.found=="number"&&(n[c]=r.found);const l=r.hits??[];l.length&&(o.documents[c]=l.map(u=>({document:this.#l(u),highlight:this.#u(u)})))}),o}#l(e){return this.#g(e)}#u(e){const t={},s=[];for(const[a,n]of Object.entries(e.highlight??{}))if(Array.isArray(n)){if(a==="path"){const o=n,r=[];for(const i of o)r.push(i.snippet);t.path=r}else if(a==="parameters"){const o=n;for(const r of o){let i=!1;for(const[c,l]of Object.entries(r))if(c!=="deepLink")if(Array.isArray(l))for(const u of l)u.matched_tokens?.length&&(i=!0);else l.matched_tokens?.length&&(i=!0);if(i){const c={name:r.name?.snippet||"",description:r.description?.snippet||"",place:r.place?.snippet||"",path:r.path?.map(l=>l?.snippet)||[]};t.parameters=[c];break}}}}else t[a]=n.snippet,s.push(a);for(const[a,n]of Object.entries(e.document))!s.includes(a)&&typeof n=="string"&&(t[a]=n.length>C?`${n.substring(0,C)}...`:n);return t.parameters||(t.parameters=[]),t}#g(e){let t;const s=Object.keys(e.highlight??{});for(const n of v)if(s.some(o=>o===n))return e.document;const a=e.highlight?.parameters;if(a){for(const n of a)for(const[o,r]of Object.entries(n))if(o!=="deepLink"){if(Array.isArray(r)){for(const i of r)if(i.matched_tokens?.length){t=n.deepLink?.snippet??t;break}}else if(r.matched_tokens?.length){t=n.deepLink?.snippet??t;break}}}if(t){const n=t.split("#")[1];return{...e.document,url:`${e.document.url}#${n}`}}return e.document}async exportDocuments(e){const t='{"documents":[',s=E(b.join(e,R));for(const[a,n]of this.#s){if(n.length===0)continue;const o=E(b.join(s,`${a}.json`)),r=!P(o),i=JSON.stringify(n).substring(1).slice(0,-1),c=r?t+i:","+i;await T(o,c,{encoding:"utf8"}),this.#s.set(a,[])}}async exportIndexes(e){const t=E(b.join(e,R));for(const s of this.#s.keys()){const a=E(b.join(t,`${s}.json`)),n=`],"schemaFields":${JSON.stringify(this.#t)}}`;await T(a,n,{encoding:"utf8"})}}async import(e){}async countFacets(e,t){return await N("com.redocly.search.facets",async s=>{s?.setAttribute("id","searchFacetsId"),s?.setAttribute("object","searchFacets"),s?.setAttribute("uri","urn:redocly:realm:api:searchFacets:searchFacetsId");const{locale:a,query:n,facetQuery:o,filter:r,field:i}=e,c=this.#f(a),l={q:n||"*",query_by:this.#h(),facet_by:"*",facet_query:this.#A(o,i),filter_by:this.#n(t,r,i),max_facet_values:y,per_page:0};if(s?.setAttribute("collectionName",c),s?.setAttribute("query",l.q),s?.setAttribute("facetQuery",l.facet_query),s?.setAttribute("filter",l.filter_by),this.#e){const u={},f=await this.#e.collections(c).documents().search(l);if(f.facet_counts&&f.facet_counts.length)for(const p of f.facet_counts)u[p.field_name]=p.counts.map(m=>({value:m.value,count:m.count,isCounterVisible:!!n||(r?.length||0)>0}));return u}else return{}})}#f(e){return`${this.#i}${e}`}#b(e){for(const[t,{queryable:s}]of e)this.#t.find(a=>a.name===t)||this.#t.push({queryable:s,name:t,type:"string",facet:!0,optional:!0})}#h(){return this.#t.filter(e=>e.facet?e.queryable:e.queryable!==!1).map(e=>e.name).join(",")}#a(e){return`\`${e.replaceAll("`","")}\``}#n(e,t,s){const a=e.teams.filter(r=>!r.includes("`")&&!r.includes("*")).map(r=>this.#a(r)),n=a.length?`${d}:=[${a.join(", ")}]`:`${d}:=[\`anonymous\`] && ${d}:!=[\`anonymous\`]`,o=(t??[]).filter(r=>r.field!==s&&r.field!==h&&r.values.length&&this.#p(r.field)).map(r=>{const i=r.values.map(c=>this.#a(c));return`${r.field}:=[${i.join(", ")}]`});return[n,...o,this.#E(t)].map(r=>`(${r})`).join(" && ")}#p(e){return this.#o().includes(e)}#o(){return this.#t.filter(e=>e.facet&&e.name!==d&&e.name===e.name.trim()).map(e=>e.name)}#E(e){const t=e?.find(r=>r.field===h);if(t?.values.length!==2)return`${h}.isDefault:true`;const[s,a]=t.values.map(r=>this.#a(r)),n=`(${h}.folderId:! ${s} && ${h}.isDefault:true)`,o=`(${h}.folderId: ${s} && ${h}.version:=${a})`;return`${n} || ${o}`}#A(e,t){return e&&t&&this.#p(t)?`${t}:${e}`:""}#m(e){const t=[];if(e&&e.length)for(const s of e)s.field===F&&t.push(...s.values);return t}#F(e,t){const s=[];for(const a of this.#o()){const n={facet_by:a,filter_by:this.#n(e,t,a),per_page:0};s.push(n)}return s}cleanupFacetValues(e){const t=e.getSearchFacets();t.forEach(s=>{s.values=[]}),e.setSearchFacets(t)}}export{X as Typesense};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function c(d){let e;try{e=decodeURIComponent(d)}catch{return}return/[\\\0]/.test(e)||e.replace(/\/$/,"").split("/").slice(1).some(t=>t===""||t==="."||t==="..")?void 0:e}export{c as decodeRequestPath};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import
|
|
1
|
+
import n from"path";import{removeLeadingSlash as s}from"../../../utils/url/remove-leading-slash.js";import{fileExistsAsync as l}from"../index.js";async function f(e,o,r){if(r){const t=await r.getPageMarkdown(e);return{exists:t!==void 0,content:t?.content,route:t?.route}}const i=e==="/index.html.md"?"/":e.replace(/\.md$/i,"");return{exists:await l(n.resolve(o.outdir,s(e))),content:void 0,route:o.getRouteBySlug(i,{followRedirect:!1})}}export{f as resolveLlmsTxtMd};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import R from"path";import
|
|
1
|
+
import R from"path";import T from"picomatch";import"../node-crypto-polyfill.js";import{REDOCLY_TEAMS_RBAC as L,REDOCLY_ROUTE_RBAC as A}from"@redocly/config";import{MCP_ROUTE as U,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 D,PUBLIC_RBAC_SCOPE_ITEM as y,RBAC_ALL_OTHER_TEAMS as l,DEFAULT_RBAC_SCOPE as x,GRAPHQL_SPEC_SLUG as B}from"../../constants/common.js";import{DEPRECATED_PUBLIC_API_DEFINITIONS_FOLDER as g,PUBLIC_API_DEFINITIONS_FOLDER as C,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 P}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 I}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{EntitlementsProvider as st}from"../entitlements/entitlements-provider.js";const j=["NONE","READ","TRIAGE","WRITE","MAINTAIN","ADMIN"],ct=new Set(["x-parsed-md-description","x-parsed-md-summary"]),it=new Set(Object.values(w).map(t=>P(t.split(":")[0])));function wt(t,e){const r=j.indexOf(t.toUpperCase()),n=j.indexOf(e.toUpperCase());return r>n?t:e}const _={};function F(t,e){if(!t?.content)return y;const r=t.content,{slug:n,fsPath:o}=e;if(!n&&!o)return y;const s=a=>{const d=`slug:${a}`,p=_[d]??T(a);_[d]=p;const E=`fsPath:${a}`,S=_[E]??T(z(a));return _[E]=S,!!(n&&p(n))||!!(o&&S(o))};if(ut(n||o||"")&&Object.keys(r).filter(p=>s(p)).length===0)return r[x]||y;const f=Object.keys(r).filter(a=>s(a));if(f.length==0)return y;const u=f.map(a=>T.scan(a,{tokens:!0,parts:!0}));let h=u[0];for(let a=1;a<u.length;a++)h=ot(h,u[a]);return r[h.input]}function N(t,e,r){const n=r?[...e,r]:e,o=[];for(const s of n)t[s]?o.push(t[s]):t[l]&&s!==r&&o.push(t[l]);return o.some(s=>s.toLowerCase()!=="none")}function Bt(t,e,r={},n=!1){if(n&&Object.keys(r).length===0)return e.isAuthenticated;const o=r.features?.[t];return o?N(o,e.teams):!0}function bt(t,e){return O(t,H,e.access?.rbac||{},e.access?.requiresLogin||!1)}function O(t,e={},r={},n=!1){if(t.slug&&typeof t.slug=="string"&&it.has(P(t.slug))||(t.slug===U||t.slug===k||t.slug===G)&&st.instance().canAccessFeature("mcp"))return!0;if(n&&Object.keys(r).length===0)return!!e.isAuthenticated;const o=q(r,e.teams||[]),s=t[L]||F(o,t[A]||{});return Object.keys(s||{}).length===0?!1:Object.keys(s).length===1&&s[l]&&s[l].toLowerCase()!=="none"?!0:N(s,e?.teams||[],e?.email)}function $t(t,e,r,n){if(!t.startsWith(C)&&!t.startsWith(g))return!0;const o=t.replace(new RegExp(`^${C}/`),"").replace(new RegExp(`^${g}/`),"").replace(new RegExp(`^${B}/`),""),c=o==="."?"":o,i={[A]:{slug:t,fsPath:c},slug:t};return O(i,n,e,r)}function Wt(t,e,r,n,o){if(!I(t,b))return[`/${v}`,`/${Y}`].includes(t)||[$,W].some(E=>I(t,E));const s=t.match(/\..{64}\.([A-Fa-f0-9]{8})\.[^.]+$/)?.[1];if(!s)return!0;const c=n[s];if(!c)return!0;const{base:i,ext:f}=R.parse(t),u=i.split(".")[0],h=f.split(".").join(""),d=c==="."?"":c,p={[A]:{slug:t,fsPath:R.posix.join(d,`${u}.${h}`)},slug:t};return O(p,o,e,r)}async function vt(t,e){const{isAuthenticated:r=!1,idpAccessToken:n,federatedAccessToken:o,federatedIdToken:s,...c}=await nt(t,e),{teams:i=[]}=c;let f;return r?f=i.filter(u=>u!==D):f=[D],{isAuthenticated:r,idpAccessToken:n,teams:f,claims:c}}function M(t,e,r={},n=!1){if(!t)return t;if(Array.isArray(t)){const o=[];for(const s of t){const c=M(s,e,r,n);c!==void 0&&o.push(c)}return o}if(typeof t=="object"){if(!O(t,e,r,n))return;let o=!1;const s={};for(const c in t){if(c===L||c===A)continue;if(ct.has(c)){s[c]=t[c];continue}const i=M(t[c],e,r,n);if(!t.link&&(c==="items"||c==="menu"&&t.type==="tab")&&Array.isArray(i)&&i.length===0&&t[c].length!==0){o=!0;continue}i!==void 0&&(s[c]=i),c==="paths"&&at(i)&&ft(i)}return o?void 0:s}return t}function Yt(t){return typeof t=="string"?t.split(" ").filter(Boolean):Array.isArray(t)?t.map(e=>e.toString()):[]}function Gt(t,e){if(!e)return;const r=e.content;if(!r)return e;const n=Object.entries(r).flatMap(([s,c])=>s===x?[[s,c]]:[[s,c]].concat(t.localeFolders.map(i=>[s.startsWith("/")?`/${i.toLocaleLowerCase()}${s}`:R.posix.join(t.localizationFolder,i,s),c]))),o=Object.fromEntries(n);return{...e,content:o}}async function Ht(t,e){if(!e)return{};const r={},n=new Set(t.scan().flatMap(({relativePath:o})=>{const{versionFolderPath:s}=K(o)||{},c=R.dirname(o);return s?[s,c]:c}));for(const o of n)r[Q(o)]=o;return r}const m=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function at(t){return m(t)&&Object.keys(t).length>0}function ft(t){for(const e of Object.keys(t)){const r=t[e];m(r)&&Object.keys(r).length===0&&delete t[e]}}function ut(t){return t?t.split("/").filter(Boolean).some(r=>r.startsWith(".")):!1}const lt=t=>{if(t&&m(t)&&("content"in t&&m(t.content)||"reunite"in t&&m(t.reunite)||"features"in t&&m(t.features)||t.teamFolders&&t.teamNamePatterns)){const e=Object.values(t.content||{});if(e.length===0)return!0;if(e.every(m))return e.every(r=>Object.values(r).every(n=>typeof n=="string"))}return!1},zt=async t=>{if(t){if(Object.keys(t).length===0)return{};if(lt(t))return mt(t);await V.panicOnContentError(`You are using an incorrect format of ${J("rbac:")} configuration. See: https://redocly.com/docs/realm/access`)}},mt=t=>{const e={...t};if(e.content){const r={};for(const n in e.content)if(e.content[n]!==void 0){const o=P(n);r[o]=e.content[n]}e.content=r}return e};function Kt(t,e){const r=t.fsPath,n=t.slug,o=[],s=Z(e)&&(r||n)?et(e,[r,n].filter(X)):null;if(s){const i=e?.teamNamePatterns?.map(f=>f.replace("{teamPathSegment}",s.teamPathSegment).replace("{projectRole}","read"))??[];o.push(...i)}const c=F(s?{content:{...tt(e),...e.content}}:e,t);return o.push(...pt(c)),ht(e,o)}function pt(t){if(!t)return[];const e=[],r=l in t?{authenticated:t[l],anonymous:t[l]}:{};for(const[n,o]of Object.entries({...r,...t}))o.toLowerCase()!=="none"&&n!==l&&e.push(n);return e}function ht(t,e){return e.map(n=>rt(t,n)??{teamName:n}).map(n=>n.projectRole&&n.projectRole!=="READ"?n.teamName?.toLowerCase().replace(n.projectRole?.toLowerCase?.()??"","read")??"":n.teamName?.toLowerCase()??"")}export{j as PROJECT_ROLES_ORDERED_BY_ACCESS_LEVEL,Gt as applyL10nToRbacConfig,Wt as canAccessAsset,Bt as canAccessFeature,O as canAccessResource,$t as canDownloadApiDefinition,ht as expandTeamsForRead,pt as extractTeamsFromScopeItems,M as filterDataByAccessDeep,vt as getAuthDetailsFromCookies,wt as getHigherRole,Kt as getRbacTeamsListForResource,F as getScopeItemsForResource,N as hasScopeAccess,lt as isRbacConfigValid,bt as isResourcePubliclyAccessible,mt as normalizeRbacConfig,zt as parseRbacConfig,Yt as parseTeamClaimToArray,Ht as resolveDirectoryHashes};
|
|
@@ -161,6 +161,7 @@ export declare const UNKNOWN_KID_RETRY_MS = 60000;
|
|
|
161
161
|
export declare function getOidcMetadata(idpId: string, providerConfig: OidcProviderConfig): Promise<OidcIssuerMetadata>;
|
|
162
162
|
export declare function discoverJwks(ssoConfig: SsoConfig): Promise<void>;
|
|
163
163
|
export declare function getRedoclyTokenPayload(token: string): Promise<Record<string, unknown>>;
|
|
164
|
+
export declare function exchangeTokenLoginCode(code: string): Promise<string | undefined>;
|
|
164
165
|
export declare function isRedoclySso(config: OidcProviderConfig): boolean;
|
|
165
166
|
export declare function verifySAMLResponse(responseXml: string, cert: string): Promise<boolean>;
|
|
166
167
|
export declare function orderTeamsRbacFirst(teams: string[], rbacConfig: RbacConfig | undefined, teamsMapping: Record<string, string> | undefined): string[];
|
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import"../node-crypto-polyfill.js";import{DOMParser as j}from"@xmldom/xmldom";import{SignedXml as
|
|
1
|
+
import"../node-crypto-polyfill.js";import{DOMParser as j}from"@xmldom/xmldom";import{SignedXml as ee}from"xml-crypto";import te from"xpath";import{deflateSync as ne,inflateSync as re}from"fflate";import{createHash as oe}from"crypto";import{ulid as se}from"ulid";import{AuthProviderType as f,DEFAULT_TEAM_CLAIM_NAME as U}from"@redocly/config";import{ALTERNATIVE_AUD_CLAIM_NAME as ie,AUTH_URL as K,JWT_SECRET_KEY as y,MAX_AUTH_TOKEN_COOKIE_BYTES as ae}from"../constants/common.js";import{ensureArray as R}from"../../utils/array/ensure-array.js";import{envConfig as ce}from"../config/env-config.js";import{decryptClaimValue as ue}from"../utils/crypto/decrypt-claim-value.js";import{decryptAesGcm as de}from"../utils/crypto/decrypt-aes-gcm.js";import{encryptAesGcm as le}from"../utils/crypto/encrypt-aes-gcm.js";import{getPathPrefix as me,withPathPrefix as pe,withoutPathPrefix as fe}from"@redocly/theme/core/utils";import{ServerRoutes as V}from"../../constants/api.js";import{AuthCookieNames as I,DEFAULT_AUTHENTICATED_TEAM as he,REQUIRED_OIDC_SCOPES as $}from"../../constants/common.js";import{appendQueryParams as ye}from"../../utils/url/append-query-params.js";import{parsePreviewUrl as B}from"../../utils/url/parse-preview-url.js";import{logger as O}from"../tools/notifiers/logger.js";import{randomString as Ae}from"../utils/crypto/random-string.js";import{randomUUID as M}from"../utils/crypto/random-uuid.js";import{AlgorithmTypes as l,JwtTokenExpired as _e}from"./jwt/types.js";import*as p from"./jwt/jwt.js";import{InternalTokenTypes as g}from"./jwt/token-types.js";import{parseTeamClaimToArray as we}from"../utils/index.js";import{parseTeamNameTemplate as Se}from"../utils/rbac-expand.js";import{arrayBufferToBase64 as Te,decodeBase64 as F,encodeBase64URL as ge,urlSafeBase64 as H}from"./jwt/encode.js";import{formatSamlCertificate as xe}from"./utils/format-saml-certificate.js";const Ie=new Set(Object.values(g));function x(e){return e?.type===f.OIDC}function Ee(e){return e?.type===f.SAML2}async function Mt(e,t){if(x(t))return ke(e,t);if(Ee(t))return Re(e,t)}async function ke(e,t){const n=await Q(e,t),r=new Set((t.scopes||[]).concat($)),o=t.authorizationRequestCustomParams||{};return{type:f.OIDC,idpId:e,name:"OAuth provider",authorizationEndpoint:n.authorization_endpoint,clientId:t.clientId,responseType:"code",scope:Array.from(r).join(" "),extraParams:o,pkce:t.pkce}}function Re(e,t){return{type:f.SAML2,idpId:e,name:"SAML2 provider",ssoUrl:t.ssoUrl,issuerId:t.issuerId,entityId:t.entityId||t.issuerId}}function z(e){return Array.from(new Set((e.scopes||[]).concat($))).join(" ")}async function W(e,t,n){return await fetch(e,{method:"POST",body:new URLSearchParams({client_id:t.clientId,...t.clientSecret?{client_secret:t.clientSecret}:{},...n}).toString(),headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}}).then(r=>r.json())}async function Lt(e,t,n,r,o={}){return await W(e,r,{scope:z(r),code:t,redirect_uri:Y(n),grant_type:"authorization_code",...o})}async function Nt(e,t,n){return await W(e,n,{scope:z(n),grant_type:"refresh_token",refresh_token:t})}function Oe(e,{authorizationEndpoint:t,clientId:n,responseType:r,scope:o,extraParams:s,idpId:i,pkce:c},d,h,u){if(!t||!n||!r||!o)return{loginUrl:void 0};const a=new URL(t),_=u?.redirectUriOverride??`${e}${pe(V.OIDC_CALLBACK)}`,S={state:M(),idpId:i,redirectUri:_,redirectTo:d,branch:u?.branchOverride??De(e),inviteCode:h,source:u?.sourceOverride??"portal",uiLocales:u?.uiLocales},T={};if(c){const A=H(Ae(50)),E=H(oe("sha256").update(A).digest("base64")),k="S256";a.searchParams.append("code_challenge",E),a.searchParams.append("code_challenge_method",k),T.code_verifier={value:A,options:{secure:!0,httpOnly:!0,expires:new Date(Date.now()+1e3*60*10),path:me()||"/"}}}a.searchParams.append("client_id",n),a.searchParams.append("scope",o),a.searchParams.append("response_type",r),a.searchParams.append("redirect_uri",Y(_)),a.searchParams.append("state",ge(JSON.stringify(S))),u?.uiLocales&&a.searchParams.append("ui_locales",u.uiLocales);for(const A in s)s[A]!==void 0&&a.searchParams.append(A,s[A]);return{loginUrl:a.toString(),cookies:T}}function Dt(e,t,n,r){const o=new URL(e);return n&&(o.searchParams.append("post_logout_redirect_uri",t),r&&o.searchParams.append("state",r),o.searchParams.append("id_token_hint",n)),o.toString()}function Me(e,t){const n=R(t?.audience??[]);return!n.length||J(e,n)}function J(e,t){const n=[e.aud,e[ie]].flat();return t.some(r=>r!==""&&n.includes(r))}function Le(e,t){return!t||!x(t)?!0:Me(e,t)&&Ne(e,t)}function Ne(e,t){return!x(t)||!Ye(t)||!t.clientId?!0:R(e.aud||[]).includes(t.clientId)}function Ct(e){if(!e)return!1;try{return p.decode(e).header.alg===l.RS256}catch{return!1}}async function bt(e){const t=Math.floor(Date.now()/1e3),n=t+(e.ttlSec??600);return p.sign({type:g.MCP_AUTHORIZATION_CODE,client_id:e.clientId,redirect_uri:e.redirectUri,id_token_enc:le(e.idToken,y),...e.idpId?{idp_id:e.idpId}:{},...e.idpAccessTokenEnc?{idp_access_token_enc:e.idpAccessTokenEnc}:{},...e.idpRefreshTokenEnc?{idp_refresh_token_enc:e.idpRefreshTokenEnc}:{},...e.codeChallenge?{code_challenge:e.codeChallenge}:{},...e.codeChallengeMethod?{code_challenge_method:e.codeChallengeMethod}:{},iat:t,exp:n},y,l.HS256)}async function Pt(e){await p.verify(e,y,l.HS256);const{payload:t}=p.decode(e);if(t.type!==g.MCP_AUTHORIZATION_CODE)throw new Error("Invalid authorization code type");if(!t.client_id||!t.redirect_uri)throw new Error("Authorization code missing required claims");if(typeof t.exp=="number"&&Date.now()>=t.exp*1e3)throw new Error("Authorization code expired");if(typeof t.id_token_enc!="string")throw new Error("Authorization code missing session");return{...t,id_token:de(t.id_token_enc,y)}}async function vt(e){const t=Math.floor(Date.now()/1e3);return p.sign({type:g.MCP_REFRESH_TOKEN,client_id:e.clientId,...e.idpId?{idp_id:e.idpId}:{},claims:e.claims,...e.idpAccessTokenEnc?{idp_access_token_enc:e.idpAccessTokenEnc}:{},...e.idpRefreshTokenEnc?{idp_refresh_token_enc:e.idpRefreshTokenEnc}:{},session_exp:e.sessionExp,iat:t,exp:e.sessionExp,jti:M()},y,l.HS256)}async function jt(e){await p.verify(e,y,l.HS256);const{payload:t}=p.decode(e);if(t.type!==g.MCP_REFRESH_TOKEN)throw new Error("Invalid refresh token type");if(!t.client_id||typeof t.claims!="object"||t.claims===null)throw new Error("Refresh token missing required claims");if(typeof t.session_exp!="number")throw new Error("Refresh token missing session expiry");return t}function Ut(e){const t=e||se(),n=t.startsWith("mcp_")?t:`mcp_${t}`;return{id:n,object:"mcpSession",uri:`urn:redocly:realm:mcp:session:${n}`}}function Y(e){const t=B(e);if(!t)return e;const n=Ce(t.hostname);if(n)return t.hostname=`previewauth--${n.previewBranch}${n.after}`,q(e,t);const r=G(t.hostname);return r?(t.hostname=`${r.projectSlug}.previewauth.${r.after}`,q(e,t)):e}function De(e){const t=B(e);if(t)return G(t.hostname)?.previewBranch}function q(e,t){const n=e.replace(/^https?:\/\/[^/?#]+/i,"");return`${t.protocol}//${t.host}${fe(n)}`}function G(e){const t=e.split(".preview.",2);if(t.length<2)return null;const[n,r]=t,o=n.indexOf("--");if(o===-1)return null;const s=n.slice(0,o),i=n.slice(o+2);return!s||!i||i.includes(".")?null:{projectSlug:s,previewBranch:i,after:r}}function Ce(e){const t=e.indexOf("."),n=t===-1?e:e.slice(0,t);if(!n.startsWith("preview-"))return null;const r=n.indexOf("--");if(r===-1)return null;const o=n.slice(r+2);if(!o)return null;const s=t===-1?"":e.slice(t);return{previewBranch:o,after:s}}function be(e){return e.type===f.OIDC}function Pe(e){return e.type===f.SAML2}function Kt(e,t,n,r,o){return be(e)?Oe(t,e,n,r,{uiLocales:o}):Pe(e)?ve(t,e,n,r,o):{}}function ve(e,t,n,r,o){const i=`<samlp:AuthnRequest xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
|
|
2
2
|
xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
|
|
3
3
|
Version="2.0"
|
|
4
4
|
ID="_${M()}"
|
|
5
5
|
IssueInstant="${new Date().toISOString()}"
|
|
6
|
-
AssertionConsumerServiceURL="${e}${
|
|
6
|
+
AssertionConsumerServiceURL="${e}${V.SAML_CALLBACK}"
|
|
7
7
|
AttributeConsumingServiceIndex="0">
|
|
8
8
|
<saml:Issuer>${t.entityId}</saml:Issuer>
|
|
9
9
|
<samlp:NameIDPolicy
|
|
10
10
|
AllowCreate="true"
|
|
11
11
|
Format="urn:oasis:names:tc:SAML:2.0:nameid-format:persistent"/>
|
|
12
|
-
</samlp:AuthnRequest>`,c=je(i);return{loginUrl:ye(t.ssoUrl,{SAMLRequest:c,RelayState:JSON.stringify({idpId:t.idpId,redirectTo:n,inviteCode:r,source:"portal",uiLocales:o})})}}function je(e){return Te(
|
|
12
|
+
</samlp:AuthnRequest>`,c=je(i);return{loginUrl:ye(t.ssoUrl,{SAMLRequest:c,RelayState:JSON.stringify({idpId:t.idpId,redirectTo:n,inviteCode:r,source:"portal",uiLocales:o})})}}function je(e){return Te(ne(new TextEncoder().encode(e)).buffer)}function Vt(e){const t=F(e);if(t.startsWith("<samlp:Response")||t.indexOf("<saml2p:Response")>-1)return t;const n=re(new Uint8Array(atob(e).split("").map(r=>r.charCodeAt(0))));return new TextDecoder().decode(n)}function $t(e){try{return JSON.parse(F(e||""))}catch{throw new Error("Invalid OAuth2 state")}}function Bt(e){const t=new j().parseFromString(e,"application/xml"),r=m(t,"//*[local-name(.)='StatusCode']/@Value")[0]?.nodeValue?.endsWith("Success")||!1,s=m(t,"//*[local-name(.)='Response']/@Destination")[0]?.nodeValue||"",i=m(t,"//*[local-name(.)='Assertion']//*[local-name(.)='Issuer']/text()")[0],c=i&&i.nodeValue||void 0,d=m(t,"//*[local-name(.)='Audience']/text()")[0],h=d&&d.nodeValue||void 0,a=m(t,"//*[local-name(.)='Assertion']//*[local-name(.)='X509Certificate']/text()")[0]?.nodeValue||"",_=m(t,"//*[local-name(.)='Subject']//*[local-name(.)='NameID']/text()")[0],S=_&&_.nodeValue||"",T=m(t,"//*[local-name(.)='Subject']//*[local-name(.)='NameID']/@Format")[0],A=T&&T.nodeValue||"",E=m(t,"//*[local-name(.)='Conditions']/@NotOnOrAfter")[0],k=Ue(E),D={},C=m(t,"//*[local-name(.)='AttributeStatement']//*[local-name(.)='Attribute']");if(C.length)for(const b of C){const P=m(b,"./@Name")[0];if(P.nodeValue){const v=m(b,"./*[local-name(.)='AttributeValue']/text()")[0];v?.nodeValue&&(D[P.nodeValue]=v.nodeValue)}}return{uid:S,success:r,expiresAt:k,issuerId:c,entityId:h,attrs:D,cert:a,nameFormat:A,destination:s}}function Ue(e){const t=typeof e?.nodeValue=="string"&&L(Date.parse(e.nodeValue)),n=L(Date.now()),r=L(Date.now()+720*60*1e3);return t?t>n&&t<r?r:t:n}function L(e){return Math.floor(e/1e3)}const N={},w={jwks:{},missedAt:{}},Ke=6e4;function Ve(e){const t=w.jwks[e];return t===void 0?!0:t===null&&Date.now()-(w.missedAt[e]??0)>=Ke}async function Q(e,t){if(!N[e]){const n=t.configurationUrl?await X(t.configurationUrl):t.configuration;N[e]=$e()?Fe(n):n}return N[e]}function $e(){const e=ce.REDOCLY_ENFORCE_RESIDENCY;return!!e&&e.includes("host.docker.internal")}const Be=["authorization_endpoint","end_session_endpoint"];function Fe(e){if(typeof e!="object"||e===null)return e;const t={...e};for(const n of Object.keys(t)){if(Be.includes(String(n)))continue;const r=t[n];typeof r=="string"&&r.includes("://localhost")&&(t[n]=r.replace("://localhost","://host.docker.internal"))}return t}const He=["kty","n","e","crv","x","y"];function ze(e,t){return He.every(n=>e[n]===t[n])}async function We(e){const t={};for(const n of Object.keys(e)){const r=e[n];if(!x(r))continue;const o=await Q(n,r);if(o.jwks_uri){const s=await X(o.jwks_uri);for(const i of s.keys){const c=t[i.kid],d=c&&ze(c,i)?[...c.idpIds,n]:[n];t[i.kid]={...i,idpIds:d},w.jwks[i.kid]=t[i.kid]}}}}function Je(e,t,n){const r=w.jwks[e]?.idpIds??[];return r.find(o=>{const s=n[o];if(!x(s))return!1;const i=R(s.audience??[]);return J(t,i.length?i:[s.clientId])})??r.at(-1)}async function X(e){return fetch(e,{headers:{Accept:"application/json"}}).then(t=>t.json())}async function Ft(e){return fetch(`${K}/oidc/userinfo`,{headers:{Accept:"application/json",Authorization:`Bearer ${e}`}}).then(t=>t.status===200?t.json():void 0).catch(()=>{})}async function Ht(e){return fetch(`${K}/api/auth/organization-session/login-code/exchange`,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({code:e})}).then(t=>t.status===200?t.json():void 0).then(t=>typeof t?.token=="string"?t.token:void 0).catch(()=>{})}function Ye(e){if(!e.configurationUrl)return!1;const t=new URL(e.configurationUrl);return["localhost","127.0.0.1","blueharvest.cloud","bhstage.cloud","cloud.redocly.com","beta.redocly.com","cloud.eu.redocly.com","beta.eu.redocly.com"].some(r=>qe(t.hostname,r))}function qe(e,t){return e===t||e.endsWith(`.${t}`)}async function zt(e,t){const n=new j().parseFromString(e,"application/xml"),r=m(n,"//*[local-name(.)='Signature' and namespace-uri(.)='http://www.w3.org/2000/09/xmldsig#']")[0];if(!r)throw new Error("Cannot find Signature in the SAML response");const o=xe(t),s=new ee({publicCert:o});s.loadSignature(r);try{return s.checkSignature(e)}catch{return!1}}function Ge(e){const t=new Set,n=r=>{if(!(!r||typeof r!="object"||Array.isArray(r)))for(const[o,s]of Object.entries(r))typeof s=="string"?t.add(o):n(s)};return n(e),t}function Qe(e,t,n){if(!t)return e;const r=Ge(t),o=s=>{const i=n?.[s]||s;return r.has(i)||!!Se(t,i)};return[...e.filter(o),...e.filter(s=>!o(s))]}async function Wt(e,t,n,r){const o=n?e[n]:void 0,s=Array.isArray(o)?Qe(o.map(String),r?.rbacConfig,r?.teamsMapping):[];let i=s.length;const c=s.length+1;for(let d=0;d<c;d++){const h={...e,idpId:t};n&&s.length&&(h[n]=s.slice(0,i));const u=await p.sign(h,y,l.HS256),a=Buffer.byteLength(u)-ae;if(a<=0)return{token:u,teamsTotal:s.length,teamsKept:i,droppedTeams:s.slice(i)};if(i===0)return null;const _=Buffer.byteLength(JSON.stringify(s.slice(0,i))),S=Math.max(1,_/i*4/3);i=Math.max(0,i-Math.max(1,Math.ceil(a/S)))}return null}function Jt(e,t,n,r){t==="urn:oasis:names:tc:SAML:2.0:nameid-format:transient"&&(e=n["http://schemas.microsoft.com/identity/claims/objectidentifier"]);let o;(t==="urn:oasis:names:tc:SAML:2.0:nameid-format:email"||t==="urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress")&&(o=e),t==="urn:oasis:names:tc:SAML:2.0:nameid-format:persistent"&&e?.match(/^.+@.+/m)&&(o=e);const s=n["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name"],i=s?.match(/^.+@.+/m);return o=o||n["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress"]||(i?s:void 0),o=o?.toLowerCase(),{sub:e,given_name:n["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname"],family_name:n["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname"],name:n["http://schemas.microsoft.com/identity/claims/displayname"]||s,email:o,email_verified:!0,teams:r?we(n[r]):[]}}function Z(e,t={}){return e.map(n=>t[n]||n)}async function Yt(e,t){if(!t)return{};const n=t[I.AUTHORIZATION];if(!n)return{};try{const r=p.decode(n);if(typeof r.payload.type=="string"&&Ie.has(r.payload.type))return{};if(r.header.alg===l.RS256){const h=Ve(r.header.kid);h&&await We(e);const u=w.jwks[r.header.kid];if(!u)return h&&(w.missedAt[r.header.kid]=Date.now()),w.jwks[r.header.kid]=null,{};await p.verify(n,u,l.RS256)}else await p.verify(n,y,l.HS256);const s=r.header.alg===l.RS256?Je(r.header.kid,r.payload,e):r.payload.idpId,i=e[s]||{};if(r.header.alg===l.RS256&&typeof r.payload.exp!="number")return O.warn("Rejected id_token: it has no exp claim"),{};if(r.header.alg===l.RS256&&!Le(r.payload,i))return O.warn("Rejected id_token: it was issued for another project"),{};const c=et(i),d=Ze(i);return{...r.payload,email:r.payload.email?.toLowerCase(),idpId:s,teams:Array.from(new Set([...Z(r.payload.teams||[],d),..."defaultTeams"in i&&i.defaultTeams||[],...Z("teamsClaimName"in i&&r.payload[c||""]||[],d),he])),name:Xe(r.payload),isAuthenticated:!0,idpAccessToken:ue(r.payload.idp_access_token,y)||t[I.IDP_ACCESS_TOKEN],federatedAccessToken:t[I.FEDERATED_ACCESS_TOKEN],federatedIdToken:t[I.FEDERATED_ID_TOKEN],authCookie:n}}catch(r){r instanceof _e||O.error("Malformed JWT token: %s",r.message)}return{}}function Xe(e){return(e.firstName&&e.lastName?`${e.firstName} ${e.lastName}`:e.name||e.given_name||e.firstName||e.lastName)||e.email}function Ze(e){switch(e.type){case f.SAML2:return e.teamsAttributeMap;case f.OIDC:return e.teamsClaimMap;default:return}}function et(e){switch(e.type){case f.SAML2:return e.teamsAttributeName??U;case f.OIDC:return e.teamsClaimName;default:return U}}function m(e,t){return te.select(t,e)||[]}export{Ke as UNKNOWN_KID_RETRY_MS,Kt as buildLoginUrl,Oe as buildOidcLoginUrl,Dt as buildOidcLogoutUrl,ve as buildSAML2LoginUrl,bt as createMcpAuthorizationCode,vt as createMcpRefreshToken,Ut as createMcpSessionResource,Vt as decodeSamlResponse,We as discoverJwks,je as encodeSAML2,Ht as exchangeTokenLoginCode,Jt as extractUserClaims,Mt as getAuthProviderLoginParams,ke as getOidcLoginParams,Q as getOidcMetadata,Ft as getRedoclyTokenPayload,Re as getSaml2LoginParams,Yt as getUserParamsFromCookies,Xe as getUsernameFromPayload,Me as idTokenAudienceIsAllowed,Le as idTokenIsForThisProject,Ct as isIdpIssuedToken,x as isOidcProviderConfig,Ye as isRedoclySso,Ee as isSaml2ProviderConfig,Lt as oidcExchangeCodeForToken,w as oidcJwksCache,N as oidcMetadataCache,Nt as oidcRefreshTokenGrant,Qe as orderTeamsRbacFirst,$t as parseOidcState,De as parsePreviewBranch,Bt as parseSamlResponse,Y as rewritePreviewAuthRedirectUri,Wt as signTokenWithinCookieSizeLimit,Pt as verifyMcpAuthorizationCode,jt as verifyMcpRefreshToken,zt as verifySAMLResponse};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{setCookie as L,deleteCookie as P}from"hono/cookie";import{AuthProviderType as Y,DEFAULT_TEAM_CLAIM_NAME as Q}from"@redocly/config";import{withPathPrefix as w,getPathPrefix as A}from"@redocly/theme/core/utils";import{compareURIs as x}from"../../../utils/url/compare-uris.js";import{ensureArray as ee}from"../../../utils/array/ensure-array.js";import{ALTERNATIVE_AUD_CLAIM_NAME as re,JWT_SECRET_KEY as U,MAX_AUTH_TOKEN_COOKIE_BYTES as N,ORG_SLUG as oe,ORG_ID as te}from"../../constants/common.js";import{AUTH_SEGMENT as ne,ServerRoutes as k}from"../../../constants/api.js";import{AuthCookieNames as _,DEFAULT_COOKIE_EXPIRATION as B}from"../../../constants/common.js";import{sanitizeRedirectPathname as H}from"../../../utils/url/sanitize-redirect-pathname.js";import{telemetry as y}from"../../telemetry/index.js";import{envConfig as K}from"../../config/env-config.js";import{fetchWithClient as ie}from"../../utils/fetch-with-client.js";import{clearAuthCookies as z,clearPostLogoutCookie as v,hasPostLogoutCookie as se,setPostLogoutCookie as j}from"../../utils/cookie.js";import{getAuthProviderLoginParams as ae,isOidcProviderConfig as b,isSaml2ProviderConfig as de,oidcExchangeCodeForToken as le,buildLoginUrl as ce,decodeSamlResponse as ue,extractUserClaims as pe,parseSamlResponse as ge,parseOidcState as fe,verifySAMLResponse as me,getUsernameFromPayload as he,buildOidcLogoutUrl as Ce,isIdpIssuedToken as Ie,getOidcMetadata as J,getRedoclyTokenPayload as _e,idTokenAudienceIsAllowed as Ae,isRedoclySso as Oe,rewritePreviewAuthRedirectUri as Re,parsePreviewBranch as Te,buildOidcLoginUrl as Le,createMcpSessionResource as M,signTokenWithinCookieSizeLimit as G}from"../auth.js";import*as $ from"../jwt/jwt.js";import{AlgorithmTypes as E}from"../jwt/types.js";import{handleErrorPageRender as we}from"../utils.js";import{encodeBase64URL as ye}from"../jwt/encode.js";import{resolveUiLocalesForIdpLogin as Me}from"./helpers/resolve-ui-locales-for-idp-login.js";async function Ge(n,e){if(!e.devLogin||K.isProductionEnv)return n.newResponse(null,404,{});const{password:r,...a}=await n.req.json(),o=await $.sign({...a,name:a.username||a.email||"Unknown"},U,E.HS256);return L(n,_.AUTHORIZATION,o,{path:A()||"/",httpOnly:!0,secure:!0,sameSite:"none"}),v(n),n.newResponse(null,200,{})}function Ze(){return async n=>{const e=n.get("logger"),r=encodeURIComponent(n.req.query("message")||"");e.error(`Login error: ${r}`);const a=`${k.LOGIN}/?error=${encodeURIComponent(r)}`;return n.newResponse(null,301,{Location:a})}}function Z(n){if(!n||!n.includes(k.MCP_CALLBACK))return null;try{const e=n.split("/"),r=e[e.length-1];if(r){const a=Buffer.from(r,"base64url").toString("utf-8");return JSON.parse(a).mcpSessionId||null}}catch{}return null}function Ve(n){return async e=>{const r=e.get("logger"),a=n.getConfig().ssoDirect;let o;try{o=fe(e.req.query("state"))}catch{return r.warn("OIDC login error: Invalid OAuth2 state"),e.text("Bad request: Invalid OAuth2 state",400)}const C=o.idpId,i=o.source==="mcp"||o.redirectTo&&typeof o.redirectTo=="string"&&o.redirectTo.includes(k.MCP_CALLBACK),u=i?Z(typeof o.redirectTo=="string"?o.redirectTo:void 0):null,s=a?.[C];if(!b(s))return r.error("OIDC login error: missing OIDC provider config"),e.text("Forbidden",403);const p=await J(C,s);if(a&&!p.token_endpoint){const m="Invalid OIDC configuration: token_endpoint is required";return r.error(`OIDC login error: ${m}`),e.text(m,500)}try{const m=p.token_endpoint,f=e.req.query("code"),h=e.req.query("error");if(h)return i&&y.sendMcpAuthorizationFailedMessage([{...M(u),error:`OIDC error: ${h}`,error_details:e.req.query("error_description")||null}]),we(e,n,{slug:"/"},403,"403OIDC");if(!f){const g="Code is expected but not present";return r.error(`OIDC login error: ${g}`),i&&y.sendMcpAuthorizationFailedMessage([{...M(u),error:g,error_details:null}]),new Response(`Forbidden: ${g}`,{status:403})}const R=typeof o.redirectUri=="string"?o.redirectUri:new URL(w(k.OIDC_CALLBACK),e.req.url).toString(),I=e.get("cookies")?.code_verifier,d=await le(m,f,R,s,{...s.tokenRequestCustomParams,...I?{code_verifier:I}:{}});if(d.error)return r.error(`Error from OIDC provider: "${d.error}"`),i&&y.sendMcpAuthorizationFailedMessage([{...M(u),error:`Token exchange error: ${d.error}`,error_details:d.error_description||null}]),e.text(`Forbidden: ${d.error_description||d.error}`,403);if(!d?.id_token){const g="No id_token, please, add openid to scopes";return r.error(`OIDC login error: ${g}`),i&&y.sendMcpAuthorizationFailedMessage([{...M(u),error:g,error_details:null}]),new Response(`Forbidden: ${g}`,{status:403})}const{payload:l,header:T}=$.decode(d.id_token),t=T.alg===E.RS256;if(!Ae(l,s)){const g="No valid audience found in id_token";return r.error(`OIDC login error: ${g}`),i&&y.sendMcpAuthorizationFailedMessage([{...M(u),error:g,error_details:null}]),new Response(`Forbidden: ${g}`,{status:403})}let c=t?d.id_token:await $.sign({...l,idpId:C},U,E.HS256);if(Buffer.byteLength(c)>N){const g=await G(l,C,s.teamsClaimName,{rbacConfig:n.getConfig().access?.rbac,teamsMapping:s.teamsClaimMap});if(!g){const S=`The id_token claims are too large for the session cookie: ${Buffer.byteLength(JSON.stringify(l))} bytes of claims`;return r.error(`OIDC login error: ${S}`),i&&y.sendMcpAuthorizationFailedMessage([{...M(u),error:S,error_details:null}]),e.text(`Forbidden: ${S}`,403)}g.teamsKept<g.teamsTotal&&r.warn(`OIDC login: the "${s.teamsClaimName}" claim is too large for the session cookie size limit; kept ${g.teamsKept} of ${g.teamsTotal} values, with teams from the RBAC configuration first; RBAC ignores the dropped teams: ${JSON.stringify(g.droppedTeams)}`),c=g.token}he(l)||r.warn("To display your username, the required 'email' or 'full_profile' scope must be added to the identity provider configuration");const D=s?.tokenExpirationTime?Date.now()+s.tokenExpirationTime*1e3:l.exp*1e3||Date.now()+B*1e3;if(s.introspectEndpoint){const g=await fetch(s.introspectEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({access_token:d.access_token})});if(g.ok){const q=(await g.json()).ext?.federatedIdentity;q&&(L(e,_.FEDERATED_ACCESS_TOKEN,q.access_token||"",{path:A()||"/",httpOnly:!1,expires:new Date(D)}),L(e,_.FEDERATED_ID_TOKEN,q.id_token||"",{path:A()||"/",httpOnly:!1,expires:new Date(D)}))}else r.warn(`OIDC introspect error: ${g.statusText}`)}if(L(e,_.AUTHORIZATION,c,{path:A()||"/",httpOnly:!0,expires:new Date(D)}),c!==d.id_token&&Buffer.byteLength(d.id_token)<=N?L(e,_.IDP_ID_TOKEN,d.id_token||"",{path:A()||"/",httpOnly:!0,expires:new Date(D)}):P(e,_.IDP_ID_TOKEN,{path:A()||"/"}),L(e,_.IDP_ACCESS_TOKEN,d.access_token||"",{path:A()||"/",httpOnly:!0,expires:new Date(D)}),d.refresh_token?L(e,_.IDP_REFRESH_TOKEN,d.refresh_token,{path:A()||"/",httpOnly:!0,expires:new Date(D)}):P(e,_.IDP_REFRESH_TOKEN,{path:A()||"/"}),P(e,"code_verifier",{path:A()||"/"}),v(e),i&&o.redirectTo&&typeof o.redirectTo=="string"&&o.redirectTo.includes(k.MCP_CALLBACK)){const S=`${e.req.url.split("?")[0].replace(k.OIDC_CALLBACK,"")}${o.redirectTo}`;return e.newResponse(null,302,{Location:S})}const V=typeof o.redirectTo=="string"?o.redirectTo:void 0,W=H(new URL(V||"/",e.req.url).pathname),X=e.newResponse(null,302,{Location:W});return r.updateContext({email:l.email,subject:l.sub}),r.info("OIDC login successful"),X}catch(m){const f=m instanceof Error?m.message:String(m),h=m instanceof Error?m.stack:String(m);if(r.error(`OIDC login error: ${f}`),i&&y.sendMcpAuthorizationFailedMessage([{...M(u),error:f,error_details:h}]),m.error==="access_denied")return r.info("Access denied"),e.text("Forbidden",403)}const O="Something went wrong";return r.error(`OIDC login error: ${O}`),i&&y.sendMcpAuthorizationFailedMessage([{...M(u),error:O,error_details:null}]),e.text(O,500)}}function We(n){return async e=>{const r=e.get("logger"),o=e.get("auth").claims?.idpId,i=n.getConfig().ssoDirect?.[o];if(e.req.method==="POST")return b(i)||(z(e),j(e)),r.info("Logout successful"),e.newResponse(null,200,{});let u;if(b(i)){const s=(await J(o,i)).end_session_endpoint;if(s){const p=new URL(e.req.url),O=e.req.header("x-forwarded-proto")||p.protocol.slice(0,-1)||"https",m=e.req.header("x-forwarded-host")||p.host,f=`${O}://${m}`,h=Te(f),R=h?ye(JSON.stringify({branch:h,postLogoutRedirectUri:`${f}${w(k.POST_LOGOUT)}`})):void 0,I=h?`${Re(f)}/${ne}/logout`:`${f}${w(k.POST_LOGOUT)}`,d=e.get("cookies"),l=d?.[_.AUTHORIZATION],T=d?.[_.IDP_ID_TOKEN]||(Ie(l)?l:void 0);u=Ce(s,I,T,R)}}return r.info("Logout successful"),z(e),j(e),e.newResponse(null,302,{Location:u||w("/")})}}function Xe(n){return async e=>{const r=n.getConfig().access?.logoutReturnUrl,a=r||w("/");return e.newResponse(null,302,{Location:a})}}function Ye(n){return async e=>{const r=e.get("logger"),a=e.req.param("code"),o=K.BH_API_URL,C=(i,u,s)=>i&&u?`${i} ${u.charAt(0)}`:s;try{if(!o)throw new Error("BH_API_URL is not set");const i=n.getConfig().ssoDirect;if(!i||!Object.keys(i).length)return r.warn("Invite no sso configured to handle"),e.redirect(w("/"));const u=await ie(`${o}/public-user-invites/${a}`);if(!u.ok)return u.status===404?(r.warn(`Invite ${a} not found redirect to homepage`),e.redirect(w("/"))):(r.error("Invite error",await u.text()),e.redirect(w("/")));const s=await u.json(),p=new URL(w("/invite"),e.req.url);return p.searchParams.set("code",a),p.searchParams.set("org",s.organization.name),p.searchParams.set("invitedBy",C(s.invitedBy.firstName,s.invitedBy.lastName,s.invitedBy.name)),e.newResponse(null,302,{Location:p.toString()})}catch(i){return r.error("Error processing invite",{error:i,inviteCode:a}),e.text(i.message||"Failed to process invite",400)}}}function Qe(n){return async e=>{const r=e.get("logger"),a=n.getConfig().ssoDirect,o=new URL(e.req.url),C=e.req.query("inviteCode"),i=e.req.header("x-forwarded-proto")||o.protocol.slice(0,-1)||"https",u=e.req.header("x-forwarded-host")||o.host,s=`${i}://${u}`;let p=o.searchParams.get("idpId");const O=o.searchParams.get("redirectTo"),m=Object.keys(a||{})[0];p=p||m;const f=o.searchParams.get("mcp_redirect_uri"),h=!!f;if(!a?.[p]){const c="Invalid idpId";if(r.error(`IdP login error: ${c}`),h){const F=Z(O||void 0);y.sendMcpAuthorizationFailedMessage([{...M(F),error:c,error_details:null}])}return e.text(`Forbidden: ${c}`,403)}const I=Me({localePrefixParam:o.searchParams.get("localePrefix"),l10n:n.getGlobalData()?.l10n}),d=p&&a?await ae(p,a[p]):void 0,l={};for(const c of Object.keys(d?.extraParams||{}))l[c]=o.searchParams.get(c)||d?.extraParams?.[c]||void 0;se(e)&&(l.prompt="login",l.post_logout="1");let T,t={};if(h&&f&&d&&d.type===Y.OIDC){r.info(`Building MCP OAuth login URL with redirect_uri: ${f}`);const c=Le("",{...d,extraParams:l},O,C,{redirectUriOverride:f,sourceOverride:"mcp",branchOverride:void 0,uiLocales:I});T=c.loginUrl,t=c.cookies||{}}else if(d){const c=ce({...d,extraParams:l},s,O,C,I);T=c.loginUrl,t=c.cookies||{}}return Object.keys(t).forEach(c=>{L(e,c,t[c].value,t[c].options)}),r.info(`IdP login initiated for ID '${p}'`),e.newResponse(null,302,{Location:T||new URL(e.req.url).pathname})}}function xe(n){return async e=>{const r=e.get("logger"),a=await e.req.formData(),o=a.get("SAMLResponse"),C=a.get("RelayState");if(typeof o!="string"||typeof C!="string"){const t="SAMLResponse is required";return r.error(`SAML2 login error: ${t}`),e.text(`Bad request: ${t}`,400)}const i=ue(o),{success:u,uid:s,nameFormat:p,attrs:O,issuerId:m,expiresAt:f}=ge(i),{idpId:h,redirectTo:R}=JSON.parse(C);if(!u){const t="SAML2 assertion is not successful";return r.error(`SAML2 login error: ${t}`),e.text(`Permission denied: ${t}`,401)}if(!f||Math.ceil(Date.now()/1e3)>=f){const t="SAML2 Token Expired";return r.error(`SAML2 login error: ${t}`),e.text(t,401)}const I=n.getConfig().ssoDirect?.[h];if(!I||!de(I)){const t="Cannot find valid IdP";return r.error(`SAML2 login error: ${t}`),e.text(`Permission denied: ${t}`,401)}if(!(I.issuerId&&m&&x(I.issuerId,m))){const t="IssuerID is misconfigured or untrusted assertions issuer received";return r.error(`SAML2 login error: ${t}`),e.text(`Permission denied: ${t}`,401)}if(!await me(i,I.x509PublicCert)){const t="SAMLResponse signature invalid";return r.error(`SAML2 login error: ${t}`),e.text(t,401)}const l=pe(s,p,O,I.teamsAttributeName??Q);if(!l.sub){const t="The provider did not return a valid user identity.";return r.error(`SAML2 login error: ${t}`),e.text(t,400)}if(!l.email){const t="The provider did not return a valid user email.";return r.error(`SAML2 login error: ${t}`),e.text(t,400)}let T=await $.sign({...l,idpId:h},U,E.HS256);if(Buffer.byteLength(T)>N){const t=await G({...l},h,"teams",{rbacConfig:n.getConfig().access?.rbac,teamsMapping:I.teamsAttributeMap});if(!t){const c=`The SAML2 claims are too large for the session cookie: ${Buffer.byteLength(JSON.stringify(l))} bytes of claims`;return r.error(`SAML2 login error: ${c}`),e.text(`Forbidden: ${c}`,403)}t.teamsKept<t.teamsTotal&&r.warn(`SAML2 login: the "teams" claim is too large for the session cookie size limit; kept ${t.teamsKept} of ${t.teamsTotal} values, with teams from the RBAC configuration first; RBAC ignores the dropped teams: ${JSON.stringify(t.droppedTeams)}`),T=t.token}return L(e,_.AUTHORIZATION,T,{path:A()||"/",httpOnly:!0,expires:new Date(f*1e3)}),P(e,_.IDP_REFRESH_TOKEN,{path:A()||"/"}),v(e),r.updateContext({email:l.email,subject:l.sub}),r.info("SAML2 login successful"),e.newResponse(null,302,{Location:R||"/"})}}function er(n){return async e=>{const r=e.get("logger"),a=new URL(e.req.query("redirectTo")||"/",e.req.url),o=w(H(a.pathname)),C=n.getConfig().ssoDirect,i=Object.entries(C||{}).find(([,R])=>b(R)&&Oe(R));if(!(C&&i))return e.newResponse(null,302,{Location:o});const s=e.req.query("token"),p=s&&await _e(s);if(!p)return e.newResponse(null,302,{Location:o});if(!ee(p[re]||[]).some(R=>R===oe||R===te))return e.newResponse(null,302,{Location:o});const f=await $.sign({...p,idpId:i?.at(0)},U,E.HS256),h=Date.now()+B*1e3;return L(e,_.AUTHORIZATION,f,{path:A()||"/",httpOnly:!0,expires:new Date(h),sameSite:"None",secure:!0}),P(e,_.IDP_REFRESH_TOKEN,{path:A()||"/"}),v(e),r.info("Token login successful"),e.newResponse(null,302,{Location:o})}}export{Ge as authorizeHandler,Qe as idpLoginHandler,Ye as inviteHandler,We as logoutHandler,Ve as oidcCallbackHandler,Xe as postLogoutHandler,Ze as redoclyLoginCallbackHandler,er as redoclyTokenLoginHandler,xe as samlCallbackHandler};
|
|
1
|
+
import{setCookie as T,deleteCookie as P}from"hono/cookie";import{AuthProviderType as Y,DEFAULT_TEAM_CLAIM_NAME as Q}from"@redocly/config";import{withPathPrefix as L,getPathPrefix as O}from"@redocly/theme/core/utils";import{compareURIs as x}from"../../../utils/url/compare-uris.js";import{ensureArray as ee}from"../../../utils/array/ensure-array.js";import{ALTERNATIVE_AUD_CLAIM_NAME as re,JWT_SECRET_KEY as U,MAX_AUTH_TOKEN_COOKIE_BYTES as N,ORG_SLUG as oe,ORG_ID as te}from"../../constants/common.js";import{AUTH_SEGMENT as ne,ServerRoutes as M}from"../../../constants/api.js";import{AuthCookieNames as A,DEFAULT_COOKIE_EXPIRATION as B}from"../../../constants/common.js";import{sanitizeRedirectPathname as H}from"../../../utils/url/sanitize-redirect-pathname.js";import{telemetry as w}from"../../telemetry/index.js";import{envConfig as K}from"../../config/env-config.js";import{fetchWithClient as ie}from"../../utils/fetch-with-client.js";import{clearAuthCookies as z,clearPostLogoutCookie as v,hasPostLogoutCookie as se,setPostLogoutCookie as j}from"../../utils/cookie.js";import{getAuthProviderLoginParams as ae,isOidcProviderConfig as b,isSaml2ProviderConfig as de,oidcExchangeCodeForToken as ce,buildLoginUrl as le,decodeSamlResponse as ue,extractUserClaims as pe,parseSamlResponse as ge,parseOidcState as fe,verifySAMLResponse as me,getUsernameFromPayload as he,buildOidcLogoutUrl as Ce,isIdpIssuedToken as Ie,getOidcMetadata as J,exchangeTokenLoginCode as _e,getRedoclyTokenPayload as Ae,idTokenAudienceIsAllowed as Oe,isRedoclySso as Re,rewritePreviewAuthRedirectUri as Te,parsePreviewBranch as Le,buildOidcLoginUrl as we,createMcpSessionResource as y,signTokenWithinCookieSizeLimit as G}from"../auth.js";import*as $ from"../jwt/jwt.js";import{AlgorithmTypes as E}from"../jwt/types.js";import{handleErrorPageRender as ye}from"../utils.js";import{encodeBase64URL as ke}from"../jwt/encode.js";import{resolveUiLocalesForIdpLogin as Me}from"./helpers/resolve-ui-locales-for-idp-login.js";async function Ze(n,e){if(!e.devLogin||K.isProductionEnv)return n.newResponse(null,404,{});const{password:r,...a}=await n.req.json(),o=await $.sign({...a,name:a.username||a.email||"Unknown"},U,E.HS256);return T(n,A.AUTHORIZATION,o,{path:O()||"/",httpOnly:!0,secure:!0,sameSite:"none"}),v(n),n.newResponse(null,200,{})}function Ve(){return async n=>{const e=n.get("logger"),r=encodeURIComponent(n.req.query("message")||"");e.error(`Login error: ${r}`);const a=`${M.LOGIN}/?error=${encodeURIComponent(r)}`;return n.newResponse(null,301,{Location:a})}}function Z(n){if(!n||!n.includes(M.MCP_CALLBACK))return null;try{const e=n.split("/"),r=e[e.length-1];if(r){const a=Buffer.from(r,"base64url").toString("utf-8");return JSON.parse(a).mcpSessionId||null}}catch{}return null}function We(n){return async e=>{const r=e.get("logger"),a=n.getConfig().ssoDirect;let o;try{o=fe(e.req.query("state"))}catch{return r.warn("OIDC login error: Invalid OAuth2 state"),e.text("Bad request: Invalid OAuth2 state",400)}const I=o.idpId,i=o.source==="mcp"||o.redirectTo&&typeof o.redirectTo=="string"&&o.redirectTo.includes(M.MCP_CALLBACK),u=i?Z(typeof o.redirectTo=="string"?o.redirectTo:void 0):null,s=a?.[I];if(!b(s))return r.error("OIDC login error: missing OIDC provider config"),e.text("Forbidden",403);const g=await J(I,s);if(a&&!g.token_endpoint){const m="Invalid OIDC configuration: token_endpoint is required";return r.error(`OIDC login error: ${m}`),e.text(m,500)}try{const m=g.token_endpoint,h=e.req.query("code"),C=e.req.query("error");if(C)return i&&w.sendMcpAuthorizationFailedMessage([{...y(u),error:`OIDC error: ${C}`,error_details:e.req.query("error_description")||null}]),ye(e,n,{slug:"/"},403,"403OIDC");if(!h){const p="Code is expected but not present";return r.error(`OIDC login error: ${p}`),i&&w.sendMcpAuthorizationFailedMessage([{...y(u),error:p,error_details:null}]),new Response(`Forbidden: ${p}`,{status:403})}const k=typeof o.redirectUri=="string"?o.redirectUri:new URL(L(M.OIDC_CALLBACK),e.req.url).toString(),f=e.get("cookies")?.code_verifier,d=await ce(m,h,k,s,{...s.tokenRequestCustomParams,...f?{code_verifier:f}:{}});if(d.error)return r.error(`Error from OIDC provider: "${d.error}"`),i&&w.sendMcpAuthorizationFailedMessage([{...y(u),error:`Token exchange error: ${d.error}`,error_details:d.error_description||null}]),e.text(`Forbidden: ${d.error_description||d.error}`,403);if(!d?.id_token){const p="No id_token, please, add openid to scopes";return r.error(`OIDC login error: ${p}`),i&&w.sendMcpAuthorizationFailedMessage([{...y(u),error:p,error_details:null}]),new Response(`Forbidden: ${p}`,{status:403})}const{payload:c,header:R}=$.decode(d.id_token),t=R.alg===E.RS256;if(!Oe(c,s)){const p="No valid audience found in id_token";return r.error(`OIDC login error: ${p}`),i&&w.sendMcpAuthorizationFailedMessage([{...y(u),error:p,error_details:null}]),new Response(`Forbidden: ${p}`,{status:403})}let l=t?d.id_token:await $.sign({...c,idpId:I},U,E.HS256);if(Buffer.byteLength(l)>N){const p=await G(c,I,s.teamsClaimName,{rbacConfig:n.getConfig().access?.rbac,teamsMapping:s.teamsClaimMap});if(!p){const S=`The id_token claims are too large for the session cookie: ${Buffer.byteLength(JSON.stringify(c))} bytes of claims`;return r.error(`OIDC login error: ${S}`),i&&w.sendMcpAuthorizationFailedMessage([{...y(u),error:S,error_details:null}]),e.text(`Forbidden: ${S}`,403)}p.teamsKept<p.teamsTotal&&r.warn(`OIDC login: the "${s.teamsClaimName}" claim is too large for the session cookie size limit; kept ${p.teamsKept} of ${p.teamsTotal} values, with teams from the RBAC configuration first; RBAC ignores the dropped teams: ${JSON.stringify(p.droppedTeams)}`),l=p.token}he(c)||r.warn("To display your username, the required 'email' or 'full_profile' scope must be added to the identity provider configuration");const D=s?.tokenExpirationTime?Date.now()+s.tokenExpirationTime*1e3:c.exp*1e3||Date.now()+B*1e3;if(s.introspectEndpoint){const p=await fetch(s.introspectEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({access_token:d.access_token})});if(p.ok){const q=(await p.json()).ext?.federatedIdentity;q&&(T(e,A.FEDERATED_ACCESS_TOKEN,q.access_token||"",{path:O()||"/",httpOnly:!1,expires:new Date(D)}),T(e,A.FEDERATED_ID_TOKEN,q.id_token||"",{path:O()||"/",httpOnly:!1,expires:new Date(D)}))}else r.warn(`OIDC introspect error: ${p.statusText}`)}if(T(e,A.AUTHORIZATION,l,{path:O()||"/",httpOnly:!0,expires:new Date(D)}),l!==d.id_token&&Buffer.byteLength(d.id_token)<=N?T(e,A.IDP_ID_TOKEN,d.id_token||"",{path:O()||"/",httpOnly:!0,expires:new Date(D)}):P(e,A.IDP_ID_TOKEN,{path:O()||"/"}),T(e,A.IDP_ACCESS_TOKEN,d.access_token||"",{path:O()||"/",httpOnly:!0,expires:new Date(D)}),d.refresh_token?T(e,A.IDP_REFRESH_TOKEN,d.refresh_token,{path:O()||"/",httpOnly:!0,expires:new Date(D)}):P(e,A.IDP_REFRESH_TOKEN,{path:O()||"/"}),P(e,"code_verifier",{path:O()||"/"}),v(e),i&&o.redirectTo&&typeof o.redirectTo=="string"&&o.redirectTo.includes(M.MCP_CALLBACK)){const S=`${e.req.url.split("?")[0].replace(M.OIDC_CALLBACK,"")}${o.redirectTo}`;return e.newResponse(null,302,{Location:S})}const V=typeof o.redirectTo=="string"?o.redirectTo:void 0,W=H(new URL(V||"/",e.req.url).pathname),X=e.newResponse(null,302,{Location:W});return r.updateContext({email:c.email,subject:c.sub}),r.info("OIDC login successful"),X}catch(m){const h=m instanceof Error?m.message:String(m),C=m instanceof Error?m.stack:String(m);if(r.error(`OIDC login error: ${h}`),i&&w.sendMcpAuthorizationFailedMessage([{...y(u),error:h,error_details:C}]),m.error==="access_denied")return r.info("Access denied"),e.text("Forbidden",403)}const _="Something went wrong";return r.error(`OIDC login error: ${_}`),i&&w.sendMcpAuthorizationFailedMessage([{...y(u),error:_,error_details:null}]),e.text(_,500)}}function Xe(n){return async e=>{const r=e.get("logger"),o=e.get("auth").claims?.idpId,i=n.getConfig().ssoDirect?.[o];if(e.req.method==="POST")return b(i)||(z(e),j(e)),r.info("Logout successful"),e.newResponse(null,200,{});let u;if(b(i)){const s=(await J(o,i)).end_session_endpoint;if(s){const g=new URL(e.req.url),_=e.req.header("x-forwarded-proto")||g.protocol.slice(0,-1)||"https",m=e.req.header("x-forwarded-host")||g.host,h=`${_}://${m}`,C=Le(h),k=C?ke(JSON.stringify({branch:C,postLogoutRedirectUri:`${h}${L(M.POST_LOGOUT)}`})):void 0,f=C?`${Te(h)}/${ne}/logout`:`${h}${L(M.POST_LOGOUT)}`,d=e.get("cookies"),c=d?.[A.AUTHORIZATION],R=d?.[A.IDP_ID_TOKEN]||(Ie(c)?c:void 0);u=Ce(s,f,R,k)}}return r.info("Logout successful"),z(e),j(e),e.newResponse(null,302,{Location:u||L("/")})}}function Ye(n){return async e=>{const r=n.getConfig().access?.logoutReturnUrl,a=r||L("/");return e.newResponse(null,302,{Location:a})}}function Qe(n){return async e=>{const r=e.get("logger"),a=e.req.param("code"),o=K.BH_API_URL,I=(i,u,s)=>i&&u?`${i} ${u.charAt(0)}`:s;try{if(!o)throw new Error("BH_API_URL is not set");const i=n.getConfig().ssoDirect;if(!i||!Object.keys(i).length)return r.warn("Invite no sso configured to handle"),e.redirect(L("/"));const u=await ie(`${o}/public-user-invites/${a}`);if(!u.ok)return u.status===404?(r.warn(`Invite ${a} not found redirect to homepage`),e.redirect(L("/"))):(r.error("Invite error",await u.text()),e.redirect(L("/")));const s=await u.json(),g=new URL(L("/invite"),e.req.url);return g.searchParams.set("code",a),g.searchParams.set("org",s.organization.name),g.searchParams.set("invitedBy",I(s.invitedBy.firstName,s.invitedBy.lastName,s.invitedBy.name)),e.newResponse(null,302,{Location:g.toString()})}catch(i){return r.error("Error processing invite",{error:i,inviteCode:a}),e.text(i.message||"Failed to process invite",400)}}}function xe(n){return async e=>{const r=e.get("logger"),a=n.getConfig().ssoDirect,o=new URL(e.req.url),I=e.req.query("inviteCode"),i=e.req.header("x-forwarded-proto")||o.protocol.slice(0,-1)||"https",u=e.req.header("x-forwarded-host")||o.host,s=`${i}://${u}`;let g=o.searchParams.get("idpId");const _=o.searchParams.get("redirectTo"),m=Object.keys(a||{})[0];g=g||m;const h=o.searchParams.get("mcp_redirect_uri"),C=!!h;if(!a?.[g]){const l="Invalid idpId";if(r.error(`IdP login error: ${l}`),C){const F=Z(_||void 0);w.sendMcpAuthorizationFailedMessage([{...y(F),error:l,error_details:null}])}return e.text(`Forbidden: ${l}`,403)}const f=Me({localePrefixParam:o.searchParams.get("localePrefix"),l10n:n.getGlobalData()?.l10n}),d=g&&a?await ae(g,a[g]):void 0,c={};for(const l of Object.keys(d?.extraParams||{}))c[l]=o.searchParams.get(l)||d?.extraParams?.[l]||void 0;se(e)&&(c.prompt="login",c.post_logout="1");let R,t={};if(C&&h&&d&&d.type===Y.OIDC){r.info(`Building MCP OAuth login URL with redirect_uri: ${h}`);const l=we("",{...d,extraParams:c},_,I,{redirectUriOverride:h,sourceOverride:"mcp",branchOverride:void 0,uiLocales:f});R=l.loginUrl,t=l.cookies||{}}else if(d){const l=le({...d,extraParams:c},s,_,I,f);R=l.loginUrl,t=l.cookies||{}}return Object.keys(t).forEach(l=>{T(e,l,t[l].value,t[l].options)}),r.info(`IdP login initiated for ID '${g}'`),e.newResponse(null,302,{Location:R||new URL(e.req.url).pathname})}}function er(n){return async e=>{const r=e.get("logger"),a=await e.req.formData(),o=a.get("SAMLResponse"),I=a.get("RelayState");if(typeof o!="string"||typeof I!="string"){const t="SAMLResponse is required";return r.error(`SAML2 login error: ${t}`),e.text(`Bad request: ${t}`,400)}const i=ue(o),{success:u,uid:s,nameFormat:g,attrs:_,issuerId:m,expiresAt:h}=ge(i),{idpId:C,redirectTo:k}=JSON.parse(I);if(!u){const t="SAML2 assertion is not successful";return r.error(`SAML2 login error: ${t}`),e.text(`Permission denied: ${t}`,401)}if(!h||Math.ceil(Date.now()/1e3)>=h){const t="SAML2 Token Expired";return r.error(`SAML2 login error: ${t}`),e.text(t,401)}const f=n.getConfig().ssoDirect?.[C];if(!f||!de(f)){const t="Cannot find valid IdP";return r.error(`SAML2 login error: ${t}`),e.text(`Permission denied: ${t}`,401)}if(!(f.issuerId&&m&&x(f.issuerId,m))){const t="IssuerID is misconfigured or untrusted assertions issuer received";return r.error(`SAML2 login error: ${t}`),e.text(`Permission denied: ${t}`,401)}if(!await me(i,f.x509PublicCert)){const t="SAMLResponse signature invalid";return r.error(`SAML2 login error: ${t}`),e.text(t,401)}const c=pe(s,g,_,f.teamsAttributeName??Q);if(!c.sub){const t="The provider did not return a valid user identity.";return r.error(`SAML2 login error: ${t}`),e.text(t,400)}if(!c.email){const t="The provider did not return a valid user email.";return r.error(`SAML2 login error: ${t}`),e.text(t,400)}let R=await $.sign({...c,idpId:C},U,E.HS256);if(Buffer.byteLength(R)>N){const t=await G({...c},C,"teams",{rbacConfig:n.getConfig().access?.rbac,teamsMapping:f.teamsAttributeMap});if(!t){const l=`The SAML2 claims are too large for the session cookie: ${Buffer.byteLength(JSON.stringify(c))} bytes of claims`;return r.error(`SAML2 login error: ${l}`),e.text(`Forbidden: ${l}`,403)}t.teamsKept<t.teamsTotal&&r.warn(`SAML2 login: the "teams" claim is too large for the session cookie size limit; kept ${t.teamsKept} of ${t.teamsTotal} values, with teams from the RBAC configuration first; RBAC ignores the dropped teams: ${JSON.stringify(t.droppedTeams)}`),R=t.token}return T(e,A.AUTHORIZATION,R,{path:O()||"/",httpOnly:!0,expires:new Date(h*1e3)}),P(e,A.IDP_REFRESH_TOKEN,{path:O()||"/"}),v(e),r.updateContext({email:c.email,subject:c.sub}),r.info("SAML2 login successful"),e.newResponse(null,302,{Location:k||"/"})}}function rr(n){return async e=>{const r=e.get("logger"),a=new URL(e.req.query("redirectTo")||"/",e.req.url),o=L(H(a.pathname)),I=n.getConfig().ssoDirect,i=Object.entries(I||{}).find(([,f])=>b(f)&&Re(f));if(!(I&&i))return e.newResponse(null,302,{Location:o});const s=e.req.query("code"),g=s?await _e(s):e.req.query("token"),_=g&&await Ae(g);if(!_)return e.newResponse(null,302,{Location:o});if(!ee(_[re]||[]).some(f=>f===oe||f===te))return e.newResponse(null,302,{Location:o});const C=await $.sign({..._,idpId:i?.at(0)},U,E.HS256),k=Date.now()+B*1e3;return T(e,A.AUTHORIZATION,C,{path:O()||"/",httpOnly:!0,expires:new Date(k),sameSite:"None",secure:!0,partitioned:!0}),P(e,A.IDP_REFRESH_TOKEN,{path:O()||"/"}),v(e),r.info("Token login successful"),e.newResponse(null,302,{Location:o})}}export{Ze as authorizeHandler,xe as idpLoginHandler,Qe as inviteHandler,Xe as logoutHandler,We as oidcCallbackHandler,Ye as postLogoutHandler,Ve as redoclyLoginCallbackHandler,rr as redoclyTokenLoginHandler,er as samlCallbackHandler};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import m from"path";import{realpath as
|
|
1
|
+
import m from"path";import{realpath as G}from"fs/promises";import{REDOCLY_ROUTE_RBAC as z,REDOCLY_TEAMS_RBAC as j}from"@redocly/config";import{combineUrls as V,withoutPathPrefix as ie,withPathPrefix as R}from"@redocly/theme/core/utils";import{CACHE_CONTROL_NO_STORE_HEADER_VALUE as W,CACHE_CONTROL_PUBLIC_HTML as ae,DEFAULT_IMMUTABLE_CACHE_MAX_AGE as se,DEPRECATED_PUBLIC_API_DEFINITIONS_FOLDER as ce,PAGE_DATA_FOLDER as le,PUBLIC_API_DEFINITIONS_FOLDER as me,PUBLIC_ASSETS_FOLDER as ue,STATIC_DATA_FOLDER as de,X_REDOCLY_CACHE_CONTROL_HEADER as fe,X_REDOCLY_CACHE_CONTROL_PUBLIC_HTML as ge}from"../../constants/common.js";import{removeTrailingSlash as Z}from"../../../utils/url/remove-trailing-slash.js";import{findInIterable as pe}from"../../../utils/collection/find-in-iterable.js";import{sanitizeRedirectPathname as he}from"../../../utils/url/sanitize-redirect-pathname.js";import{envConfig as Re}from"../../config/env-config.js";import{addLeadingSlash as Ae}from"../../../utils/url/add-leading-slash.js";import{isPathInFolder as D}from"../../../utils/path/is-path-in-folder.js";import{getLlmsTxtMdPathBySlug as Ee}from"../../utils/llmstxt/get-llms-txt-md-path-by-slug.js";import{resolveLlmsTxtMd as J}from"../../utils/llmstxt/resolve-llms-txt-md.js";import{removeLeadingSlash as I}from"../../../utils/url/remove-leading-slash.js";import{decodeRequestPath as Ce}from"../../utils/decode-request-path.js";import{AI_INDEX_EXPORT_FOLDER as _e,SEARCH_DATA_EXPORT_FOLDER as Le}from"../../constants/plugins/search.js";import{processRedirects as Te}from"./helpers/process-redirects.js";import{renderPage as Pe,getServerProps as Oe}from"../../ssr/index.js";import{canAccessAsset as we,canAccessResource as K}from"../../utils/rbac.js";import{handleErrorPageRender as A,handleUnauthorized as Q,handleUnauthorizedAsset as x}from"../utils.js";import{DEFAULT_MAX_AGE_FOR_MIME_TYPE as De,MIME_TYPES as Ie}from"../mime-types.js";import{fileExistsAsync as Se}from"../../utils/index.js";import{isAiAgentRequest as ye}from"../../utils/ai-agent-detection.js";import{getRedirectRoute as Ue}from"../utils/legacy-openapi-redirects.js";import{getContentTypeHeaderValue as ee}from"../utils/content-type.js";import{telemetry as be}from"../../../cli/telemetry/index.js";import{telemetry as Me}from"../../telemetry/index.js";const Fe=[Le,_e,de,I(me),I(ce),le];async function qe(e,E){try{const[C,u]=await Promise.all([G(e),G(E)]);return Fe.some(t=>D(C,m.join(u,t)))}catch{return!1}}function mt(e,E,C,u){return async t=>{const S=t.get("logger"),i=t.req,c=new URL(i.url),_=c.pathname.replace(/\/{2,}/g,"/"),y=Ce(_);if(y===void 0)return t.text("Bad Request",400);const d=Re.isProductionEnv?301:302;if(_!==c.pathname)return t.newResponse(null,d,{Location:_+c.search});const r=ie(y),U=m.parse(r).ext.toLowerCase()===".md",b=ye({accept:i.header("accept"),signatureAgent:i.header("signature-agent"),signature:i.header("signature"),signatureInput:i.header("signature-input"),userAgent:i.header("user-agent")}),a=Ae(Z(r)),o=(i.method==="GET"||i.method==="HEAD")&&!U?e.getRouteBySlug(a,{followRedirect:!1})||pe(e.routesBySlug?.values(),n=>n.hasClientRoutes&&(r===n.slug||r.startsWith(n.slug+"/"))):void 0,M=e.getRedirect(a);if(M){const n=Te({redirect:M,reqUrlSearch:c.search});return Me.sendRedirectMessage([{id:a,object:"redirect",uri:`urn:redocly:realm:api:redirect:${a}`,from:a,templateId:n.type.toString()}]),t.newResponse(null,n.type,{Location:n.location})}if(o?.metadata?.type==="openapi"){const n=Ue(c.pathname);if(n)return S.info("Legacy OpenAPI docs redirect from "+c.pathname),t.newResponse(null,d,{Location:encodeURI(n)});if(r.match(/[A-Z]/))return S.warn("Redirect to lowercase route to avoid 404 error"),t.newResponse(null,d,{Location:encodeURI(R(r.toLowerCase()))})}if(r.endsWith("/")&&r!=="/"){const n=he(new URL(a||"/",t.req.url).pathname);return t.newResponse(null,d,{Location:R((n==="/"?"/":Z(n))+c.search)})}const{isAuthenticated:f,teams:L,claims:{email:T}}=t.get("auth");if(o&&!K(o,{isAuthenticated:f,email:T,teams:L},e.config.access?.rbac,e.config.access?.requiresLogin))return f?A(t,e,{slug:o.slug,[j]:o[j],[z]:o[z]},403):Q(t,e,o.slug);const g=o&&b?Ee(o.slug):void 0,F=g?await J(g,e,u):void 0,P=F?.exists??!1;if(o&&(!b||!P)){const n=await E(o),N=await Oe(o,t,n,e),{html:ne,statusCode:X,error:oe}=await Pe(o,N,t,e,be),Y=e.config.access?.rbac,$=!e.config.access?.requiresLogin&&(!Y||!Object.keys(Y).length),k=X>=400||!!oe||!!e.compilationErrors?.length,re=$&&!k;let h;return k?h=W:$?h=ae:h="private",t.html(ne,X,{"Cache-Control":h,...re&&{[fe]:ge}})}const p=g&&P?g:r,te=I(p),s=m.resolve(e.outdir,te);if(!D(s,e.outdir))return x(t);const q=U?await J(r,e,u):void 0,l=q?.route;if(l&&!K(l,{isAuthenticated:f,email:T,teams:L},e.config.access?.rbac,e.config.access?.requiresLogin))return Q(t,e,r);if(!P&&!l){if(await qe(s,e.outdir))return A(t,e,{slug:a},404);const n=e.getGlobalConfig("access");if(!we(p,n?.rbac||{},n?.requiresLogin||!1,e.getGlobalConfig("directoryPaths"),{isAuthenticated:f,email:T,teams:L}))return D(p,ue)?x(t):A(t,e,{slug:a},404)}const O=Ie[m.extname(s)]||"text/plain",w=s.match(/assets\/.*\.[a-f0-9]{8,}\..+/)||s.match(/runtime\/chunks\/.*/)?se:De[O],H=w?{"Cache-Control":`public, max-age=${w}, immutable`,Expires:new Date(Date.now()+w*1e3).toUTCString()}:{"Cache-Control":W},B=i.query("download")!=null,v=F?.content??q?.content;if(v!==void 0)return t.newResponse(v,200,{"Content-Type":ee(O),"Access-Control-Allow-Origin":"*",...H,...l&&{"X-Robots-Tag":"noindex, follow",...e.config.seo?.siteUrl&&{Link:`<${V(e.config.seo.siteUrl,R(l.slug))}>; rel="canonical"`}},...B&&{"Content-Disposition":`attachment; filename="${m.basename(p)}"`}});if(await Se(s)){const n=await C(s);return t.newResponse(n,200,{"Content-Type":ee(O),"Access-Control-Allow-Origin":"*",...H,...l&&{"X-Robots-Tag":"noindex, follow",...e.config.seo?.siteUrl&&{Link:`<${V(e.config.seo.siteUrl,R(l.slug))}>; rel="canonical"`}},...B&&{"Content-Disposition":`attachment; filename="${m.basename(s)}"`}})}else return A(t,e,{slug:a},404)}}export{mt as dynamicRouteHandler};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{removeTrailingSlash as
|
|
1
|
+
import{removeTrailingSlash as i}from"../../../../utils/url/remove-trailing-slash.js";import{isLocalLink as e}from"../../../../utils/path/is-local-link.js";import{withPathPrefix as r}from"@redocly/theme/core/utils";function m({redirect:o,reqUrlSearch:t=""}){const n=e(o.to)?r(o.to):o.to;return{location:a(i(n))+t,type:o?.type||301}}function a(o){return encodeURI(o).replace(/%25([0-9A-Fa-f]{2})/g,"%$1")}export{m as processRedirects};
|
|
@@ -15,10 +15,10 @@ export type ConsentPageProps = {
|
|
|
15
15
|
clientIdHost: string | undefined;
|
|
16
16
|
redirectUrl: URL;
|
|
17
17
|
scopes: readonly string[];
|
|
18
|
-
|
|
18
|
+
accessLifetimeDays: number;
|
|
19
19
|
rememberDays: number | undefined;
|
|
20
20
|
consentToken: string;
|
|
21
21
|
};
|
|
22
|
-
export declare function consentPage({ site, user, clientName, clientIdHost, redirectUrl, scopes,
|
|
22
|
+
export declare function consentPage({ site, user, clientName, clientIdHost, redirectUrl, scopes, accessLifetimeDays, rememberDays, consentToken, }: ConsentPageProps): string;
|
|
23
23
|
export declare function consentInvalidPage(site: PageSite): string;
|
|
24
24
|
//# sourceMappingURL=mcp-consent-page.d.ts.map
|
|
@@ -1,35 +1,35 @@
|
|
|
1
|
-
import{ICONS as d,code as E,escapeHtml as a,htmlDocument as p,siteHeader as N}from"../../../plugins/mcp/handlers/credentials-page/layout.js";import{statusPage as L}from"../../../plugins/mcp/handlers/credentials-page/outcome-pages.js";const $=300,
|
|
2
|
-
<h2 id="${
|
|
1
|
+
import{ICONS as d,code as E,escapeHtml as a,htmlDocument as p,siteHeader as N}from"../../../plugins/mcp/handlers/credentials-page/layout.js";import{statusPage as L}from"../../../plugins/mcp/handlers/credentials-page/outcome-pages.js";const $=300,s={TITLE:"Allow MCP access",INTRO:"An MCP client asks to use this portal with your account.",WARNING:"Allow access only if you started this connection in your MCP client.",REDIRECT_LABEL:"Sends access to",REDIRECT_HINT:"The app receives access at this address.",USER_LABEL:"Signed in as",NOT_PROVIDED:"Not provided",CLIENT_LABEL:"App",CLIENT_UNKNOWN:"The app did not send a name. Continue only if you just started a connection yourself.",CLIENT_NAME_HINT:"The app chose this name itself. We do not check it.",CLIENT_ID_HOST:e=>`App details loaded from ${E(e)}`,PANEL_TITLE:"What the client gets",ACCOUNT_DETAILS:"Your account details, including your name and email address",ACT_AS_YOU:"Use of the MCP server of this portal as you",ACCESS_LIFETIME:e=>`Access that it can renew for up to ${e===1?"1 day":`${e} days`}`,REMEMBER:e=>`If you allow access, we do not ask again for this client for ${e} days.`,SCOPES_LABEL:"Scopes:",ALLOW:"Allow access",DENY:"Deny",INVALID_TITLE:"This request is no longer valid",INVALID_BODY:e=>`An access request works for ${e} minutes. This one has expired or can no longer be used.`,INVALID_NEXT:"Go back to your MCP client and start the connection again."},h={"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store","X-Frame-Options":"DENY","Referrer-Policy":"no-referrer","Content-Security-Policy":"default-src 'none'; style-src 'unsafe-inline'; img-src 'self'; frame-ancestors 'none'; base-uri 'none'"};function _({protocol:e,host:n,pathname:t,search:o}){return`${e}${n?`//${n}`:""}${t}${o}`}function r(e,n,t){return`<section aria-labelledby="${e}">
|
|
2
|
+
<h2 id="${e}">${a(n)}</h2>
|
|
3
3
|
${t.filter(Boolean).join(`
|
|
4
4
|
`)}
|
|
5
|
-
</section>`}function m(
|
|
6
|
-
<li>${
|
|
7
|
-
<li>${
|
|
8
|
-
<li>${
|
|
9
|
-
</ol>`,c=t?`<p>${
|
|
5
|
+
</section>`}function m(e,n){return r("consent-client",s.CLIENT_LABEL,[e?`<p>${a(e)}</p><p class="muted small">${s.CLIENT_NAME_HINT}</p>`:`<p>${s.CLIENT_UNKNOWN}</p>`,n?`<p class="muted small">${s.CLIENT_ID_HOST(n)}</p>`:""])}function A({scopes:e,accessLifetimeDays:n,rememberDays:t}){const o=`${d.shield}${s.PANEL_TITLE}`,i=`<ol class="steps">
|
|
6
|
+
<li>${s.ACCOUNT_DETAILS}</li>
|
|
7
|
+
<li>${s.ACT_AS_YOU}</li>
|
|
8
|
+
<li>${s.ACCESS_LIFETIME(n)}</li>
|
|
9
|
+
</ol>`,c=t?`<p>${s.REMEMBER(t)}</p>`:"";return`<aside class="panel" aria-labelledby="panel-title">
|
|
10
10
|
<div class="panel-steps"><h2 id="panel-title">${o}</h2>${i}</div>
|
|
11
11
|
<details class="panel-steps-toggle"><summary><h2>${o}</h2></summary>${i}</details>
|
|
12
12
|
<div class="link-facts">
|
|
13
13
|
${c}
|
|
14
|
-
<div class="tags"><span>${
|
|
14
|
+
<div class="tags"><span>${s.SCOPES_LABEL}</span>${e.map(l=>`<span class="tag">${a(l)}</span>`).join("")}</div>
|
|
15
15
|
</div>
|
|
16
|
-
</aside>`}function S({site:
|
|
16
|
+
</aside>`}function S({site:e,user:n,clientName:t,clientIdHost:o,redirectUrl:i,scopes:c,accessLifetimeDays:l,rememberDays:T,consentToken:u}){const I=`<div class="page">
|
|
17
17
|
<main class="card">
|
|
18
|
-
${N(
|
|
19
|
-
<h1>${
|
|
20
|
-
<p class="lede">${
|
|
21
|
-
<div class="banner warning" role="note">${d.warning}<p>${
|
|
18
|
+
${N(e)}
|
|
19
|
+
<h1>${s.TITLE}</h1>
|
|
20
|
+
<p class="lede">${s.INTRO}</p>
|
|
21
|
+
<div class="banner warning" role="note">${d.warning}<p>${s.WARNING}</p></div>
|
|
22
22
|
<div class="info-card">
|
|
23
23
|
${m(t,o)}
|
|
24
|
-
${r("consent-user",
|
|
25
|
-
${r("consent-redirect",
|
|
24
|
+
${r("consent-user",s.USER_LABEL,[`<p>${a(n||s.NOT_PROVIDED)}</p>`])}
|
|
25
|
+
${r("consent-redirect",s.REDIRECT_LABEL,[`<p>${E(_(i))}</p>`,`<p class="muted small">${s.REDIRECT_HINT}</p>`])}
|
|
26
26
|
</div>
|
|
27
27
|
<form class="credentials" method="post" autocomplete="off">
|
|
28
28
|
<input type="hidden" name="consent" value="${a(u)}">
|
|
29
29
|
<div class="actions">
|
|
30
|
-
<div class="actions-row"><button class="secondary" type="submit" name="decision" value="deny">${
|
|
30
|
+
<div class="actions-row"><button class="secondary" type="submit" name="decision" value="deny">${s.DENY}</button><button class="primary" type="submit" name="decision" value="allow">${s.ALLOW}</button></div>
|
|
31
31
|
</div>
|
|
32
32
|
</form>
|
|
33
33
|
</main>
|
|
34
|
-
${A({scopes:c,
|
|
35
|
-
</div>`;return p({title:
|
|
34
|
+
${A({scopes:c,accessLifetimeDays:l,rememberDays:T})}
|
|
35
|
+
</div>`;return p({title:s.TITLE,body:I},e.colorScheme)}function y(e){return p(L("warning",s.INVALID_TITLE,[s.INVALID_BODY($/60),s.INVALID_NEXT]),e.colorScheme)}export{h as CONSENT_PAGE_HEADERS,$ as MCP_CONSENT_TTL_SEC,y as consentInvalidPage,S as consentPage};
|