@redocly/realm 0.130.0-next.8 → 0.130.0
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 +148 -0
- package/dist/bin.js +1 -1
- package/dist/cli/develop.js +1 -1
- package/dist/cli/stats/collectors/openapi.js +1 -1
- package/dist/client/ErrorBoundary.js +1 -1
- package/dist/client/app/Sidebar/RequestAccessButton.js +2 -2
- package/dist/client/app/Sidebar/Sidebar.js +2 -2
- package/dist/client/app/hooks/catalog/useCatalogClassic.js +1 -1
- package/dist/client/app/hooks/catalog/useCatalogFilter.js +1 -1
- package/dist/client/app/hooks/catalog/useCatalogViewMode.js +1 -1
- package/dist/client/app/hooks/catalog/useSearchTracker.js +1 -1
- package/dist/client/app/hooks/usePageTimeTracker.js +1 -1
- package/dist/client/app/hooks/useRouteChangeTracker.js +1 -1
- package/dist/client/app/pages/DevLogin/DevLogin.js +1 -1
- package/dist/client/app/search/message-handlers.d.ts +29 -0
- package/dist/client/app/search/message-handlers.js +1 -0
- package/dist/client/app/search/sse-parser.d.ts +10 -0
- package/dist/client/app/search/sse-parser.js +2 -0
- package/dist/client/app/search/useAiSearch.d.ts +9 -11
- package/dist/client/app/search/useAiSearch.js +1 -1
- package/dist/client/app/search/useSearch.js +1 -1
- package/dist/client/constants/ai-search.d.ts +30 -0
- package/dist/client/constants/ai-search.js +1 -0
- package/dist/client/constants/index.d.ts +2 -0
- package/dist/client/constants/index.js +1 -0
- package/dist/client/types/ai-search.d.ts +73 -0
- package/dist/client/types/ai-search.js +0 -0
- package/dist/client/types/index.d.ts +1 -0
- package/dist/constants/l10n/langs/ar.js +1 -1
- package/dist/constants/l10n/langs/de.js +1 -1
- package/dist/constants/l10n/langs/en.js +1 -1
- package/dist/constants/l10n/langs/es.js +1 -1
- package/dist/constants/l10n/langs/fr.js +1 -1
- package/dist/constants/l10n/langs/hi.js +1 -1
- package/dist/constants/l10n/langs/it.js +1 -1
- package/dist/constants/l10n/langs/ja.js +1 -1
- package/dist/constants/l10n/langs/ko.js +1 -1
- package/dist/constants/l10n/langs/pl.js +1 -1
- package/dist/constants/l10n/langs/pt-BR.js +1 -1
- package/dist/constants/l10n/langs/pt.js +1 -1
- package/dist/constants/l10n/langs/ru.js +1 -1
- package/dist/constants/l10n/langs/uk.js +1 -1
- package/dist/constants/l10n/langs/zh.js +1 -1
- package/dist/server/api-routes/run-api-routes-worker.js +1 -1
- package/dist/server/constants/common.js +1 -1
- package/dist/server/entitlements/entitlements-provider.js +1 -1
- package/dist/server/persistence/kv/services/kv-service.js +1 -1
- package/dist/server/plugins/asyncapi-docs/template/AsyncApiDocs.js +5 -3
- package/dist/server/plugins/catalog-entities/database/catalog-entities-service.d.ts +32 -9
- package/dist/server/plugins/catalog-entities/database/catalog-entities-service.js +1 -1
- package/dist/server/plugins/catalog-entities/database/repositories/local/catalog-entities-bff-repository.d.ts +16 -5
- package/dist/server/plugins/catalog-entities/database/repositories/local/catalog-entities-bff-repository.js +21 -17
- package/dist/server/plugins/catalog-entities/database/repositories/local/catalog-entities-local-read-repository.d.ts +35 -9
- package/dist/server/plugins/catalog-entities/database/repositories/local/catalog-entities-local-read-repository.js +24 -21
- package/dist/server/plugins/catalog-entities/database/repositories/local/catalog-entities-local-repository.d.ts +31 -8
- package/dist/server/plugins/catalog-entities/database/repositories/local/catalog-entities-local-repository.js +1 -1
- package/dist/server/plugins/catalog-entities/database/repositories/local/catalog-entities-local-write-repository.js +1 -1
- package/dist/server/plugins/catalog-entities/database/repositories/local/catalog-entities-relations-repository.d.ts +7 -1
- package/dist/server/plugins/catalog-entities/database/repositories/local/catalog-entities-relations-repository.js +1 -1
- package/dist/server/plugins/catalog-entities/database/repositories/remote/catalog-entities-remote-repository.d.ts +1 -1
- package/dist/server/plugins/catalog-entities/database/repositories/remote/catalog-entities-remote-repository.js +1 -1
- package/dist/server/plugins/catalog-entities/database/repositories/utils/build-entities-exclusion-filter.d.ts +13 -0
- package/dist/server/plugins/catalog-entities/database/repositories/utils/build-entities-exclusion-filter.js +1 -0
- package/dist/server/plugins/catalog-entities/database/repositories/utils/build-rbac-filter.d.ts +31 -0
- package/dist/server/plugins/catalog-entities/database/repositories/utils/build-rbac-filter.js +9 -0
- package/dist/server/plugins/catalog-entities/extensions/extractors/api-description/base.js +1 -1
- package/dist/server/plugins/catalog-entities/extensions/extractors/api-description/openapi-entities-extractor.js +1 -1
- package/dist/server/plugins/catalog-entities/extensions/extractors/fs-entities-extractor.js +1 -1
- package/dist/server/plugins/catalog-entities/get-server-props.js +1 -1
- package/dist/server/plugins/catalog-entities/types/openapi.d.ts +11 -0
- package/dist/server/plugins/catalog-entities/types/openapi.js +0 -0
- package/dist/server/plugins/catalog-entities/types/params.d.ts +6 -0
- package/dist/server/plugins/catalog-entities/types/params.js +0 -0
- package/dist/server/plugins/catalog-entities/utils/catalog-data-collector.js +1 -1
- package/dist/server/plugins/catalog-entities/utils/get-not-accessible-catalog-resources.d.ts +11 -0
- package/dist/server/plugins/catalog-entities/utils/get-not-accessible-catalog-resources.js +1 -0
- package/dist/server/plugins/config-parser/index.js +1 -1
- package/dist/server/plugins/markdown/markdown-static-data-loader.js +1 -1
- package/dist/server/plugins/mcp/docs-mcp/tools/docs-mcp-tool.js +1 -1
- package/dist/server/plugins/mcp/docs-mcp/tools/get-endpoint-info.js +1 -1
- package/dist/server/plugins/mcp/docs-mcp/tools/get-endpoints.js +1 -1
- package/dist/server/plugins/mcp/docs-mcp/tools/get-full-api-description.js +1 -1
- package/dist/server/plugins/mcp/docs-mcp/tools/get-security-schemes.js +1 -1
- package/dist/server/plugins/mcp/handlers/docs-mcp-handler.js +1 -1
- package/dist/server/plugins/mcp/handlers/errors.js +1 -1
- package/dist/server/plugins/mcp/servers/base-server.js +1 -1
- package/dist/server/plugins/openapi-docs/template/OpenAPIDocs.js +8 -4
- package/dist/server/plugins/openapi-docs/template/helpers.d.ts +1 -1
- package/dist/server/plugins/openapi-docs/template/helpers.js +3 -3
- package/dist/server/plugins/scorecard-classic/types.d.ts +3 -3
- package/dist/server/plugins/scorecard-classic/types.js +1 -1
- package/dist/server/plugins/search/llmstxt/index.js +4 -4
- package/dist/server/plugins/sso/index.js +1 -1
- package/dist/server/store.js +1 -1
- package/dist/server/tools/notifiers/logger.js +1 -1
- package/dist/server/tools/notifiers/reporter.js +7 -7
- package/dist/server/utils/rbac.d.ts +65 -0
- package/dist/server/web-server/auth.js +3 -3
- package/dist/server/web-server/middleware/catalogAuthMiddleware.d.ts +4 -6
- package/dist/server/web-server/middleware/catalogAuthMiddleware.js +1 -1
- package/dist/server/web-server/routes/ask-ai.js +1 -1
- package/dist/server/web-server/routes/auth.js +1 -1
- package/dist/server/web-server/routes/catalog/bff-catalog-related-entities.js +1 -1
- package/dist/server/web-server/routes/catalog/bff-catalog.js +1 -1
- package/dist/server/web-server/routes/catalog/catalog.js +1 -1
- package/dist/server/web-server/routes/catalog/helpers/has-access-to-entity.d.ts +10 -0
- package/dist/server/web-server/routes/catalog/helpers/has-access-to-entity.js +1 -0
- package/dist/server/web-server/routes/dynamic-route.js +1 -1
- package/dist/server/web-server/routes/helpers/get-current-rbac-teams.d.ts +3 -0
- package/dist/server/web-server/routes/helpers/get-current-rbac-teams.js +1 -0
- package/dist/server/web-server/routes/helpers/get-rbac-restrictions-data-for-catalog.d.ts +11 -0
- package/dist/server/web-server/routes/helpers/get-rbac-restrictions-data-for-catalog.js +1 -0
- package/dist/server/web-server/routes/index.js +1 -1
- package/dist/server/web-server/routes/mcp-oauth.js +1 -1
- package/dist/server/web-server/routes/page-data.js +1 -1
- package/dist/server/web-server/utils.d.ts +2 -2
- package/package.json +16 -16
|
@@ -65,6 +65,71 @@ export declare const normalizeRbacConfig: (rbacConfig: RbacConfig) => {
|
|
|
65
65
|
reunite?: {
|
|
66
66
|
[x: string]: string;
|
|
67
67
|
} | undefined;
|
|
68
|
+
entitiesCatalog?: {
|
|
69
|
+
catalogs?: {
|
|
70
|
+
[x: string]: unknown;
|
|
71
|
+
all?: {
|
|
72
|
+
[x: string]: string;
|
|
73
|
+
} | undefined;
|
|
74
|
+
services?: {
|
|
75
|
+
[x: string]: string;
|
|
76
|
+
} | undefined;
|
|
77
|
+
domains?: {
|
|
78
|
+
[x: string]: string;
|
|
79
|
+
} | undefined;
|
|
80
|
+
teams?: {
|
|
81
|
+
[x: string]: string;
|
|
82
|
+
} | undefined;
|
|
83
|
+
users?: {
|
|
84
|
+
[x: string]: string;
|
|
85
|
+
} | undefined;
|
|
86
|
+
apiDescriptions?: {
|
|
87
|
+
[x: string]: string;
|
|
88
|
+
} | undefined;
|
|
89
|
+
dataSchemas?: {
|
|
90
|
+
[x: string]: string;
|
|
91
|
+
} | undefined;
|
|
92
|
+
apiOperations?: {
|
|
93
|
+
[x: string]: string;
|
|
94
|
+
} | undefined;
|
|
95
|
+
} | undefined;
|
|
96
|
+
entities?: {
|
|
97
|
+
[x: string]: unknown;
|
|
98
|
+
"**"?: {
|
|
99
|
+
[x: string]: string;
|
|
100
|
+
} | undefined;
|
|
101
|
+
} | undefined;
|
|
102
|
+
entitiesTypes?: {
|
|
103
|
+
[x: string]: unknown;
|
|
104
|
+
user?: {
|
|
105
|
+
[x: string]: string;
|
|
106
|
+
} | undefined;
|
|
107
|
+
service?: {
|
|
108
|
+
[x: string]: string;
|
|
109
|
+
} | undefined;
|
|
110
|
+
domain?: {
|
|
111
|
+
[x: string]: string;
|
|
112
|
+
} | undefined;
|
|
113
|
+
team?: {
|
|
114
|
+
[x: string]: string;
|
|
115
|
+
} | undefined;
|
|
116
|
+
apiDescription?: {
|
|
117
|
+
[x: string]: string;
|
|
118
|
+
} | undefined;
|
|
119
|
+
apiOperation?: {
|
|
120
|
+
[x: string]: string;
|
|
121
|
+
} | undefined;
|
|
122
|
+
dataSchema?: {
|
|
123
|
+
[x: string]: string;
|
|
124
|
+
} | undefined;
|
|
125
|
+
} | undefined;
|
|
126
|
+
entitiesGroups?: {
|
|
127
|
+
entities?: string[] | undefined;
|
|
128
|
+
config?: {
|
|
129
|
+
[x: string]: string;
|
|
130
|
+
} | undefined;
|
|
131
|
+
}[] | undefined;
|
|
132
|
+
} | undefined;
|
|
68
133
|
content?: {
|
|
69
134
|
[x: string]: unknown;
|
|
70
135
|
"**"?: {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import"../node-crypto-polyfill.js";import{DOMParser as
|
|
1
|
+
import"../node-crypto-polyfill.js";import{DOMParser as D}from"@xmldom/xmldom";import{SignedXml as B}from"xml-crypto";import F from"xpath";import{deflateSync as H,inflateSync as J}from"fflate";import{createHash as q}from"crypto";import{ulid as W}from"ulid";import{AuthProviderType as u,DEFAULT_TEAM_CLAIM_NAME as K}from"@redocly/config";import{AUTH_URL as Q,JWT_SECRET_KEY as I}from"../constants/common.js";import{getPathPrefix as X,withPathPrefix as Y}from"@redocly/theme/core/utils";import{DEFAULT_AUTHENTICATED_TEAM as G,REQUIRED_OIDC_SCOPES as N,ServerRoutes as P}from"../../constants/common.js";import{appendQueryParams as Z}from"../../utils/url/append-query-params.js";import{logger as ee}from"../tools/notifiers/logger.js";import{randomString as te}from"../utils/crypto/random-string.js";import{randomUUID as k}from"../utils/crypto/random-uuid.js";import{AlgorithmTypes as y,JwtTokenExpired as ne}from"./jwt/types.js";import*as p from"./jwt/jwt.js";import{parseTeamClaimToArray as re}from"../utils/index.js";import{arrayBufferToBase64 as ae,decodeBase64 as R,encodeBase64URL as oe,urlSafeBase64 as v}from"./jwt/encode.js";import{formatSamlCertificate as se}from"./utils/format-saml-certificate.js";function j(e){return e?.type===u.OIDC}function ie(e){return e?.type===u.SAML2}async function ze(e,t){if(j(t))return ce(e,t);if(ie(t))return ue(e,t)}async function ce(e,t){const r=await V(e,t),n=new Set((t.scopes||[]).concat(N)),a=t.authorizationRequestCustomParams||{};return{type:u.OIDC,idpId:e,name:"OAuth provider",authorizationEndpoint:r.authorization_endpoint,clientId:t.clientId,responseType:"code",scope:Array.from(n).join(" "),extraParams:a,pkce:t.pkce}}function ue(e,t){return{type:u.SAML2,idpId:e,name:"SAML2 provider",ssoUrl:t.ssoUrl,issuerId:t.issuerId,entityId:t.entityId||t.issuerId}}async function Be(e,t,r,n,a={}){const o=new Set((n.scopes||[]).concat(N));return await fetch(e,{method:"POST",body:new URLSearchParams({client_id:n.clientId,scope:Array.from(o).join(" "),code:t,redirect_uri:E(r),grant_type:"authorization_code",...n.clientSecret?{client_secret:n.clientSecret}:{},...a}).toString(),headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}}).then(s=>s.json())}function de(e,{authorizationEndpoint:t,clientId:r,responseType:n,scope:a,extraParams:o,idpId:s,pkce:l},m,A,S){if(!t||!r||!n||!a)return{loginUrl:void 0};const c=new URL(t),f=S?.redirectUriOverride??`${e}${Y(P.OIDC_CALLBACK)}`,x={state:k(),idpId:s,redirectUri:f,redirectTo:m,branch:S?.branchOverride??me(e),inviteCode:A,source:S?.sourceOverride??"portal"},h={};if(l){const d=v(te(50)),_=v(q("sha256").update(d).digest("base64")),g="S256";c.searchParams.append("code_challenge",_),c.searchParams.append("code_challenge_method",g),h.code_verifier={value:d,options:{secure:!0,httpOnly:!0,expires:new Date(Date.now()+1e3*60*10),path:X()||"/"}}}c.searchParams.append("client_id",r),c.searchParams.append("scope",a),c.searchParams.append("response_type",n),c.searchParams.append("redirect_uri",E(f)),c.searchParams.append("state",oe(JSON.stringify(x)));for(const d in o)o[d]!==void 0&&c.searchParams.append(d,o[d]);return{loginUrl:c.toString(),cookies:h}}function Fe(e,t,r,n){const a=new URL(e);return a.searchParams.append("post_logout_redirect_uri",t),n&&a.searchParams.append("state",n),a.searchParams.append("id_token_hint",r),a.toString()}async function He(e){const t=Math.floor(Date.now()/1e3),r=t+(e.ttlSec??600);return p.sign({type:"mcp_auth_code",client_id:e.clientId,redirect_uri:e.redirectUri,id_token:e.idToken,iat:t,exp:r},I,y.HS256)}async function Je(e){await p.verify(e,I,y.HS256);const{payload:t}=p.decode(e);if(t.type!=="mcp_auth_code")throw new Error("Invalid authorization code type");if(!t.client_id||!t.redirect_uri)throw new Error("Authorization code missing required claims");if(typeof t.exp=="number"&&Date.now()>=t.exp*1e3)throw new Error("Authorization code expired");return t}function qe(e){const t=e||W(),r=t.startsWith("mcp_")?t:`mcp_${t}`;return{id:r,object:"mcp_session",uri:`urn:redocly:realm:mcp:session:${r}`}}function E(e){return e.match(/^https:\/\/preview-[^\.]+--/)?"https://previewauth--"+e.split("--")[1]:e.match(/^(https:\/\/[^\.]+)--[^\.]+\.preview\./)?e.replace(/^(https:\/\/[^\.]+?)--[^\.]+\.preview\./,"$1.previewauth."):e}function me(e){return e.match(/^(https:\/\/[^\.]+)--([^\.]+)\.preview\./)?.[2]||void 0}function le(e){return e.type===u.OIDC}function pe(e){return e.type===u.SAML2}function We(e,t,r,n){return le(e)?de(t,e,r,n):pe(e)?fe(t,e,r,n):{}}function fe(e,t,r,n){const o=`<samlp:AuthnRequest xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
|
|
2
2
|
xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
|
|
3
3
|
Version="2.0"
|
|
4
|
-
ID="_${
|
|
4
|
+
ID="_${k()}"
|
|
5
5
|
IssueInstant="${new Date().toISOString()}"
|
|
6
6
|
AssertionConsumerServiceURL="${e}${P.SAML_CALLBACK}"
|
|
7
7
|
AttributeConsumingServiceIndex="0">
|
|
@@ -9,4 +9,4 @@ import"../node-crypto-polyfill.js";import{DOMParser as U}from"@xmldom/xmldom";im
|
|
|
9
9
|
<samlp:NameIDPolicy
|
|
10
10
|
AllowCreate="true"
|
|
11
11
|
Format="urn:oasis:names:tc:SAML:2.0:nameid-format:persistent"/>
|
|
12
|
-
</samlp:AuthnRequest>`,s=he(o);return{loginUrl:Z(t.ssoUrl,{SAMLRequest:s,RelayState:JSON.stringify({idpId:t.idpId,redirectTo:
|
|
12
|
+
</samlp:AuthnRequest>`,s=he(o);return{loginUrl:Z(t.ssoUrl,{SAMLRequest:s,RelayState:JSON.stringify({idpId:t.idpId,redirectTo:r,inviteCode:n,source:"portal"})})}}function he(e){return ae(H(new TextEncoder().encode(e)).buffer)}function Ke(e){const t=R(e);if(t.startsWith("<samlp:Response")||t.indexOf("<saml2p:Response")>-1)return t;const r=J(new Uint8Array(atob(e).split("").map(n=>n.charCodeAt(0))));return new TextDecoder().decode(r)}function Qe(e){try{return JSON.parse(R(e||""))}catch{throw new Error("Invalid OAuth2 state")}}function Xe(e){const t=new D().parseFromString(e,"application/xml"),n=i(t,"//*[local-name(.)='StatusCode']/@Value")[0]?.nodeValue?.endsWith("Success")||!1,o=i(t,"//*[local-name(.)='Response']/@Destination")[0]?.nodeValue||"",s=i(t,"//*[local-name(.)='Assertion']//*[local-name(.)='Issuer']/text()")[0],l=s&&s.nodeValue||void 0,m=i(t,"//*[local-name(.)='Audience']/text()")[0],A=m&&m.nodeValue||void 0,c=i(t,"//*[local-name(.)='Assertion']//*[local-name(.)='X509Certificate']/text()")[0]?.nodeValue||"",f=i(t,"//*[local-name(.)='Subject']//*[local-name(.)='NameID']/text()")[0],x=f&&f.nodeValue||"",h=i(t,"//*[local-name(.)='Subject']//*[local-name(.)='NameID']/@Format")[0],d=h&&h.nodeValue||"",_=i(t,"//*[local-name(.)='Conditions']/@NotOnOrAfter")[0],g=ye(_),T={},C=i(t,"//*[local-name(.)='AttributeStatement']//*[local-name(.)='Attribute']");if(C.length)for(const O of C){const U=i(O,"./@Name")[0];if(U.nodeValue){const b=i(O,"./*[local-name(.)='AttributeValue']/text()")[0];b?.nodeValue&&(T[U.nodeValue]=b.nodeValue)}}return{uid:x,success:n,expiresAt:g,issuerId:l,entityId:A,attrs:T,cert:c,nameFormat:d,destination:o}}function ye(e){const t=typeof e?.nodeValue=="string"&&L(Date.parse(e.nodeValue)),r=L(Date.now()),n=L(Date.now()+720*60*1e3);return t?t>r&&t<n?n:t:r}function L(e){return Math.floor(e/1e3)}const M={},w={jwks:{}};async function V(e,t){return M[e]||(M[e]=t.configurationUrl?await $(t.configurationUrl):t.configuration),M[e]}async function we(e){for(const t of Object.keys(e)){const r=e[t];if(!j(r))continue;const n=await V(t,r);if(n.jwks_uri){const a=await $(n.jwks_uri);for(const o of a.keys)w.jwks[o.kid]={...o,idpId:t}}}}async function $(e){return fetch(e,{headers:{Accept:"application/json"}}).then(t=>t.json())}async function Ye(e){return fetch(`${Q}/oidc/userinfo`,{headers:{Accept:"application/json",Authorization:`Bearer ${e}`}}).then(t=>t.status===200?t.json():void 0).catch(()=>{})}function Ge(e){if(!e.configurationUrl)return!1;const t=new URL(e.configurationUrl);return["localhost","127.0.0.1","blueharvest.cloud","bhstage.cloud","cloud.redocly.com","beta.redocly.com","cloud.eu.redocly.com","beta.eu.redocly.com","cba.au.redocly.com"].some(n=>Se(t.hostname,n))}function Se(e,t){return e===t||e.endsWith(`.${t}`)}async function Ze(e,t){const r=new D().parseFromString(e),n=i(r,"//*[local-name(.)='Signature' and namespace-uri(.)='http://www.w3.org/2000/09/xmldsig#']")[0];if(!n)throw new Error("Cannot find Signature in the SAML response");const a=se(t),o=new B({publicCert:a});o.loadSignature(n);try{return o.checkSignature(e)}catch{return!1}}function et(e,t,r,n){t==="urn:oasis:names:tc:SAML:2.0:nameid-format:transient"&&(e=r["http://schemas.microsoft.com/identity/claims/objectidentifier"]);let a;(t==="urn:oasis:names:tc:SAML:2.0:nameid-format:email"||t==="urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress")&&(a=e),t==="urn:oasis:names:tc:SAML:2.0:nameid-format:persistent"&&e?.match(/.+@.+/)&&(a=e);const o=r["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name"],s=o?.match(/.+@.+/);return a=a||r["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress"]||(s?o:void 0),a=a?.toLowerCase(),{sub:e,given_name:r["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname"],family_name:r["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname"],name:r["http://schemas.microsoft.com/identity/claims/displayname"]||o,email:a,email_verified:!0,teams:n?re(r[n]):[]}}function z(e,t={}){return e.map(r=>t[r]||r)}async function tt(e,t){if(!t)return{};const r=t.authorization;if(!r)return{};try{const n=p.decode(r);if(n.header.alg===y.RS256){w.jwks[n.header.kid]===void 0&&await we(e);const m=w.jwks[n.header.kid];if(!m)return w.jwks[n.header.kid]=null,{};await p.verify(r,m,y.RS256)}else await p.verify(r,I,y.HS256);const a=n.payload.idpId||w.jwks[n.header.kid]?.idpId,o=e[a]||{},s=_e(o),l=xe(o);return{...n.payload,email:n.payload.email?.toLowerCase(),idpId:a,teams:Array.from(new Set([...z(n.payload.teams||[],l),..."defaultTeams"in o&&o.defaultTeams||[],...z("teamsClaimName"in o&&n.payload[s||""]||[],l),G])),name:Ae(n.payload),isAuthenticated:!0,idpAccessToken:t.idp_access_token,federatedAccessToken:t.federated_access_token,federatedIdToken:t.federated_id_token,authCookie:r}}catch(n){n instanceof ne||ee.error("Malformed JWT token: %s",n.message)}return{}}function Ae(e){return(e.firstName&&e.lastName?`${e.firstName} ${e.lastName}`:e.name||e.given_name||e.firstName||e.lastName)||e.email}function xe(e){switch(e.type){case u.SAML2:return e.teamsAttributeMap;case u.OIDC:return e.teamsClaimMap;default:return}}function _e(e){switch(e.type){case u.SAML2:return e.teamsAttributeName;case u.OIDC:return e.teamsClaimName;default:return K}}function i(e,t){return F.select(t,e)||[]}export{We as buildLoginUrl,de as buildOidcLoginUrl,Fe as buildOidcLogoutUrl,fe as buildSAML2LoginUrl,He as createMcpAuthorizationCode,qe as createMcpSessionResource,Ke as decodeSamlResponse,he as encodeSAML2,et as extractUserClaims,ze as getAuthProviderLoginParams,ce as getOidcLoginParams,V as getOidcMetadata,Ye as getRedoclyTokenPayload,ue as getSaml2LoginParams,tt as getUserParamsFromCookies,Ae as getUsernameFromPayload,j as isOidcProviderConfig,Ge as isRedoclySso,ie as isSaml2ProviderConfig,Be as oidcExchangeCodeForToken,Qe as parseOidcState,me as parsePreviewBranch,Xe as parseSamlResponse,E as rewritePreviewAuthRedirectUri,Je as verifyMcpAuthorizationCode,Ze as verifySAMLResponse};
|
|
@@ -1,8 +1,6 @@
|
|
|
1
1
|
import type { Context, Next } from 'hono';
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
}
|
|
6
|
-
export declare function catalogAuthMiddleware(serverOutDir: string, options?: CatalogAuthMiddlewareOptions): (ctx: Context, next: Next) => Promise<Response | void>;
|
|
7
|
-
export {};
|
|
2
|
+
export declare function catalogAuthMiddleware({ serverOutDir, protectReadMethods, }: {
|
|
3
|
+
serverOutDir: string;
|
|
4
|
+
protectReadMethods?: boolean;
|
|
5
|
+
}): (ctx: Context, next: Next) => Promise<Response | void>;
|
|
8
6
|
//# sourceMappingURL=catalogAuthMiddleware.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{KvService as
|
|
1
|
+
import{KvService as p}from"../../persistence/kv/services/kv-service.js";import{DEFAULT_AUTHENTICATED_TEAM as A}from"../../../constants/common.js";import{JWT_SECRET_KEY as l}from"../../constants/common.js";import*as d from"../jwt/jwt.js";import{AlgorithmTypes as y}from"../jwt/types.js";const I=60,T=e=>["POST","PUT","DELETE","PATCH"].includes(e),h=e=>["GET"].includes(e);function D({serverOutDir:e,protectReadMethods:t=!0}){return async(r,a)=>await f(r,a,e,t)}const f=async(e,t,r,a=!0)=>{const s=e.req.method,n=T(s)||h(s)&&a,o=e.req.header("apiKey");if(o)return await v(e,t,o,r);const c=e.req.header("authorization")?.replace("Bearer ","");return c?await w(e,t,c):n?e.json({message:"API key is required"},401):await t()},v=async(e,t,r,a)=>{if(!process.env.BH_API_URL||!process.env.ORGANIZATION_ID)return e.json({message:"API key validation service not configured"},500);try{const s=await p.getInstance({baseDbDir:a});let n=await E(s,r);if(n)return e.set("apiKeyTeams",n.teams),await t();const o=new URL(`/api/orgs/${process.env.ORGANIZATION_ID}/session`,process.env.BH_API_URL).toString(),i=await fetch(o,{method:"GET",headers:{Authorization:`Bearer ${r}`}});if(!i.ok)return e.json({message:"Invalid API key"},401);const m=(await i.json())?.user?.teams?.[process.env.ORGANIZATION_ID]??[],u=[A,...m];return e.set("apiKeyTeams",u),await s.set(["api-keys","reunite",r],{valid:!0,teams:u},{ttlInSeconds:I}),await t()}catch{return e.json({message:"API key validation failed"},400)}},w=async(e,t,r)=>{try{const a=await d.verify(r,l,y.HS256),s=d.decode(r).payload.isInternalConnection;return!a||!s?e.json({message:"API key is required"},401):await t()}catch{return e.json({message:"API key validation failed"},400)}},E=async(e,t)=>{try{return await e.get(["api-keys","reunite",t])}catch{return null}};export{D as catalogAuthMiddleware};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{RbacFeatures as
|
|
1
|
+
import{RbacFeatures as p}from"../../../constants/common.js";import{ASK_AI_API_URL as r}from"../../constants/common.js";import{canAccessFeature as u}from"../../utils/rbac.js";import{handleUnauthorizedApiRequest as f}from"../utils.js";import{isAiSearchEnabled as h}from"../../plugins/search/utils.js";function C(a){return async e=>{if(!r)return e.newResponse(null,404);const t=a.getConfig();if(!h(t))return e.newResponse(null,403,{});const o=e.get("auth");if(!u(p.AI_SEARCH,o,t.rbac,t.requiresLogin))return f(e);const i={"Content-Type":"application/json"},n=[];o.claims?.authCookie&&n.push(`authorization=${o.claims.authCookie}`),o.idpAccessToken&&n.push(`accessToken=${o.idpAccessToken}`),n.length>0&&(i.Cookie=n.join("; "));const c=await e.req.json(),s=await fetch(r,{method:"POST",body:JSON.stringify(c),headers:i});return s.ok?e.newResponse(s.body,200,{"Content-Type":"text/event-stream"}):e.newResponse(s.body,s.status,{"Content-Type":"application/json"})}}export{C as askAiHandler};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{setCookie as L,deleteCookie as T}from"hono/cookie";import{AuthProviderType as G}from"@redocly/config";import{withPathPrefix as R,getPathPrefix as _}from"@redocly/theme/core/utils";import{compareURIs as X}from"../../../utils/url/compare-uris.js";import{ensureArray as q}from"../../../utils/array/ensure-array.js";import{ALTERNATIVE_AUD_CLAIM_NAME as E,JWT_SECRET_KEY as v,ORG_SLUG as W}from"../../constants/common.js";import{DEFAULT_COOKIE_EXPIRATION as F,ServerRoutes as D}from"../../../constants/common.js";import{sanitizeRedirectPathname as B}from"../../../utils/url/sanitize-redirect-pathname.js";import{telemetry as k}from"../../telemetry/index.js";import{getAuthProviderLoginParams as Y,isOidcProviderConfig as $,isSaml2ProviderConfig as Q,oidcExchangeCodeForToken as Z,buildLoginUrl as x,decodeSamlResponse as ee,extractUserClaims as re,parseSamlResponse as oe,parseOidcState as ne,verifySAMLResponse as te,getUsernameFromPayload as ie,buildOidcLogoutUrl as se,getOidcMetadata as z,getRedoclyTokenPayload as ae,isRedoclySso as de,rewritePreviewAuthRedirectUri as ce,parsePreviewBranch as N,buildOidcLoginUrl as le,createMcpSessionResource as I}from"../auth.js";import*as S from"../jwt/jwt.js";import{AlgorithmTypes as ue}from"../jwt/types.js";import{handleErrorPageRender as pe}from"../utils.js";import{encodeBase64URL as ge}from"../jwt/encode.js";async function Oe(i){if(process.env.NODE_ENV==="production")return i.newResponse(null,404,{});const{password:e,...r}=await i.req.json(),a=await S.sign({...r,name:r.username||r.email||"Unknown"},v);return L(i,"authorization",a,{path:_()||"/",httpOnly:!0,secure:!0,sameSite:"none"}),i.newResponse(null,200,{})}function Pe(){return async i=>{const e=i.get("logger"),r=encodeURIComponent(i.req.query("message")||"");e.error(`Login error: ${r}`);const a=`${D.LOGIN}/?error=${encodeURIComponent(r)}`;return i.newResponse(null,301,{Location:a})}}function H(i){if(!i||!i.includes(D.MCP_CALLBACK))return null;try{const e=i.split("/"),r=e[e.length-1];if(r){const a=Buffer.from(r,"base64url").toString("utf-8");return JSON.parse(a).mcpSessionId||null}}catch{}return null}function Se(i){return async e=>{const r=e.get("logger"),a=i.getConfig().ssoDirect,n=ne(e.req.query("state")),f=n.idpId,t=n.source==="mcp"||n.redirectTo&&typeof n.redirectTo=="string"&&n.redirectTo.includes(D.MCP_CALLBACK),c=t?H(typeof n.redirectTo=="string"?n.redirectTo:void 0):null,s=a?.[f];if(!$(s))return r.error("OIDC login error: missing OIDC provider config"),e.text("Forbidden",403);const d=await z(f,s);if(a&&!d.token_endpoint){const p="Invalid OIDC configuration: token_endpoint is required";return r.error(`OIDC login error: ${p}`),e.text(p,500)}try{const p=d.token_endpoint,l=e.req.query("code"),m=e.req.query("error");if(m)return t&&k.sendMcpAuthorizationFailedMessage({...I(c),error:`OIDC error: ${m}`,error_details:e.req.query("error_description")||null}),pe(e,i,{slug:"/"},403,"403OIDC");if(!l){const h="Code is expected but not present";return r.error(`OIDC login error: ${h}`),t&&k.sendMcpAuthorizationFailedMessage({...I(c),error:h,error_details:null}),new Response(`Forbidden: ${h}`,{status:403})}const y=e.req.header("x-forwarded-host"),g=e.req.header("x-forwarded-proto")||"https",A=t&&typeof n.redirectUri=="string"?n.redirectUri:new URL(R(D.OIDC_CALLBACK),y?`${g}://${y}`:e.req.url).toString(),C=e.get("cookies")?.code_verifier,u=await Z(p,l,A,s,{...s.tokenRequestCustomParams,...C?{code_verifier:C}:{}});if(u.error)return r.error(`Error from OIDC provider: "${u.error}"`),t&&k.sendMcpAuthorizationFailedMessage({...I(c),error:`Token exchange error: ${u.error}`,error_details:u.error_description||null}),e.text(`Forbidden: ${u.error_description||u.error}`,403);if(!u?.id_token){const h="No id_token, please, add openid to scopes";return r.error(`OIDC login error: ${h}`),t&&k.sendMcpAuthorizationFailedMessage({...I(c),error:h,error_details:null}),new Response(`Forbidden: ${h}`,{status:403})}const{payload:o,header:U}=S.decode(u.id_token),j=U.alg===ue.RS256;if(s.audience?.length&&![...q(o.aud||[]),...q(o[E]||[])].some(M=>s.audience?.includes(M))){const M="No valid audience found in id_token";return r.error(`OIDC login error: ${M}`),t&&k.sendMcpAuthorizationFailedMessage({...I(c),error:M,error_details:null}),new Response(`Forbidden: ${M}`)}const b=j?u.id_token:await S.sign({...o,idpId:f},v);ie(o)||r.warn("To display your username, the required 'email' or 'full_profile' scope must be added to the identity provider configuration");const O=s?.tokenExpirationTime?Date.now()+s.tokenExpirationTime*1e3:o.exp*1e3||Date.now()+F*1e3;if(s.introspectEndpoint){const h=await fetch(s.introspectEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({access_token:u.access_token})});if(h.ok){const P=(await h.json()).ext?.federatedIdentity;P&&(L(e,"federated_access_token",P.access_token||"",{path:_()||"/",httpOnly:!1,expires:new Date(O)}),L(e,"federated_id_token",P.id_token||"",{path:_()||"/",httpOnly:!1,expires:new Date(O)}))}else r.warn(`OIDC introspect error: ${h.statusText}`)}if(L(e,"authorization",b,{path:_()||"/",httpOnly:!0,expires:new Date(O)}),b!==u.id_token&&L(e,"idp_id_token",u.id_token||"",{path:_()||"/",httpOnly:!0,expires:new Date(O)}),L(e,"idp_access_token",u.access_token||"",{path:_()||"/",httpOnly:!0,expires:new Date(O)}),T(e,"code_verifier",{path:_()||"/"}),t&&n.redirectTo&&typeof n.redirectTo=="string"&&n.redirectTo.includes(D.MCP_CALLBACK)){const h=e.req.url.split("?")[0].replace(D.OIDC_CALLBACK,""),M=R(n.redirectTo),P=`${h}${M}`;return e.newResponse(null,302,{Location:P})}const K=typeof n.redirectTo=="string"?n.redirectTo:void 0;let J=B(new URL(K||"/",e.req.url).pathname);const V=e.newResponse(null,302,{Location:J});return r.updateContext({email:o.email,subject:o.sub}),r.info("OIDC login successful"),V}catch(p){const l=p instanceof Error?p.message:String(p),m=p instanceof Error?p.stack:String(p);if(r.error(`OIDC login error: ${l}`),t&&k.sendMcpAuthorizationFailedMessage({...I(c),error:l,error_details:m}),p.error==="access_denied")return r.info("Access denied"),e.text("Forbidden",403)}const w="Something went wrong";return r.error(`OIDC login error: ${w}`),t&&k.sendMcpAuthorizationFailedMessage({...I(c),error:w,error_details:null}),e.text(w,500)}}function ve(i){return async e=>{const r=e.get("logger"),n=e.get("auth").claims?.idpId,t=i.getConfig().ssoDirect?.[n];if(e.req.method==="POST")return $(t)||T(e,"authorization",{path:_()||"/"}),r.info("Logout successful"),e.newResponse(null,200,{});let c;if($(t)){const s=(await z(n,t)).end_session_endpoint;if(s){const d=new URL(e.req.url),w=e.req.header("x-forwarded-proto")||d.protocol.slice(0,-1)||"https",p=e.req.header("x-forwarded-host")||d.host,l=`${w}://${p}`,m=N(l),y=m?ge(JSON.stringify({branch:N(l)})):void 0,g=m?`${ce(l)}/_auth/logout`:`${l}/post-logout`;c=se(s,g,e.get("cookies")?.idp_id_token||e.get("cookies")?.authorization||"",y)}}return r.info("Logout successful"),T(e,"authorization",{path:_()||"/"}),e.newResponse(null,302,{Location:c||R("/")})}}function $e(i){return async e=>{const r=i.getConfig().logoutReturnUrl,a=r||R("/");return e.newResponse(null,302,{Location:a})}}function Ue(i){return async e=>{const r=e.get("logger"),a=e.req.param("code"),n=process.env.BH_API_URL,f=(t,c,s)=>t&&c?`${t} ${c.charAt(0)}`:s;try{if(!n)throw new Error("BH_API_URL is not set");const t=i.getConfig().ssoDirect;if(!t||!Object.keys(t).length)return r.warn("Invite no sso configured to handle"),e.redirect(R("/"));const c=await fetch(`${n}/user-invites/public/${a}`);if(!c.ok)return c.status===404?(r.warn(`Invite ${a} not found redirect to homepage`),e.redirect(R("/"))):(r.error("Invite error",await c.text()),e.redirect(R("/")));const s=await c.json(),d=new URL(R("/invite"),e.req.url);return d.searchParams.set("code",a),d.searchParams.set("org",s.organization.name),d.searchParams.set("invitedBy",f(s.invitedBy.firstName,s.invitedBy.lastName,s.invitedBy.name)),e.newResponse(null,302,{Location:d.toString()})}catch(t){return r.error("Error processing invite",{error:t,inviteCode:a}),e.text(t.message||"Failed to process invite",400)}}}function Te(i){return async e=>{const r=e.get("logger"),a=i.getConfig().ssoDirect,n=new URL(e.req.url),f=e.req.query("inviteCode"),t=e.req.header("x-forwarded-proto")||n.protocol.slice(0,-1)||"https",c=e.req.header("x-forwarded-host")||n.host,s=`${t}://${c}`;let d=n.searchParams.get("idpId");const w=n.searchParams.get("redirectTo"),p=Object.keys(a||{})[0];d=d||p;const l=n.searchParams.get("mcp_redirect_uri"),m=!!l;if(!a?.[d]){const o="Invalid idpId";if(r.error(`IdP login error: ${o}`),m){const U=H(w||void 0);k.sendMcpAuthorizationFailedMessage({...I(U),error:o,error_details:null})}return e.text(`Forbidden: ${o}`,403)}const g=d&&a?await Y(d,a[d]):void 0,A={};for(const o of Object.keys(g?.extraParams||{}))A[o]=n.searchParams.get(o)||g?.extraParams?.[o]||void 0;let C,u={};if(m&&l&&g&&g.type===G.OIDC){r.info(`Building MCP OAuth login URL with redirect_uri: ${l}`);const o=le("",{...g,extraParams:A},w,f,{redirectUriOverride:l,sourceOverride:"mcp",branchOverride:void 0});C=o.loginUrl,u=o.cookies||{}}else if(g){const o=x({...g,extraParams:A},s,w,f);C=o.loginUrl,u=o.cookies||{}}return Object.keys(u).forEach(o=>{L(e,o,u[o].value,u[o].options)}),r.info(`IdP login initiated for ID '${d}'`),e.newResponse(null,302,{Location:C||new URL(e.req.url).pathname})}}function qe(i){return async e=>{const r=e.get("logger"),a=await e.req.formData(),n=a.get("SAMLResponse"),f=a.get("RelayState");if(typeof n!="string"||typeof f!="string"){const o="SAMLResponse is required";return r.error(`SAML2 login error: ${o}`),e.text(`Bad request: ${o}`,400)}const t=ee(n),{success:c,uid:s,nameFormat:d,attrs:w,issuerId:p,expiresAt:l}=oe(t),{idpId:m,redirectTo:y}=JSON.parse(f);if(!c){const o="SAML2 assertion is not successful";return r.error(`SAML2 login error: ${o}`),e.text(`Permission denied: ${o}`,401)}if(!l||Math.ceil(Date.now()/1e3)>=l){const o="SAML2 Token Expired";return r.error(`SAML2 login error: ${o}`),e.text(o,401)}const g=i.getConfig().ssoDirect?.[m];if(!g||!Q(g)){const o="Cannot find valid IdP";return r.error(`SAML2 login error: ${o}`),e.text(`Permission denied: ${o}`,401)}if(!(g.issuerId&&p&&X(g.issuerId,p))){const o="IssuerID is misconfigured or untrusted assertions issuer received";return r.error(`SAML2 login error: ${o}`),e.text(`Permission denied: ${o}`,401)}if(!await te(t,g.x509PublicCert)){const o="SAMLResponse signature invalid";return r.error(`SAML2 login error: ${o}`),e.text(o,401)}const C=re(s,d,w,g.teamsAttributeName);if(!C.sub){const o="The provider did not return a valid user identity.";return r.error(`SAML2 login error: ${o}`),e.text(o,400)}if(!C.email){const o="The provider did not return a valid user email.";return r.error(`SAML2 login error: ${o}`),e.text(o,400)}const u=await S.sign({...C,idpId:m},v);return L(e,"authorization",u,{path:_()||"/",httpOnly:!0,expires:new Date(l*1e3)}),r.updateContext({email:C.email,subject:C.sub}),r.info("SAML2 login successful"),e.newResponse(null,302,{Location:y||"/"})}}function be(i){return async e=>{const r=e.get("logger"),a=new URL(e.req.query("redirectTo")||"/",e.req.url),n=R(B(a.pathname)),f=i.getConfig().ssoDirect,t=Object.entries(f||{}).find(([,y])=>$(y)&&de(y));if(!(f&&t))return e.newResponse(null,302,{Location:n});const s=e.req.query("token"),d=s&&await ae(s);if(!d)return e.newResponse(null,302,{Location:n});if(!q(d[E]||[]).some(y=>y===W))return e.newResponse(null,302,{Location:n});const l=await S.sign({...d,idpId:t?.at(0)},v),m=Date.now()+F*1e3;return L(e,"authorization",l,{path:_()||"/",httpOnly:!0,expires:new Date(m),sameSite:"None",secure:!0}),r.info("Token login successful"),e.newResponse(null,302,{Location:n})}}export{Oe as authorizeHandler,Te as idpLoginHandler,Ue as inviteHandler,ve as logoutHandler,Se as oidcCallbackHandler,$e as postLogoutHandler,Pe as redoclyLoginCallbackHandler,be as redoclyTokenLoginHandler,qe as samlCallbackHandler};
|
|
1
|
+
import{setCookie as R,deleteCookie as q}from"hono/cookie";import{AuthProviderType as X}from"@redocly/config";import{withPathPrefix as L,getPathPrefix as C}from"@redocly/theme/core/utils";import{compareURIs as W}from"../../../utils/url/compare-uris.js";import{ensureArray as b}from"../../../utils/array/ensure-array.js";import{ALTERNATIVE_AUD_CLAIM_NAME as F,JWT_SECRET_KEY as $,ORG_SLUG as Y,ORG_ID as Q}from"../../constants/common.js";import{DEFAULT_COOKIE_EXPIRATION as B,ServerRoutes as S}from"../../../constants/common.js";import{sanitizeRedirectPathname as z}from"../../../utils/url/sanitize-redirect-pathname.js";import{telemetry as M}from"../../telemetry/index.js";import{getAuthProviderLoginParams as Z,isOidcProviderConfig as U,isSaml2ProviderConfig as x,oidcExchangeCodeForToken as ee,buildLoginUrl as re,decodeSamlResponse as oe,extractUserClaims as ne,parseSamlResponse as te,parseOidcState as ie,verifySAMLResponse as se,getUsernameFromPayload as ae,buildOidcLogoutUrl as de,getOidcMetadata as H,getRedoclyTokenPayload as ce,isRedoclySso as le,rewritePreviewAuthRedirectUri as ue,parsePreviewBranch as N,buildOidcLoginUrl as pe,createMcpSessionResource as k}from"../auth.js";import*as P from"../jwt/jwt.js";import{AlgorithmTypes as v}from"../jwt/types.js";import{handleErrorPageRender as ge}from"../utils.js";import{encodeBase64URL as fe}from"../jwt/encode.js";async function Oe(i){if(process.env.NODE_ENV==="production")return i.newResponse(null,404,{});const{password:e,...r}=await i.req.json(),a=await P.sign({...r,name:r.username||r.email||"Unknown"},$,v.HS256);return R(i,"authorization",a,{path:C()||"/",httpOnly:!0,secure:!0,sameSite:"none"}),i.newResponse(null,200,{})}function Pe(){return async i=>{const e=i.get("logger"),r=encodeURIComponent(i.req.query("message")||"");e.error(`Login error: ${r}`);const a=`${S.LOGIN}/?error=${encodeURIComponent(r)}`;return i.newResponse(null,301,{Location:a})}}function j(i){if(!i||!i.includes(S.MCP_CALLBACK))return null;try{const e=i.split("/"),r=e[e.length-1];if(r){const a=Buffer.from(r,"base64url").toString("utf-8");return JSON.parse(a).mcpSessionId||null}}catch{}return null}function ve(i){return async e=>{const r=e.get("logger"),a=i.getConfig().ssoDirect,n=ie(e.req.query("state")),f=n.idpId,t=n.source==="mcp"||n.redirectTo&&typeof n.redirectTo=="string"&&n.redirectTo.includes(S.MCP_CALLBACK),c=t?j(typeof n.redirectTo=="string"?n.redirectTo:void 0):null,s=a?.[f];if(!U(s))return r.error("OIDC login error: missing OIDC provider config"),e.text("Forbidden",403);const d=await H(f,s);if(a&&!d.token_endpoint){const p="Invalid OIDC configuration: token_endpoint is required";return r.error(`OIDC login error: ${p}`),e.text(p,500)}try{const p=d.token_endpoint,l=e.req.query("code"),m=e.req.query("error");if(m)return t&&M.sendMcpAuthorizationFailedMessage([{...k(c),error:`OIDC error: ${m}`,error_details:e.req.query("error_description")||null}]),ge(e,i,{slug:"/"},403,"403OIDC");if(!l){const h="Code is expected but not present";return r.error(`OIDC login error: ${h}`),t&&M.sendMcpAuthorizationFailedMessage([{...k(c),error:h,error_details:null}]),new Response(`Forbidden: ${h}`,{status:403})}const w=e.req.header("x-forwarded-host"),g=e.req.header("x-forwarded-proto")||"https",A=t&&typeof n.redirectUri=="string"?n.redirectUri:new URL(L(S.OIDC_CALLBACK),w?`${g}://${w}`:e.req.url).toString(),_=e.get("cookies")?.code_verifier,u=await ee(p,l,A,s,{...s.tokenRequestCustomParams,..._?{code_verifier:_}:{}});if(u.error)return r.error(`Error from OIDC provider: "${u.error}"`),t&&M.sendMcpAuthorizationFailedMessage([{...k(c),error:`Token exchange error: ${u.error}`,error_details:u.error_description||null}]),e.text(`Forbidden: ${u.error_description||u.error}`,403);if(!u?.id_token){const h="No id_token, please, add openid to scopes";return r.error(`OIDC login error: ${h}`),t&&M.sendMcpAuthorizationFailedMessage([{...k(c),error:h,error_details:null}]),new Response(`Forbidden: ${h}`,{status:403})}const{payload:o,header:T}=P.decode(u.id_token),K=T.alg===v.RS256;if(s.audience?.length&&![...b(o.aud||[]),...b(o[F]||[])].some(I=>s.audience?.includes(I))){const I="No valid audience found in id_token";return r.error(`OIDC login error: ${I}`),t&&M.sendMcpAuthorizationFailedMessage([{...k(c),error:I,error_details:null}]),new Response(`Forbidden: ${I}`)}const E=K?u.id_token:await P.sign({...o,idpId:f},$,v.HS256);ae(o)||r.warn("To display your username, the required 'email' or 'full_profile' scope must be added to the identity provider configuration");const D=s?.tokenExpirationTime?Date.now()+s.tokenExpirationTime*1e3:o.exp*1e3||Date.now()+B*1e3;if(s.introspectEndpoint){const h=await fetch(s.introspectEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({access_token:u.access_token})});if(h.ok){const O=(await h.json()).ext?.federatedIdentity;O&&(R(e,"federated_access_token",O.access_token||"",{path:C()||"/",httpOnly:!1,expires:new Date(D)}),R(e,"federated_id_token",O.id_token||"",{path:C()||"/",httpOnly:!1,expires:new Date(D)}))}else r.warn(`OIDC introspect error: ${h.statusText}`)}if(R(e,"authorization",E,{path:C()||"/",httpOnly:!0,expires:new Date(D)}),E!==u.id_token&&R(e,"idp_id_token",u.id_token||"",{path:C()||"/",httpOnly:!0,expires:new Date(D)}),R(e,"idp_access_token",u.access_token||"",{path:C()||"/",httpOnly:!0,expires:new Date(D)}),q(e,"code_verifier",{path:C()||"/"}),t&&n.redirectTo&&typeof n.redirectTo=="string"&&n.redirectTo.includes(S.MCP_CALLBACK)){const h=e.req.url.split("?")[0].replace(S.OIDC_CALLBACK,""),I=L(n.redirectTo),O=`${h}${I}`;return e.newResponse(null,302,{Location:O})}const J=typeof n.redirectTo=="string"?n.redirectTo:void 0;let V=z(new URL(J||"/",e.req.url).pathname);const G=e.newResponse(null,302,{Location:V});return r.updateContext({email:o.email,subject:o.sub}),r.info("OIDC login successful"),G}catch(p){const l=p instanceof Error?p.message:String(p),m=p instanceof Error?p.stack:String(p);if(r.error(`OIDC login error: ${l}`),t&&M.sendMcpAuthorizationFailedMessage([{...k(c),error:l,error_details:m}]),p.error==="access_denied")return r.info("Access denied"),e.text("Forbidden",403)}const y="Something went wrong";return r.error(`OIDC login error: ${y}`),t&&M.sendMcpAuthorizationFailedMessage([{...k(c),error:y,error_details:null}]),e.text(y,500)}}function $e(i){return async e=>{const r=e.get("logger"),n=e.get("auth").claims?.idpId,t=i.getConfig().ssoDirect?.[n];if(e.req.method==="POST")return U(t)||q(e,"authorization",{path:C()||"/"}),r.info("Logout successful"),e.newResponse(null,200,{});let c;if(U(t)){const s=(await H(n,t)).end_session_endpoint;if(s){const d=new URL(e.req.url),y=e.req.header("x-forwarded-proto")||d.protocol.slice(0,-1)||"https",p=e.req.header("x-forwarded-host")||d.host,l=`${y}://${p}`,m=N(l),w=m?fe(JSON.stringify({branch:N(l)})):void 0,g=m?`${ue(l)}/_auth/logout`:`${l}/post-logout`;c=de(s,g,e.get("cookies")?.idp_id_token||e.get("cookies")?.authorization||"",w)}}return r.info("Logout successful"),q(e,"authorization",{path:C()||"/"}),e.newResponse(null,302,{Location:c||L("/")})}}function Ue(i){return async e=>{const r=i.getConfig().logoutReturnUrl,a=r||L("/");return e.newResponse(null,302,{Location:a})}}function Te(i){return async e=>{const r=e.get("logger"),a=e.req.param("code"),n=process.env.BH_API_URL,f=(t,c,s)=>t&&c?`${t} ${c.charAt(0)}`:s;try{if(!n)throw new Error("BH_API_URL is not set");const t=i.getConfig().ssoDirect;if(!t||!Object.keys(t).length)return r.warn("Invite no sso configured to handle"),e.redirect(L("/"));const c=await fetch(`${n}/user-invites/public/${a}`);if(!c.ok)return c.status===404?(r.warn(`Invite ${a} not found redirect to homepage`),e.redirect(L("/"))):(r.error("Invite error",await c.text()),e.redirect(L("/")));const s=await c.json(),d=new URL(L("/invite"),e.req.url);return d.searchParams.set("code",a),d.searchParams.set("org",s.organization.name),d.searchParams.set("invitedBy",f(s.invitedBy.firstName,s.invitedBy.lastName,s.invitedBy.name)),e.newResponse(null,302,{Location:d.toString()})}catch(t){return r.error("Error processing invite",{error:t,inviteCode:a}),e.text(t.message||"Failed to process invite",400)}}}function qe(i){return async e=>{const r=e.get("logger"),a=i.getConfig().ssoDirect,n=new URL(e.req.url),f=e.req.query("inviteCode"),t=e.req.header("x-forwarded-proto")||n.protocol.slice(0,-1)||"https",c=e.req.header("x-forwarded-host")||n.host,s=`${t}://${c}`;let d=n.searchParams.get("idpId");const y=n.searchParams.get("redirectTo"),p=Object.keys(a||{})[0];d=d||p;const l=n.searchParams.get("mcp_redirect_uri"),m=!!l;if(!a?.[d]){const o="Invalid idpId";if(r.error(`IdP login error: ${o}`),m){const T=j(y||void 0);M.sendMcpAuthorizationFailedMessage([{...k(T),error:o,error_details:null}])}return e.text(`Forbidden: ${o}`,403)}const g=d&&a?await Z(d,a[d]):void 0,A={};for(const o of Object.keys(g?.extraParams||{}))A[o]=n.searchParams.get(o)||g?.extraParams?.[o]||void 0;let _,u={};if(m&&l&&g&&g.type===X.OIDC){r.info(`Building MCP OAuth login URL with redirect_uri: ${l}`);const o=pe("",{...g,extraParams:A},y,f,{redirectUriOverride:l,sourceOverride:"mcp",branchOverride:void 0});_=o.loginUrl,u=o.cookies||{}}else if(g){const o=re({...g,extraParams:A},s,y,f);_=o.loginUrl,u=o.cookies||{}}return Object.keys(u).forEach(o=>{R(e,o,u[o].value,u[o].options)}),r.info(`IdP login initiated for ID '${d}'`),e.newResponse(null,302,{Location:_||new URL(e.req.url).pathname})}}function be(i){return async e=>{const r=e.get("logger"),a=await e.req.formData(),n=a.get("SAMLResponse"),f=a.get("RelayState");if(typeof n!="string"||typeof f!="string"){const o="SAMLResponse is required";return r.error(`SAML2 login error: ${o}`),e.text(`Bad request: ${o}`,400)}const t=oe(n),{success:c,uid:s,nameFormat:d,attrs:y,issuerId:p,expiresAt:l}=te(t),{idpId:m,redirectTo:w}=JSON.parse(f);if(!c){const o="SAML2 assertion is not successful";return r.error(`SAML2 login error: ${o}`),e.text(`Permission denied: ${o}`,401)}if(!l||Math.ceil(Date.now()/1e3)>=l){const o="SAML2 Token Expired";return r.error(`SAML2 login error: ${o}`),e.text(o,401)}const g=i.getConfig().ssoDirect?.[m];if(!g||!x(g)){const o="Cannot find valid IdP";return r.error(`SAML2 login error: ${o}`),e.text(`Permission denied: ${o}`,401)}if(!(g.issuerId&&p&&W(g.issuerId,p))){const o="IssuerID is misconfigured or untrusted assertions issuer received";return r.error(`SAML2 login error: ${o}`),e.text(`Permission denied: ${o}`,401)}if(!await se(t,g.x509PublicCert)){const o="SAMLResponse signature invalid";return r.error(`SAML2 login error: ${o}`),e.text(o,401)}const _=ne(s,d,y,g.teamsAttributeName);if(!_.sub){const o="The provider did not return a valid user identity.";return r.error(`SAML2 login error: ${o}`),e.text(o,400)}if(!_.email){const o="The provider did not return a valid user email.";return r.error(`SAML2 login error: ${o}`),e.text(o,400)}const u=await P.sign({..._,idpId:m},$,v.HS256);return R(e,"authorization",u,{path:C()||"/",httpOnly:!0,expires:new Date(l*1e3)}),r.updateContext({email:_.email,subject:_.sub}),r.info("SAML2 login successful"),e.newResponse(null,302,{Location:w||"/"})}}function Ee(i){return async e=>{const r=e.get("logger"),a=new URL(e.req.query("redirectTo")||"/",e.req.url),n=L(z(a.pathname)),f=i.getConfig().ssoDirect,t=Object.entries(f||{}).find(([,w])=>U(w)&&le(w));if(!(f&&t))return e.newResponse(null,302,{Location:n});const s=e.req.query("token"),d=s&&await ce(s);if(!d)return e.newResponse(null,302,{Location:n});if(!b(d[F]||[]).some(w=>w===Y||w===Q))return e.newResponse(null,302,{Location:n});const l=await P.sign({...d,idpId:t?.at(0)},$,v.HS256),m=Date.now()+B*1e3;return R(e,"authorization",l,{path:C()||"/",httpOnly:!0,expires:new Date(m),sameSite:"None",secure:!0}),r.info("Token login successful"),e.newResponse(null,302,{Location:n})}}export{Oe as authorizeHandler,qe as idpLoginHandler,Te as inviteHandler,$e as logoutHandler,ve as oidcCallbackHandler,Ue as postLogoutHandler,Pe as redoclyLoginCallbackHandler,Ee as redoclyTokenLoginHandler,be as samlCallbackHandler};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{telemetryTraceStep as
|
|
1
|
+
import{telemetryTraceStep as o}from"../../../telemetry/helpers/trace-step.js";import{CATALOG_ENTITY_KEY as d}from"../../../../constants/common.js";import{ALLOWED_CATALOG_QUERY_PARAMS as y}from"../../../constants/plugins/catalog-entities.js";import{allowlistObject as g}from"../../../../utils/object/allowlist-object.js";import{CatalogEntitiesService as f}from"../../../plugins/catalog-entities/database/catalog-entities-service.js";import{createPaginationParamsValidator as E}from"../../../providers/database/pagination/schemas.js";import{ENTITY_RELATION_FROM_DATABASE as A}from"../../../plugins/catalog-entities/database/mappers/field-transformations.js";import{getRbacRestrictionsDataForCatalog as b}from"../helpers/get-rbac-restrictions-data-for-catalog.js";const _=["id","key","title","type","summary","source","sourceFile","createdAt","updatedAt","version","revision"],p=async({catalogEntitiesService:i,store:a,ctx:e})=>o("catalog_entities.bff.related_entities.get_related_entities",async t=>{try{const r=e.req.param(d);if(!r)return t?.error(new Error("Entity key is required")),e.json({message:"Entity key is required"},400);t?.setAttribute("pathParams",JSON.stringify({entityKey:r}));const s=e.req.query();t?.setAttribute("queryParams",JSON.stringify(g(s,y)));const m=E(_,A).parse(s),{currentRbacTeamsForRead:l,excludedTypes:c,excludedEntities:u}=b({store:a,ctx:e}),n=await i.getRelatedEntities({entityKey:r,paginationParams:m,rbacTeams:l,excludedTypes:c,excludedEntities:u});return t?.setAttribute("relatedEntitiesCount",n.items.length),e.json(n)}catch(r){return console.error(r),t?.error(r),e.json({message:r.message},500)}});function v(i){return async a=>o("catalog_entities.bff.related_entities",async e=>{e?.setAttribute("method",a.req.method);const t=await f.getInstance({baseDbDir:i.serverOutDir});return p({catalogEntitiesService:t,ctx:a,store:i})})}export{v as bffCatalogRelatedEntitiesHandler};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{telemetryTraceStep as d}from"../../../telemetry/helpers/trace-step.js";import{CATALOG_ENTITY_KEY as g}from"../../../../constants/common.js";import{ALLOWED_CATALOG_QUERY_PARAMS as p}from"../../../constants/plugins/catalog-entities.js";import{allowlistObject as E}from"../../../../utils/object/allowlist-object.js";import{CatalogEntitiesService as b}from"../../../plugins/catalog-entities/database/catalog-entities-service.js";import{createPaginationParamsValidator as v}from"../../../providers/database/pagination/schemas.js";import{isValidIsoDate as A}from"../../../utils/is-valid-iso-date.js";import{isValidSanitizedString as q}from"../../../utils/validate-and-sanitize-string.js";import{getRbacRestrictionsDataForCatalog as l}from"../helpers/get-rbac-restrictions-data-for-catalog.js";const h=["type","key","title","summary","tags","metadata","metadata.*","git","contact","links","id","source","sourceFile","version","revision","createdAt","updatedAt","domains","owners"],w=async({catalogEntitiesService:r,ctx:e,store:n})=>d("catalog_entities.bff.get_entities",async t=>{const i=e.req.query();t?.setAttribute("queryParams",JSON.stringify(E(i,p)));const a=v(h).parse(i),{currentRbacTeamsForRead:s,excludedTypes:o,excludedEntities:u}=l({store:n,ctx:e}),m=await r.getEntitiesWithRelations({paginationParams:a,rbacTeams:s,excludedTypes:o,excludedEntities:u});return t?.setAttribute("entitiesCount",m.items.length),e.json(m)}),R=async({catalogEntitiesService:r,ctx:e,store:n})=>d("catalog_entities.bff.get_entity",async t=>{const i=e.req.param(g);if(!i)return t?.error(new Error("Entity key is required")),e.json({message:"Entity key is required"},400);const a=e.req.query("revision");let s=null;if(a){if(!A(a))return t?.error(new Error("Invalid revision parameter")),e.json({message:"Invalid revision parameter: must be a valid ISO 8601 date-time string"},400);s=a}const o=e.req.query("version");if(!q(o,{pattern:/^[a-zA-Z0-9._-]+$/,maxLength:100,allowEmpty:!0}))return t?.error(new Error("Invalid version parameter")),e.json({message:"Invalid version parameter: version must contain only alphanumeric characters, dots, hyphens, and underscores, and must not exceed 100 characters"},400);const u=e.req.query();t?.setAttribute("queryParams",JSON.stringify(u)),t?.setAttribute("pathParams",JSON.stringify({entityKey:i}));const{currentRbacTeamsForRead:m,excludedTypes:c,excludedEntities:f}=l({store:n,ctx:e}),y=await r.getEntityWithRelationsByKey({entityKey:i,filter:{revision:s,version:o},rbacTeams:m,excludedTypes:c,excludedEntities:f});return y?(t?.setAttribute("entity",JSON.stringify(y)),e.json(y)):(t?.error(new Error("Entity not found")),e.json({message:"Entity not found"},404))});function F(r){return async e=>d("catalog_entities.bff",async n=>{n?.setAttribute("method",e.req.method);const t=await b.getInstance({baseDbDir:r.serverOutDir});return e.req.param("entityKey")?R({catalogEntitiesService:t,ctx:e,store:r}):w({catalogEntitiesService:t,ctx:e,store:r})})}export{F as bffCatalogHandler};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{getCompleteCatalogConfig as
|
|
1
|
+
import{getCompleteCatalogConfig as w}from"../../../plugins/catalog-entities/get-complete-catalog-config.js";import{parseAndValidateEntities as h,parseAndValidateEntity as p,parseAndValidateEntityUpdate as b}from"../../../plugins/catalog-entities/entities/validate-entity.js";import{telemetryTraceStep as u}from"../../../telemetry/helpers/trace-step.js";import{CATALOG_FILTERS_CACHE_NAMESPACE as T,ALLOWED_CATALOG_QUERY_PARAMS as j}from"../../../constants/plugins/catalog-entities.js";import{CATALOG_ENTITY_ID as m}from"../../../../constants/common.js";import{allowlistObject as _}from"../../../../utils/object/allowlist-object.js";import{isValidIsoDate as q}from"../../../utils/is-valid-iso-date.js";import{CatalogEntitiesService as O}from"../../../plugins/catalog-entities/database/catalog-entities-service.js";import{createPaginationParamsValidator as v}from"../../../providers/database/pagination/schemas.js";import{createEntityRelationDtoFromFileSchema as C}from"../../../plugins/catalog-entities/database/mappers/create-entity-relation-dto-from-file-schema.js";import{CacheService as F}from"../../../persistence/cache/services/cache-service.js";import{hasAccessToEntity as E}from"./helpers/has-access-to-entity.js";import{getRbacRestrictionsDataForCatalog as A}from"../helpers/get-rbac-restrictions-data-for-catalog.js";const R=["type","key","title","summary","tags","metadata","metadata.*","git","contact","links","id","source","sourceFile","createdAt","updatedAt"],f=async n=>{await(await F.getInstance({baseDbDir:n})).deleteByNamespace(T)},I=async({catalogEntitiesService:n,ctx:e,store:y})=>u("catalog_entities.get_entities",async i=>{const a=e.get("logger");try{const t=e.req.query();i?.setAttribute("queryParams",JSON.stringify(_(t,j)));const{currentRbacTeamsForRead:o,excludedTypes:r,excludedEntities:s}=A({store:y,ctx:e}),d=v(R).parse(t),c=await n.getEntities({paginationParams:d,rbacTeams:o,excludedTypes:r,excludedEntities:s});return i?.setAttribute("entitiesCount",c.items.length),e.json(c)}catch(t){return a.error(t),i?.error(t),e.json({message:"Failed to get entities"},500)}}),D=async({catalogEntitiesService:n,ctx:e,store:y})=>u("catalog_entities.get_entity",async i=>{const a=e.req.param(m);if(!a)return i?.error(new Error("Entity id is required")),e.json({message:"Entity id is required"},400);i?.setAttribute("pathParams",JSON.stringify({entityId:a}));const{currentRbacTeamsForRead:t,excludedTypes:o,excludedEntities:r}=A({store:y,ctx:e}),s=await n.getEntityById(a,{rbacTeams:t,excludedTypes:o,excludedEntities:r});return s?(i?.setAttribute("entity",JSON.stringify(s)),e.json(s)):(i?.error(new Error("Entity not found")),e.json({message:"Entity not found"},404))}),P=async({catalogEntitiesService:n,ctx:e,catalogConfig:y,serverOutDir:i,store:a})=>u("catalog_entities.create_entity",async t=>{const o=e.get("logger");try{const r=await e.req.json();t?.setAttribute("requestBody",JSON.stringify(r));const s=p(r,y);if(!E({ctx:e,store:a,accessLevel:"WRITE",entityType:s.type,entityKey:s.key}))return t?.error(new Error("Access denied")),e.json({message:"Access denied"},403);const c=await n.createEntity(s),l=s.relations?.map(g=>C(s.key,g));return await n.createEntitiesRelations(l??[]),c?(f(i),t?.setAttribute("entity",JSON.stringify(c)),e.json(c)):(t?.error(new Error("Failed to create entity")),e.json({message:"Failed to create entity"},500))}catch(r){return o.error(r),r instanceof Error&&r.message.includes("validation failed")?(t?.error(new Error(r.message)),e.json({message:r.message},400)):(t?.error(r),e.json({message:"Failed to create entity"},500))}}),N=async({catalogEntitiesService:n,ctx:e,catalogConfig:y,serverOutDir:i,store:a})=>u("catalog_entities.bulk_upsert_entities",async t=>{const o=e.get("logger");try{const r=await e.req.json();t?.setAttribute("requestBody",JSON.stringify(r));const s=h(r,y);for(const l of s)if(!E({ctx:e,store:a,accessLevel:"WRITE",entityType:l.type,entityKey:l.key}))return t?.error(new Error("Access denied")),e.json({message:"Access denied"},403);const d=await n.createEntities(s);if(!d.length)return t?.error(new Error("Failed to create entities")),e.json({message:"Failed to create entities"},500);f(i);const c=d.filter(l=>l.status==="ok");return t?.setAttribute("totalSuccess",c.length),t?.setAttribute("totalFailed",d.length-c.length),e.json(d,207)}catch(r){return o.error(r),r instanceof Error&&r.message.includes("validation failed")?(t?.error(new Error(r.message)),e.json({message:r.message},400)):(t?.error(r),e.json({message:"Failed to create entities"},500))}}),W=async({catalogEntitiesService:n,ctx:e,catalogConfig:y,serverOutDir:i,store:a})=>u("catalog_entities.update_entity",async t=>{const o=e.get("logger"),r=e.req.param(m);if(!r)return t?.error(new Error("Entity id is required")),e.json({message:"Entity id is required"},400);t?.setAttribute("pathParams",JSON.stringify({entityId:r}));try{const s=await e.req.json();t?.setAttribute("requestBody",JSON.stringify(s));const d=await n.getEntityById(r);if(!d)return t?.error(new Error(`Entity with id: ${r} not found`)),e.json({message:`Entity with id: ${r} not found`},404);if(!E({ctx:e,store:a,accessLevel:"WRITE",entityType:s.type??d.type,entityKey:s.key??d.key}))return t?.error(new Error("Access denied")),e.json({message:"Access denied"},403);const l=b(s,y,s?.type??d.type);if(l.revision&&!q(l.revision))throw new Error("Entity validation failed: 'entity.revision' must be a valid ISO 8601 date-time string");const g=await n.updateEntity(l,d);return g?(f(i),t?.setAttribute("entity",JSON.stringify(g)),e.json(g)):(t?.error(new Error("Failed to update entity")),e.json({message:"Failed to update entity"},500))}catch(s){return o.error(s),s instanceof Error&&s.message.includes("validation failed")?(t?.error(new Error(s.message)),e.json({message:s.message},400)):(t?.error(s),e.json({message:s.message},500))}}),k=async({catalogEntitiesService:n,ctx:e,serverOutDir:y,store:i})=>u("catalog_entities.delete_entity",async a=>{const t=e.req.param(m);if(!t)return a?.error(new Error("Entity id is required")),e.json({message:"Entity id is required"},400);a?.setAttribute("pathParams",JSON.stringify({entityId:t}));const o=await n.getEntityById(t);return o?E({ctx:e,store:i,accessLevel:"WRITE",entityType:o.type,entityKey:o.key})?(await n.deleteEntity(o),f(y),new Response(null,{status:204})):(a?.error(new Error("Access denied")),e.json({message:"Access denied"},403)):new Response(null,{status:204})}),L={GET:I,POST:P,PUT:N},J={GET:D,DELETE:k,PATCH:W};function S(n){return async e=>u("catalog_entities",async y=>{const i=await O.getInstance({baseDbDir:n.serverOutDir}),a=e.req.method;y?.setAttribute("method",a);const t=e.req.param(m)?J:L,o=w(n.config.entitiesCatalog),r=t[a];return r?await r({catalogEntitiesService:i,ctx:e,catalogConfig:o,serverOutDir:n.serverOutDir,store:n}):(y?.error(new Error("Method not allowed")),e.json({message:"Method not allowed"},405))})}export{S as catalogHandler};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { Context } from 'hono';
|
|
2
|
+
import type { Store } from '../../../../store';
|
|
3
|
+
export declare function hasAccessToEntity({ ctx, store, accessLevel, entityType, entityKey, }: {
|
|
4
|
+
ctx: Context;
|
|
5
|
+
store: Store;
|
|
6
|
+
accessLevel: 'READ' | 'WRITE';
|
|
7
|
+
entityType: string;
|
|
8
|
+
entityKey: string;
|
|
9
|
+
}): boolean;
|
|
10
|
+
//# sourceMappingURL=has-access-to-entity.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{getNotAccessibleCatalogResources as a}from"../../../../plugins/catalog-entities/utils/get-not-accessible-catalog-resources.js";import{getCurrentRbacTeams as f}from"../../helpers/get-current-rbac-teams.js";function g({ctx:e,store:t,accessLevel:s,entityType:c,entityKey:r}){const n=t.getConfig().rbac||{},o=f(e),{types:i,entities:u}=a({rbacConfig:n,currentRbacTeams:o,accessLevel:s});return!(i.includes(c)||u.includes(r))}export{g as hasAccessToEntity};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import u from"path";import{REDOCLY_ROUTE_RBAC as E,REDOCLY_TEAMS_RBAC as w}from"@redocly/config";import{withoutPathPrefix as M,withPathPrefix as q}from"@redocly/theme/core/utils";import{CACHE_CONTROL_NO_CACHE_HEADER_VALUE as _,DEFAULT_IMMUTABLE_CACHE_MAX_AGE as O}from"../../constants/common.js";import{removeTrailingSlash as F}from"../../../utils/url/remove-trailing-slash.js";import{findInIterable as H}from"../../../utils/collection/find-in-iterable.js";import{sanitizeRedirectPathname as v}from"../../../utils/url/sanitize-redirect-pathname.js";import{sanitizePath as z}from"../../../utils/path/sanitize-path.js";import{normalizeRouteSlug as B}from"../../../utils/path/normalize-route-slug.js";import{isPathInFolder as G}from"../../../utils/path/is-path-in-folder.js";import{processRedirects as N}from"./helpers/process-redirects.js";import{renderPage as Y,getServerProps as $}from"../../ssr/index.js";import{canAccessAsset as k,canAccessResource as L}from"../../utils/rbac.js";import{handleErrorPageRender as y,handleUnauthorized as P,handleUnauthorizedAsset as U}from"../utils.js";import{DEFAULT_MAX_AGE_FOR_MIME_TYPE as V,MIME_TYPES as W}from"../mime-types.js";import{fileExistsAsync as X}from"../../utils/index.js";import{getRedirectRoute as
|
|
1
|
+
import u from"path";import{REDOCLY_ROUTE_RBAC as E,REDOCLY_TEAMS_RBAC as w}from"@redocly/config";import{withoutPathPrefix as M,withPathPrefix as q}from"@redocly/theme/core/utils";import{CACHE_CONTROL_NO_CACHE_HEADER_VALUE as _,DEFAULT_IMMUTABLE_CACHE_MAX_AGE as O}from"../../constants/common.js";import{removeTrailingSlash as F}from"../../../utils/url/remove-trailing-slash.js";import{findInIterable as H}from"../../../utils/collection/find-in-iterable.js";import{sanitizeRedirectPathname as v}from"../../../utils/url/sanitize-redirect-pathname.js";import{sanitizePath as z}from"../../../utils/path/sanitize-path.js";import{normalizeRouteSlug as B}from"../../../utils/path/normalize-route-slug.js";import{isPathInFolder as G}from"../../../utils/path/is-path-in-folder.js";import{processRedirects as N}from"./helpers/process-redirects.js";import{renderPage as Y,getServerProps as $}from"../../ssr/index.js";import{canAccessAsset as k,canAccessResource as L}from"../../utils/rbac.js";import{handleErrorPageRender as y,handleUnauthorized as P,handleUnauthorizedAsset as U}from"../utils.js";import{DEFAULT_MAX_AGE_FOR_MIME_TYPE as V,MIME_TYPES as W}from"../mime-types.js";import{fileExistsAsync as X}from"../../utils/index.js";import{getRedirectRoute as j}from"../utils/legacy-openapi-redirects.js";import{telemetry as Z}from"../../../cli/telemetry/index.js";import{telemetry as J}from"../../telemetry/index.js";function Ae(e,I,T){return async o=>{const h=o.get("logger"),c=o.req,i=new URL(c.url),n=M(z(decodeURIComponent(i.pathname))),R=u.parse(n).ext===".md",m=B(n),r=(c.method==="GET"||c.method==="HEAD")&&!R?e.getRouteBySlug(m,{followRedirect:!1})||H(e.routesBySlug?.values(),t=>t.hasClientRoutes&&(n===t.slug||n.startsWith(t.slug+"/"))):void 0,A=e.getRedirect(m);if(A){const t=N({redirect:A,reqUrlSearch:i.search});return J.sendRedirectMessage([{object:"redirect",from:m,templateId:t.type.toString()}]),o.newResponse(null,t.type,{Location:t.location})}const d=process.env.NODE_ENV==="production"?301:302;if(r?.metadata?.type==="openapi"){const t=j(i.pathname);if(t)return h.info("Legacy OpenAPI docs redirect from "+i.pathname),o.newResponse(null,d,{Location:encodeURI(t)});if(i.pathname.match(/[A-Z]/))return h.warn("Redirect to lowercase route to avoid 404 error"),o.newResponse(null,d,{Location:encodeURI(i.pathname.toLowerCase())})}if(n.endsWith("/")&&n!=="/"){const t=v(new URL(m||"/",o.req.url).pathname);return o.newResponse(null,d,{Location:encodeURI(q((t==="/"?"/":F(t))+i.search))})}const{isAuthenticated:l,teams:f,claims:{email:p}}=o.get("auth");if(r){if(!L(r,{isAuthenticated:l,email:p,teams:f},e.config.rbac,e.config.requiresLogin))return l?y(o,e,{slug:r.slug,[w]:r[w],[E]:r[E]},403):P(o,e,r.slug);const t=await I(r),s=await $(r,o,t,e),{html:b,statusCode:D}=await Y(r,s,o,e,Z);return o.html(b,D,{"Cache-Control":_})}const a=u.resolve(e.outdir,"."+n);if(!G(a,e.outdir))return U(o);if(R){const t=n==="index.html.md"?"/":n.replace(/\.md$/,""),s=e.getRouteBySlug(t,{followRedirect:!1});if(s&&!L(s,{isAuthenticated:l,email:p,teams:f},e.config.rbac,e.config.requiresLogin))return P(o,e,n)}if(!k(n,e.getGlobalConfig("rbac"),e.getGlobalConfig("requiresLogin"),e.getGlobalConfig("directoryPaths"),{isAuthenticated:l,email:p,teams:f}))return U(o);const C=W[u.extname(a)]||"text/plain",g=a.match(/assets\/.*\.[a-f0-9]{8,}\..+/)||a.match(/runtime\/chunks\/.*/)?O:V[C],S=g?{"Cache-Control":`public, max-age=${g}, immutable`,Expires:new Date(Date.now()+g*1e3).toUTCString()}:{"Cache-Control":_};if(await X(a)){const t=c.query("download")!=null,s=await T(a);return o.newResponse(s,200,{"Content-Type":C,"Access-Control-Allow-Origin":"*",...S,...t&&{"Content-Disposition":`attachment; filename="${u.basename(a)}"`}})}else return y(o,e,{slug:m},404)}}export{Ae as dynamicRouteHandler};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function t(e){return e.get("apiKeyTeams")?.length?e.get("apiKeyTeams"):e.get("auth")?.teams||[]}export{t as getCurrentRbacTeams};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { Context } from 'hono';
|
|
2
|
+
import type { Store } from '../../../store.js';
|
|
3
|
+
export declare function getRbacRestrictionsDataForCatalog({ store, ctx }: {
|
|
4
|
+
store: Store;
|
|
5
|
+
ctx: Context;
|
|
6
|
+
}): {
|
|
7
|
+
currentRbacTeamsForRead: string[];
|
|
8
|
+
excludedTypes: string[];
|
|
9
|
+
excludedEntities: string[];
|
|
10
|
+
};
|
|
11
|
+
//# sourceMappingURL=get-rbac-restrictions-data-for-catalog.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{getNotAccessibleCatalogResources as n}from"../../../plugins/catalog-entities/utils/get-not-accessible-catalog-resources.js";import{getCurrentRbacTeams as i}from"./get-current-rbac-teams.js";import{expandTeamsForRead as m}from"../../../utils/rbac.js";function b({store:o,ctx:r}){const e=o.getConfig().rbac||{},t=i(r),a=m(e,t),{types:c,entities:s}=n({rbacConfig:e,currentRbacTeams:t});return{currentRbacTeamsForRead:a,excludedTypes:c,excludedEntities:s}}export{b as getRbacRestrictionsDataForCatalog};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{serveStatic as
|
|
1
|
+
import{serveStatic as H}from"hono/serve-static";import{withPathPrefix as e,withoutPathPrefix as R}from"@redocly/theme/core/utils";import{ServerRoutes as l}from"../../../constants/common.js";import{PUBLIC_STATIC_FOLDER as L}from"../../constants/common.js";import{authMiddleware as C}from"../middleware/authMiddleware.js";import{ensureSearchData as c}from"../middleware/ensureSearchData.js";import{dynamicMiddleware as g}from"../middleware/dynamic-middleware/dynamic-middleware.js";import{installRoutes as S}from"../../plugins/dev-onboarding/api/routes/index.js";import{authorizeHandler as I,oidcCallbackHandler as P,logoutHandler as A,postLogoutHandler as D,idpLoginHandler as h,redoclyLoginCallbackHandler as M,samlCallbackHandler as N,redoclyTokenLoginHandler as v,inviteHandler as B}from"./auth.js";import{appDataHandler as U}from"./app-data.js";import{searchFacetsHandler as w,searchHandler as G}from"./search.js";import{dynamicRouteHandler as F}from"./dynamic-route.js";import{pageDataHandler as K,sharedPageDataHandler as y}from"./page-data.js";import{pathPrefixRedirectHandler as k}from"./path-prefix-redirect.js";import{getRoutesByLineHandler as _,resolvePathHandler as O,resolvePathsHandler as Y,resolveSlugHandler as E}from"./resolve-route.js";import{feedbackHandler as b}from"./feedback.js";import{loggerMiddleware as V}from"../middleware/loggerMiddleware.js";import{responseHeadersMiddleware as x}from"../middleware/responseHeadersMiddleware.js";import{idleTimeoutMiddleware as z}from"../middleware/idleTimeoutMiddleware.js";import{otelTracesHandler as Z}from"./otel/otel.js";import{healthCheckHandler as u}from"./health.js";import{askAiHandler as $}from"./ask-ai.js";import{replayOauth2RedirectCallbackHandler as q}from"./replay-oauth2-redirect.js";import{mcpOAuthProtectedResourceHandler as W,mcpOAuthAuthorizationServerHandler as j,mcpDynamicClientRegistrationHandler as J,mcpAuthorizationHandler as Q,mcpTokenPortalHandler as X,mcpCallbackHandler as r}from"./mcp-oauth.js";import{corsMiddleware as T}from"../middleware/corsMiddleware.js";import{installApiRoutes as aa}from"./api-routes/api-routes.js";import{cookieMiddleware as ea}from"../middleware/cookieMiddleware.js";import{staticContentHandler as ia}from"../routes/static-content.js";import{infoHandler as s}from"./info.js";import{catalogHandler as la}from"./catalog/catalog.js";import{catalogRelationsHandler as ta}from"./catalog/catalog-relations.js";import{bffCatalogHandler as ma}from"./catalog/bff-catalog.js";import{bffCatalogRevisionsHandler as da}from"./catalog/bff-catalog-revisions.js";import{bffCatalogRelatedEntitiesHandler as na}from"./catalog/bff-catalog-related-entities.js";import{catalogAuthMiddleware as t}from"../middleware/catalogAuthMiddleware.js";import{telemetryMiddleware as oa}from"../middleware/telemetry-middleware.js";import{errorHandler as pa}from"./error.js";function qa(a,i,m){const{resolveRouteData:n,readStaticAsset:o}=m;a.use("*",z()),a.use("*",ea()),a.use("*",g(i)),a.use("*",C(i)),a.use("*",V()),a.use("*",x(i)),a.use("*",oa()),a.use(e("*"),H({root:`./${L}`,getContent:(d,f)=>ia(d,f,i,o),rewriteRequestPath:d=>R(d)})),a.use(e(l.FEEDBACK),T({allowMethods:["POST"]})),a.use(e(l.ASK_AI),T({allowMethods:["POST"]})),a.use("*",Aa(i));const p=c(i);a.use(e(l.INFO),s()),process.env.NEW_CATALOG_ENABLED==="true"&&(a.use(e(l.CATALOG_ENTITIES),t({serverOutDir:i.serverOutDir}),la(i)),a.use(e(l.CATALOG_ENTITIES_RELATIONS),t({serverOutDir:i.serverOutDir}),ta(i)),a.get(e(l.BFF_CATALOG_ENTITIES),t({serverOutDir:i.serverOutDir,protectReadMethods:!1}),ma(i)),a.get(e(l.BFF_CATALOG_RELATED_ENTITIES),t({serverOutDir:i.serverOutDir,protectReadMethods:!1}),na(i)),a.get(e(l.BFF_CATALOG_REVISIONS),t({serverOutDir:i.serverOutDir,protectReadMethods:!1}),da(i))),a.get(e(l.SHARED_PAGE_DATA),y(i)),a.get(e(l.PAGE_DATA),K(i,n)),a.get(e(l.APP_DATA),U(i)),a.post(e(l.SEARCH),p,G(i)),a.post(e(l.SEARCH_FACETS),p,w(i)),a.post(e(l.AUTHORIZATION),I),a.post(e(l.LOGOUT),A(i)),a.get(e(l.LOGOUT),A(i)),a.get(e(l.POST_LOGOUT),D(i)),a.get(e(l.OIDC_CALLBACK),P(i)),a.get(e(l.REDOCLY_TOKEN_LOGIN),v(i)),a.get(e(l.REDOCLY_LOGIN_CALLBACK),M()),a.get(e(l.IDP_LOGIN),h(i)),a.post(e(l.SAML_CALLBACK),N(i)),a.get(e(l.INVITE),B(i)),a.get(e(l.HEALTH),u),a.get(e(l.MCP_OAUTH_PROTECTED_RESOURCE),W()),a.get(e(l.MCP_OAUTH_AUTHORIZATION_SERVER),j()),a.post(e(l.MCP_DYNAMIC_CLIENT_REGISTRATION),J()),a.get(e(l.MCP_AUTHORIZATION),Q()),a.post(e(l.MCP_TOKEN_PORTAL),X()),a.get(e(l.MCP_CALLBACK),r()),a.get(e(`${l.MCP_CALLBACK}/*`),r()),S(a,i),aa(a,i),a.post(e(l.FEEDBACK),b(i)),a.post(e(l.RESOLVE_ROUTE_BY_PATH),O(i)),a.post(e(l.RESOLVE_ROUTES_BY_PATHS),Y(i)),a.post(e(l.RESOLVE_ROUTE_BY_SLUG),E(i)),a.post(e(l.ASK_AI),$(i)),a.get(e(l.GET_ROUTES_BY_LINE),_(i)),a.post(e(l.OTEL_TRACES),Z),a.get(e(l.REPLAY_OAUTH2_CALLBACK),q),a.all(e("/*"),F(i,n,o)),a.get("*",k),a.onError(pa)}function Aa(a){return async(i,m)=>{await a.waitForPluginsLifecycle(),await m()}}function Wa(a,i){a.get(e(l.INFO),s()),a.post(e(l.RESOLVE_ROUTE_BY_PATH),O(i)),a.post(e(l.RESOLVE_ROUTE_BY_SLUG),E(i)),a.get(e(l.GET_ROUTES_BY_LINE),_(i))}export{Wa as installDevRoutes,qa as installProdRoutes,Aa as waitForPluginsLifecycle};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{getCookie as
|
|
1
|
+
import{getCookie as y}from"hono/cookie";import{ulid as S}from"ulid";import{AUTH_URL as _,JWT_SECRET_KEY as C}from"../../constants/common.js";import{ServerRoutes as d}from"../../../constants/common.js";import{withPathPrefix as m}from"@redocly/theme/core/utils";import{telemetry as l}from"../../telemetry/index.js";import{createMcpAuthorizationCode as T,verifyMcpAuthorizationCode as k,createMcpSessionResource as u}from"../auth.js";import*as h from"../jwt/jwt.js";import{AlgorithmTypes as M}from"../jwt/types.js";import{getRequestOrigin as g}from"../utils/get-request-origin.js";const n=(e,r,o=200,a)=>e.json(r,o,{"Content-Type":"application/json",...a??{}});async function I(e){const r=Math.floor(Date.now()/1e3);return h.sign({type:"mcp_context",...e,iat:r,exp:r+600},C,M.HS256)}async function A(e){await h.verify(e,C,M.HS256);const{payload:r}=h.decode(e);if(r.type!=="mcp_context")throw new Error("Invalid context token type");return r}function $(){return async e=>{if(e.req.method!=="GET")return n(e,{error:"Method not allowed"},405,{Allow:"GET"});const r=g(e);return n(e,{resource:`${r}/mcp`,authorization_servers:[r],bearer_methods_supported:["header"],resource_documentation:`${r}/.well-known/oauth-authorization-server`,scopes_supported:["openid","profile","email","offline_access"],bearer_token_types_supported:["Bearer"]})}}function H(){return async e=>{const r=g(e);return n(e,{issuer:_||"",authorization_endpoint:`${r}${d.MCP_AUTHORIZATION}`,token_endpoint:`${r}${d.MCP_TOKEN_PORTAL}`,jwks_uri:`${_||""}/.well-known/jwks.json`,registration_endpoint:`${r}${d.MCP_DYNAMIC_CLIENT_REGISTRATION}`,scopes_supported:["openid","profile","email","offline_access"],response_types_supported:["code"],grant_types_supported:["authorization_code","refresh_token","client_credentials"],subject_types_supported:["public"],id_token_signing_alg_values_supported:["RS256"],code_challenge_methods_supported:["S256"]})}}function q(){return async e=>{if(e.req.method!=="POST")return n(e,{error:"Method not allowed"},405);try{return n(e,{client_id:process.env.OAUTH_CLIENT_ID||"",client_name:"MCP Client",redirect_uris:[],grant_types:["authorization_code","refresh_token"],response_types:["code"],scope:"openid offline email",subject_type:"public",token_endpoint_auth_method:"none",created_at:new Date().toISOString(),updated_at:new Date().toISOString()},201)}catch(r){return n(e,{error:"invalid_request",error_description:r?.message||"Unable to register client"},500)}}}function b(){return async e=>{const r=new URL(e.req.url),{searchParams:o}=r,a=o.get("redirect_uri"),t=S();l.sendMcpAuthorizationStartedMessage([{...u(t),redirect_uri:a||null}]);const s=g(e),c={isMcpFlow:!0,originalRedirectUri:a,mcpClientId:o.get("client_id"),mcpState:o.get("state"),mcpSessionId:t,timestamp:Date.now()};try{const i=await I(c),p=new URL(d.IDP_LOGIN,s);return p.searchParams.set("redirectTo",`${m(d.MCP_CALLBACK)}/${i}`),p.searchParams.set("idpId","oidc"),e.redirect(p.toString())}catch(i){const p=i instanceof Error?i.message:String(i),w=i instanceof Error?i.stack:String(i);l.sendMcpAuthorizationFailedMessage([{...u(t),error:p,error_details:w}]);const f=new URL(m(`${_}/oauth2/auth`));return f.search=o.toString(),e.redirect(f.toString())}}}function j(){return async e=>{if(e.req.method!=="POST")return n(e,{error:"Method not allowed"},405);try{const r=await e.req.formData(),o=r.get("grant_type"),a=r.get("code"),t=r.get("redirect_uri")||void 0;if(o!=="authorization_code"||!a)return n(e,{error:"invalid_request",error_description:"Invalid grant type or missing authorization code"},400);try{const s=await k(a);if(t&&t!==s.redirect_uri)return n(e,{error:"invalid_grant",error_description:"redirect_uri mismatch"},400);if(process.env.OAUTH_CLIENT_ID&&s.client_id&&s.client_id!==process.env.OAUTH_CLIENT_ID)return n(e,{error:"invalid_client",error_description:"Client mismatch"},400);const c=s.id_token;return typeof c!="string"||c.length===0?n(e,{error:"invalid_grant",error_description:"Missing id_token in authorization code"},400):n(e,{access_token:c,token_type:"Bearer",expires_in:3600,scope:"openid profile email",id_token:c},200,{"Cache-Control":"no-store",Pragma:"no-cache"})}catch{return n(e,{error:"invalid_grant",error_description:"Invalid authorization code"},400)}}catch(r){const o=r instanceof Error?r.message:String(r);return n(e,{error:"server_error",error_description:"Failed to process token request",error_details:o},500)}}}function N(){return async e=>{const r=new URL(e.req.url);let o=r.searchParams.get("context");if(!o&&r.pathname.startsWith(m(`${d.MCP_CALLBACK}/`))){const t=r.pathname.split("/");o=t[t.length-1]}if(!o)return l.sendMcpAuthorizationFailedMessage([{...u(null),error:"Missing context parameter",error_details:null}]),e.text("Missing context parameter",400);let a=null;try{const t=await A(o);if(a=t.mcpSessionId||null,!t.isMcpFlow||!t.originalRedirectUri)throw new Error("Invalid MCP context");const s=y(e,"idp_id_token")||y(e,"authorization"),c=await T({idToken:s||"",clientId:t.mcpClientId||"",redirectUri:t.originalRedirectUri,ttlSec:600}),i=new URL(t.originalRedirectUri);return i.searchParams.set("code",c),t.mcpState&&i.searchParams.set("state",t.mcpState),l.sendMcpAuthorizationCompletedMessage([{...u(a),redirect_uri:t.originalRedirectUri||null}]),e.redirect(i.toString())}catch(t){const s=t instanceof Error?t.message:String(t),c=t instanceof Error?t.stack:String(t);return l.sendMcpAuthorizationFailedMessage([{...u(a),error:s,error_details:c}]),e.text(`Invalid MCP callback: ${s}`,400)}}}export{I as createMcpContextToken,b as mcpAuthorizationHandler,N as mcpCallbackHandler,q as mcpDynamicClientRegistrationHandler,H as mcpOAuthAuthorizationServerHandler,$ as mcpOAuthProtectedResourceHandler,j as mcpTokenPortalHandler,A as verifyAndParseMcpContextToken};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{DEV_LOGIN_SLUG as w,ServerRoutes as N}from"../../../constants/common.js";import{CACHE_CONTROL_NO_CACHE_HEADER_VALUE as a,DEFAULT_TITLE as O}from"../../constants/common.js";import{findInIterable as U}from"../../../utils/collection/find-in-iterable.js";import{removeTrailingSlash as $}from"../../../utils/url/remove-trailing-slash.js";import{isDevelopMode as F}from"../../utils/envs/is-develop-mode.js";import{canAccessResource as q,filterDataByAccessDeep as
|
|
1
|
+
import{DEV_LOGIN_SLUG as w,ServerRoutes as N}from"../../../constants/common.js";import{CACHE_CONTROL_NO_CACHE_HEADER_VALUE as a,DEFAULT_TITLE as O}from"../../constants/common.js";import{findInIterable as U}from"../../../utils/collection/find-in-iterable.js";import{removeTrailingSlash as $}from"../../../utils/url/remove-trailing-slash.js";import{isDevelopMode as F}from"../../utils/envs/is-develop-mode.js";import{canAccessResource as q,filterDataByAccessDeep as b,isResourcePubliclyAccessible as B}from"../../utils/rbac.js";import{getServerProps as H}from"../../ssr/index.js";import{readSharedData as V}from"../../utils/index.js";import{getRedirectLoginUrl as G}from"../utils/get-redirect-login-url.js";import{processRedirects as M}from"./helpers/process-redirects.js";import{removeErrorDetails as k}from"../utils/remove-error-details.js";import{telemetry as K}from"../../telemetry/index.js";function ae(e,s){return async(t,m)=>{const l=t.get("logger"),{req:u}=t,{pathname:d}=new URL(u.url),{seo:f,ssoDirect:h}=e.getConfig(),i=f?.title||O;if(e?.compilationErrors?.length&&F())return t.json({templateId:"compilation-error",props:{compilationErrors:e?.compilationErrors},sharedDataIds:{}},500,{"Cache-Control":a});const p=d.match(/page-data(.*)data.json$/);if(!p)return m();const c=decodeURI(p[1]),n=c==="/index/"?"/":$(c),o=e.getRouteBySlug(n,{followRedirect:!1})||U(e.routesBySlug.values(),r=>r.hasClientRoutes&&c.startsWith(r.slug));if(c===N.OIDC_CALLBACK+"/")return t.json({templateId:"403OIDC",sharedDataIds:{},props:{seo:{title:`${i} - Forbidden`}}},200,{"Cache-Control":a});const{isAuthenticated:C,teams:D,claims:{name:j,picture:A,email:I}}=t.get("auth"),R={isAuthenticated:C,email:I,teams:D},g={isAuthenticated:C,name:j,picture:A,email:I,teams:D},E=e.getRedirect(n);if(E){const r=M({redirect:E}).location;return K.sendRedirectMessage([{object:"redirect",from:n,templateId:"404"}]),t.json({templateId:"404",redirectTo:r,sharedDataIds:{},props:{}},301,{"Cache-Control":a})}if(!o){const r=e.getRouteBySlug(n,{followRedirect:!0});return l.error(`Page not found: ${d}`),t.json({templateId:"404",redirectTo:r?.slug,sharedDataIds:{},props:{seo:{title:`${i} - Not Found`}},userData:g},404,{"Cache-Control":a})}if(l.verbose(`Page viewed: ${o.slug}`),!q(o,R,e.config.rbac,e.config.requiresLogin)&&o.slug!==w){if(C)return t.json({templateId:"403",sharedDataIds:{},props:{seo:{title:`${i} - Forbidden`}},userData:g},403,{"Cache-Control":a});const r=Object.keys(h||{}).length>0;return t.json({templateId:"404",sharedDataIds:{},props:{seo:{title:`${i} - Not Found`}},userData:g,...r?{redirectTo:G(e,o.slug)}:{}},r?401:404,{"Cache-Control":a})}const S=b(o.versions,R,e.config.rbac,e.config.requiresLogin),v=e.routesSharedData.get(o.slug)||{},T=await s(o),_=await H(o,t,T,e),{sharedDataIds:y,...L}=_,P={templateId:o.templateId,versions:S,sharedDataIds:{...v,...y||{}},props:process.env.NODE_ENV==="production"?k(L):L,slug:o.slug,userData:g,isPublic:B(o,e.config)};return t.json(P,200,{"Cache-Control":a})}}function se(e){return async(s,t)=>{const m=s.get("logger"),{req:l}=s,{pathname:u}=new URL(l.url),d=u.match(/\/page-data\/shared\/(.*)\.json/);if(!d)return t();const f=decodeURIComponent(d[1]),h=await V(f,e.outdir),{isAuthenticated:i,teams:p,claims:{email:c}}=s.get("auth"),n=b(h,{isAuthenticated:i,email:c,teams:p},e.config.rbac,e.config.requiresLogin);return n?s.json(n,200,{"Cache-Control":a}):(m.error(`Shared data not found: ${u}`),s.text("Not Found",404,{"Cache-Control":a}))}}export{ae as pageDataHandler,se as sharedPageDataHandler};
|
|
@@ -12,10 +12,10 @@ export declare function handleErrorPageRender(ctx: Context, store: Store, option
|
|
|
12
12
|
};
|
|
13
13
|
}, statusCode: ClientErrorStatusCode, templateId?: string): Promise<Response>;
|
|
14
14
|
export declare function getLoginUrlWithRedirect(redirectTo: string): string;
|
|
15
|
-
export declare function handleUnauthorizedAsset(ctx: Context): Promise<Response & import("hono").TypedResponse<"Forbidden", 100 | -1 | 500 | 400 | 200 | 302 | 401 |
|
|
15
|
+
export declare function handleUnauthorizedAsset(ctx: Context): Promise<Response & import("hono").TypedResponse<"Forbidden", 100 | -1 | 500 | 400 | 200 | 302 | 401 | 403 | 300 | 301 | 102 | 103 | 201 | 202 | 203 | 206 | 207 | 208 | 226 | 303 | 305 | 306 | 307 | 308 | 402 | 404 | 405 | 406 | 407 | 408 | 409 | 410 | 411 | 412 | 413 | 414 | 415 | 416 | 417 | 418 | 421 | 422 | 423 | 424 | 425 | 426 | 428 | 429 | 431 | 451 | 501 | 502 | 503 | 504 | 505 | 506 | 507 | 508 | 510 | 511, "text">>;
|
|
16
16
|
export declare function handleUnauthorizedApiRequest(ctx: Context): Response & import("hono").TypedResponse<{
|
|
17
17
|
message: string;
|
|
18
|
-
}, 100 | -1 | 500 | 400 | 200 | 302 | 401 |
|
|
18
|
+
}, 100 | -1 | 500 | 400 | 200 | 302 | 401 | 403 | 300 | 301 | 102 | 103 | 201 | 202 | 203 | 206 | 207 | 208 | 226 | 303 | 305 | 306 | 307 | 308 | 402 | 404 | 405 | 406 | 407 | 408 | 409 | 410 | 411 | 412 | 413 | 414 | 415 | 416 | 417 | 418 | 421 | 422 | 423 | 424 | 425 | 426 | 428 | 429 | 431 | 451 | 501 | 502 | 503 | 504 | 505 | 506 | 507 | 508 | 510 | 511, "json">;
|
|
19
19
|
/**
|
|
20
20
|
* Normalize the IP address to an IPv4 address.
|
|
21
21
|
* @param address - The IP address to normalize.
|