@redocly/revel 0.138.0-next.3 → 0.138.0-next.4
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 +7 -0
- package/dist/server/constants/common.d.ts +1 -0
- package/dist/server/constants/common.js +1 -1
- package/dist/server/esbuild/esbuild-logger.js +3 -3
- package/dist/server/plugins/mcp/auth/assistant-anonymous-token.d.ts +0 -1
- package/dist/server/plugins/mcp/auth/assistant-anonymous-token.js +1 -1
- package/dist/server/utils/static-data.js +1 -1
- package/dist/server/web-server/auth.d.ts +9 -1
- package/dist/server/web-server/auth.js +4 -4
- package/dist/server/web-server/jwt/jwt.js +1 -1
- package/dist/server/web-server/jwt/token-types.d.ts +11 -0
- package/dist/server/web-server/jwt/token-types.js +1 -0
- 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/mcp-routes/mcp-oauth.js +1 -1
- package/dist/server/web-server/routes/semantic-search.d.ts +1 -1
- package/dist/server/web-server/routes/semantic-search.js +1 -1
- package/dist/server/web-server/routes/static-content.js +1 -1
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,12 @@
|
|
|
1
1
|
# @redocly/revel
|
|
2
2
|
|
|
3
|
+
## 0.138.0-next.4
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- 73d4f1d720f: Fixed an issue where builds of projects that use the AsciiDoc plugin failed even though JavaScript compilation succeeded.
|
|
8
|
+
- 5a51ac25f06: Fixed security issues in the web server.
|
|
9
|
+
|
|
3
10
|
## 0.138.0-next.3
|
|
4
11
|
|
|
5
12
|
### Minor Changes
|
|
@@ -3,6 +3,7 @@ export declare const PUBLIC_ASSETS_FOLDER = "/assets";
|
|
|
3
3
|
export declare const DEPRECATED_PUBLIC_API_DEFINITIONS_FOLDER = "/_spec";
|
|
4
4
|
export declare const PUBLIC_API_DEFINITIONS_FOLDER = "/_bundle";
|
|
5
5
|
export declare const PUBLIC_STATIC_FOLDER = "static";
|
|
6
|
+
export declare const STATIC_DATA_FOLDER = "static-data";
|
|
6
7
|
export declare const LINK_ORIGINAL_ATTR_NAME = "redocly:::linkOriginal";
|
|
7
8
|
export declare const VERSION_SEPARATOR = "@";
|
|
8
9
|
export declare const DEFAULT_VERSION_NAME = "default";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ServerRoutes as S}from"../../constants/api.js";import{USER_THEME_ALIAS as
|
|
1
|
+
import{ServerRoutes as S}from"../../constants/api.js";import{USER_THEME_ALIAS as c}from"../../constants/common.js";import{envConfig as _}from"../config/env-config.js";const U="runtime",M="/assets",P="/_spec",i="/_bundle",l="static",m="static-data",F="redocly:::linkOriginal",K="@",H="default",B=new RegExp("((?!@i18n\\/|@l10n\\/)\\/?@.*?(?=\\/))","g"),Y="@redocly/theme/plugin.js",d="styles.css",u=["@theme/plugin.js","@theme/plugin.cjs","@theme/plugin.mjs"],L="test_secret_key",G=_.JWT_SECRET_KEY||L,r=4096,p=196,g=r-p,W=3600,h=1440*60,O="@i18n",C="@l10n",J=[c,O,C,"@api","@mcp"],f="https://redocly.com/auth/aud",k="catalog.json",$="scorecard.json",j="page-count.json",w="sitemap.xml",V="llms.txt",o=_.PROJECT_ID,R=_.PROJECT_SLUG,e=_.ORGANIZATION_ID,s=_.ORG_SLUG,t=_.BH_API_URL,T=t&&s&&R?`${t}/orgs/${s}/projects/${R}`:void 0,E=t&&e&&o?`${t}/orgs/${e}/projects/${o}`:void 0,D=t?`${t}/entitlements/.well-known/jwks`:"https://app.cloud.redocly.com/api/entitlements/.well-known/jwks",X=_.ENTITLEMENTS_JWKS_CDN_URL||D,v=T?`${T}/feedback`:"",y=E?`${E}/ai-agentic-conversations`:"",b=E?`${E}/ai-assistant-escalations`:"",Z=E?`${E}/ai-assistant-feedback`:"",q=E?`${E}/semantic-search`:"",z="no-store",Q=365*24*60*60,__="X-Redocly-Cache-Control",E_="no-cache",t_="public, s-maxage=86400, max-age=10, must-revalidate",o_=_.AUTH_URL,R_="Developer Documentation",n=_.REDOCLY_SSR_RENDER_MODE==="worker"?"worker":"main",e_=n==="main"?0:_.REDOCLY_SSR_WORKERS_MIN!=null?Number(_.REDOCLY_SSR_WORKERS_MIN):2,s_=n==="main"?1:_.REDOCLY_SSR_WORKERS_MAX!=null?Number(_.REDOCLY_SSR_WORKERS_MAX):5,T_="-----BEGIN CERTIFICATE-----",n_="-----END CERTIFICATE-----",A_=!_.isDevelopMode&&_.REDOCLY_TELEMETRY!=="off"||_.REDOCLY_TELEMETRY==="on",I_="http://localhost:4318/v1/traces",S_=[S.HEALTH],A=_.SERVER_EDITOR_APP_URL||"http://127.0.0.1:3000",c_=_.REDOCLY_CORS_ORIGINS?_.REDOCLY_CORS_ORIGINS.split(",").map(I=>I.trim()).filter(Boolean).concat(A):[A],L_="markdown/partials",r_="markdown/partials-deps";export{b as AI_ASSISTANT_ESCALATIONS_API_URL,Z as AI_ASSISTANT_FEEDBACK_API_URL,c_ as ALLOWED_CORS_ORIGINS,f as ALTERNATIVE_AUD_CLAIM_NAME,y as ASK_AI_API_URL,o_ as AUTH_URL,T_ as BEGIN_CERTIFICATE_DELIMITER,T as BH_API_PROJECTS_URL,E as BH_API_PROJECTS_URL_V2,z as CACHE_CONTROL_NO_STORE_HEADER_VALUE,E_ as CACHE_CONTROL_PUBLIC_HTML,k as CATALOG_OUTPUT_FILE_NAME,Q as DEFAULT_IMMUTABLE_CACHE_MAX_AGE,u as DEFAULT_PROJECT_PLUGIN_PATHS,Y as DEFAULT_THEME_PLUGIN_PATH,R_ as DEFAULT_TITLE,H as DEFAULT_VERSION_NAME,P as DEPRECATED_PUBLIC_API_DEFINITIONS_FOLDER,n_ as END_CERTIFICATE_DELIMITER,X as ENTITLEMENTS_JWKS_URL,L as FALLBACK_JWT_SECRET_KEY,v as FEEDBACK_API_URL,O as I18N_DIR_NAME,G as JWT_SECRET_KEY,C as L10N_DIR_NAME,F as LINK_ORIGINAL_ATTR_NAME,V as LLMS_TXT_FILE_NAME,L_ as MARKDOC_PARTIALS_DATA_KEY,r_ as MARKDOC_PARTIALS_DEPS_KEY,g as MAX_AUTH_TOKEN_COOKIE_BYTES,W as MCP_ACCESS_TOKEN_TTL_SEC,h as MCP_REFRESH_SESSION_LIFETIME_SEC,e as ORG_ID,s as ORG_SLUG,S_ as OTEL_EXCLUDED_ROUTES,I_ as OTEL_TRACES_DEV_URL,j as PAGE_COUNT_OUTPUT_FILE_NAME,o as PROJECT_ID,R as PROJECT_SLUG,i as PUBLIC_API_DEFINITIONS_FOLDER,M as PUBLIC_ASSETS_FOLDER,l as PUBLIC_STATIC_FOLDER,J as RESERVED_DIR_NAMES,U as RUNTIME_RESOURCES_DIR,$ as SCORECARD_OUTPUT_FILE_NAME,q as SEMANTIC_SEARCH_API_URL,A as SERVER_EDITOR_APP_URL,w as SITEMAP_FILE_NAME,n as SSR_RENDER_MODE,s_ as SSR_WORKERS_MAX,e_ as SSR_WORKERS_MIN,m as STATIC_DATA_FOLDER,d as STYLES_FILE,A_ as TELEMETRY_ENABLED,B as VERSIONED_FOLDER_REGEXP_MATCH,K as VERSION_SEPARATOR,__ as X_REDOCLY_CACHE_CONTROL_HEADER,t_ as X_REDOCLY_CACHE_CONTROL_PUBLIC_HTML};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import*as E from"esbuild";import{logger as
|
|
2
|
-
`),hasMatched:!1};const
|
|
3
|
-
`),{lineText:s}=r,o
|
|
1
|
+
import*as E from"esbuild";import{logger as d}from"../tools/notifiers/logger.js";import{reporter as m}from"../tools/notifiers/reporter.js";import{envConfig as h}from"../config/env-config.js";import{telemetry as f}from"../../cli/telemetry/index.js";import{stopAllCompilers as y}from"./esbuild.js";import{getCodeframe as C}from"../utils/codeframes/codeframes.js";import{shutdowner as M}from"../tools/shutdowner.js";class T extends Error{errors;warnings;constructor(r){super(r.message??"",r instanceof Error?{cause:r}:void 0),this.errors=r.errors??[],this.warnings=r.warnings??[]}}async function N({errors:e,warnings:r,message:n}){const s=typeof n=="string"&&n.length>0?n:void 0,i=await g(e,"error"),l=await g(r,"warning");if(r.forEach((t,a)=>{d.warn(l[a])}),e.forEach((t,a)=>{const c=t.location?.file||"";c&&c.includes("node_modules/")?(d.error(i[a]),f.sendCliErrorCaughtMessage([{id:"cli",object:"error",uri:"urn:redocly:realm:cli:error:cli",message:JSON.stringify(t)}])):(d.contentError(i[a]),f.sendCliErrorCaughtMessage([{id:"cli",object:"error",uri:"urn:redocly:realm:cli:error:cli",message:JSON.stringify(t),scope:"content"}]))}),!e.length&&s!==void 0){const t=`JavaScript compilation failed: ${s}`;d.error(t),f.sendCliErrorCaughtMessage([{id:"cli",object:"error",uri:"urn:redocly:realm:cli:error:cli",message:t}])}(e.length>0||s!==void 0)&&h.isBuildMode&&(await y(),await M.exitWithCode(1))}async function g(e,r){return e.length?h.REDOCLY_LOG_FORMAT==="JSON"?e.map(n=>JSON.stringify(n)):await E.formatMessages(e,{kind:r,color:!1,terminalWidth:0}):[]}function w(e,r){if(!r?.lineText)return{line:1,column:1,lines:e.split(`
|
|
2
|
+
`),hasMatched:!1};const n=e.split(`
|
|
3
|
+
`),{lineText:s}=r,i=o=>{const t=o.indexOf(s);return t===-1?null:t};if(r.line&&r.line<=n.length&&i(n[r.line-1]))return{line:r.line,column:r.column||1,lines:n,hasMatched:!0};const l=n.findIndex(o=>i(o)!==null);if(l>=0){const o=i(n[l]);return{line:l+1,column:(o??0)+1,lines:n,hasMatched:!0}}return{line:1,column:1,lines:n,hasMatched:!1}}function _(e,r,n,s){const{line:i,column:l,lines:o,hasMatched:t}=w(n,s),{frame:a,start:c}=C({start:{line:i,character:l},end:{line:i,character:l+(s?.lineText?.length||0)},lines:o},!0),p=`${e}::${r}::${i}`,u={message:e,sourceFileRelativePath:r,sourceFileLocation:c,codeframe:a,hasMatched:t};return m.getCompilationProblem(p)||m.reportCompilationError({type:"ERROR",severity:"ERROR",...u}),u}export{T as EsbuildError,N as esbuildLogger,_ as reportEsbuildError};
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
export declare const ASSISTANT_ANONYMOUS_TOKEN_TYPE = "ai_assistant_anonymous";
|
|
2
1
|
/**
|
|
3
2
|
* Mints the token the portal sends with an anonymous visitor's assistant question, so that the
|
|
4
3
|
* Reunite API reaches `/mcp` with anonymous scope instead of an OAuth challenge. Returns nothing
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{hkdfSync as
|
|
1
|
+
import{hkdfSync as S}from"node:crypto";import{FALLBACK_JWT_SECRET_KEY as c}from"../../../constants/common.js";import{envConfig as o}from"../../../config/env-config.js";import{AlgorithmTypes as i}from"../../../web-server/jwt/types.js";import*as r from"../../../web-server/jwt/jwt.js";import{InternalTokenTypes as a}from"../../../web-server/jwt/token-types.js";import{toAudienceList as m}from"./token-audience.js";const T=600,u="ai-assistant-anonymous";function f(){const n=o.JWT_SECRET_KEY;if(!(!n||n===c||!o.PROJECT_ID))return Buffer.from(S("sha256",n,u,u,32)).toString("hex")}async function N(){const n=f();if(!n)return;const t=Math.floor(Date.now()/1e3);return r.sign({type:a.AI_ASSISTANT_ANONYMOUS,anonymous:!0,aud:o.PROJECT_ID,iat:t,exp:t+T},n,i.HS256)}async function I(n){const t=f();if(!t)return!1;try{await r.verify(n,t,i.HS256)}catch{return!1}const{payload:e}=r.decode(n),s=o.PROJECT_ID;return e.type===a.AI_ASSISTANT_ANONYMOUS&&e.anonymous===!0&&!!s&&m(e.aud).includes(s)}export{N as createAssistantAnonymousToken,I as isAssistantAnonymousToken};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import o from"path";import{stat as
|
|
1
|
+
import o from"path";import{stat as n,readFile as s}from"fs/promises";import{writeFileSync as c}from"fs";import{removeTrailingSlash as m}from"../../utils/url/remove-trailing-slash.js";import{STATIC_DATA_FOLDER as f}from"../constants/common.js";import{ensureDir as p}from"./fs.js";import{sanitizeWindowsFilename as u}from"./sanitize-windows-filename.js";const F=(t,a,r)=>{const i=e(t,r);c(p(i),JSON.stringify(a),"utf-8")},T=async(t,a)=>{const r=e(t,a);return await l(r)?s(r,"utf-8").then(i=>JSON.parse(i)):{}},e=(t,a)=>{const r=m(t.slice(1)),i=process.platform==="win32"?u(r):r;return o.join(a,f,`${i}.json`)};async function l(t){try{return await n(t),!0}catch{return!1}}export{T as readStaticData,F as writeStaticData};
|
|
@@ -2,6 +2,7 @@ import '../node-crypto-polyfill.js';
|
|
|
2
2
|
import { AuthProviderType } from '@redocly/config';
|
|
3
3
|
import type { AuthProviderConfig, OidcIssuerMetadata, OidcProviderConfig, RbacConfig, Saml2ProviderConfig, SsoConfig } from '@redocly/config';
|
|
4
4
|
import type { UserIDToken } from '../types';
|
|
5
|
+
import { InternalTokenTypes } from './jwt/token-types.js';
|
|
5
6
|
export type AuthProviderLoginParams = OidcLoginParams | Saml2LoginParams;
|
|
6
7
|
export type OidcJwk = {
|
|
7
8
|
n: string;
|
|
@@ -58,6 +59,13 @@ export declare function buildOidcLoginUrl(origin: string, { authorizationEndpoin
|
|
|
58
59
|
}>;
|
|
59
60
|
};
|
|
60
61
|
export declare function buildOidcLogoutUrl(endSessionEndpoint: string, postLogoutUrl: string, idTokenHint: string | undefined, state?: string): string;
|
|
62
|
+
/**
|
|
63
|
+
* True when the provider sets no `audience`, or the token's `aud` or alternative
|
|
64
|
+
* audience claim names one of its values.
|
|
65
|
+
*/
|
|
66
|
+
export declare function idTokenAudienceIsAllowed(tokenPayload: Record<string, unknown>, idpConfig: {
|
|
67
|
+
audience?: string[];
|
|
68
|
+
} | undefined): boolean;
|
|
61
69
|
export declare function isIdpIssuedToken(token: string | undefined): boolean;
|
|
62
70
|
type McpAuthorizationCodePayload = {
|
|
63
71
|
client_id: string;
|
|
@@ -85,7 +93,7 @@ export declare function createMcpAuthorizationCode(params: {
|
|
|
85
93
|
}): Promise<string>;
|
|
86
94
|
export declare function verifyMcpAuthorizationCode(code: string): Promise<McpAuthorizationCodePayload>;
|
|
87
95
|
export type McpRefreshTokenPayload = {
|
|
88
|
-
type:
|
|
96
|
+
type: typeof InternalTokenTypes.MCP_REFRESH_TOKEN;
|
|
89
97
|
client_id: string;
|
|
90
98
|
idp_id?: string;
|
|
91
99
|
claims: Record<string, unknown>;
|
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import"../node-crypto-polyfill.js";import{DOMParser as
|
|
1
|
+
import"../node-crypto-polyfill.js";import{DOMParser as v}from"@xmldom/xmldom";import{SignedXml as Z}from"xml-crypto";import Q from"xpath";import{deflateSync as ee,inflateSync as te}from"fflate";import{createHash as ne}from"crypto";import{ulid as re}from"ulid";import{AuthProviderType as p,DEFAULT_TEAM_CLAIM_NAME as U}from"@redocly/config";import{ALTERNATIVE_AUD_CLAIM_NAME as oe,AUTH_URL as se,JWT_SECRET_KEY as w,MAX_AUTH_TOKEN_COOKIE_BYTES as ae}from"../constants/common.js";import{ensureArray as k}from"../../utils/array/ensure-array.js";import{envConfig as ie}from"../config/env-config.js";import{decryptClaimValue as ce}from"../utils/crypto/decrypt-claim-value.js";import{getPathPrefix as ue,withPathPrefix as le}from"@redocly/theme/core/utils";import{ServerRoutes as j}from"../../constants/api.js";import{AuthCookieNames as g,DEFAULT_AUTHENTICATED_TEAM as de,REQUIRED_OIDC_SCOPES as V}from"../../constants/common.js";import{appendQueryParams as me}from"../../utils/url/append-query-params.js";import{parsePreviewUrl as B}from"../../utils/url/parse-preview-url.js";import{logger as R}from"../tools/notifiers/logger.js";import{randomString as pe}from"../utils/crypto/random-string.js";import{randomUUID as H}from"../utils/crypto/random-uuid.js";import{AlgorithmTypes as u,JwtTokenExpired as fe}from"./jwt/types.js";import*as l from"./jwt/jwt.js";import{InternalTokenTypes as T}from"./jwt/token-types.js";import{parseTeamClaimToArray as he}from"../utils/index.js";import{parseTeamNameTemplate as ye}from"../utils/rbac-expand.js";import{arrayBufferToBase64 as Ae,decodeBase64 as $,encodeBase64URL as we,urlSafeBase64 as F}from"./jwt/encode.js";import{formatSamlCertificate as Se}from"./utils/format-saml-certificate.js";const _e=new Set(Object.values(T));function O(e){return e?.type===p.OIDC}function Te(e){return e?.type===p.SAML2}async function At(e,t){if(O(t))return xe(e,t);if(Te(t))return ge(e,t)}async function xe(e,t){const n=await Y(e,t),r=new Set((t.scopes||[]).concat(V)),o=t.authorizationRequestCustomParams||{};return{type:p.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 ge(e,t){return{type:p.SAML2,idpId:e,name:"SAML2 provider",ssoUrl:t.ssoUrl,issuerId:t.issuerId,entityId:t.entityId||t.issuerId}}function K(e){return Array.from(new Set((e.scopes||[]).concat(V))).join(" ")}async function z(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 wt(e,t,n,r,o={}){return await z(e,r,{scope:K(r),code:t,redirect_uri:W(n),grant_type:"authorization_code",...o})}async function St(e,t,n){return await z(e,n,{scope:K(n),grant_type:"refresh_token",refresh_token:t})}function Ie(e,{authorizationEndpoint:t,clientId:n,responseType:r,scope:o,extraParams:s,idpId:a,pkce:f},d,h,m){if(!t||!n||!r||!o)return{loginUrl:void 0};const i=new URL(t),A=m?.redirectUriOverride??`${e}${le(j.OIDC_CALLBACK)}`,S={state:H(),idpId:a,redirectUri:A,redirectTo:d,branch:m?.branchOverride??Re(e),inviteCode:h,source:m?.sourceOverride??"portal",uiLocales:m?.uiLocales},_={};if(f){const y=F(pe(50)),I=F(ne("sha256").update(y).digest("base64")),E="S256";i.searchParams.append("code_challenge",I),i.searchParams.append("code_challenge_method",E),_.code_verifier={value:y,options:{secure:!0,httpOnly:!0,expires:new Date(Date.now()+1e3*60*10),path:ue()||"/"}}}i.searchParams.append("client_id",n),i.searchParams.append("scope",o),i.searchParams.append("response_type",r),i.searchParams.append("redirect_uri",W(A)),i.searchParams.append("state",we(JSON.stringify(S))),m?.uiLocales&&i.searchParams.append("ui_locales",m.uiLocales);for(const y in s)s[y]!==void 0&&i.searchParams.append(y,s[y]);return{loginUrl:i.toString(),cookies:_}}function _t(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 Ee(e,t){const n=t?.audience;return n?.length?[...k(e.aud||[]),...k(e[oe]||[])].some(o=>n.includes(o)):!0}function ke(e,t){return!O(t)||!je(t)||!t.clientId?!0:k(e.aud||[]).includes(t.clientId)}function Tt(e){if(!e)return!1;try{return l.decode(e).header.alg===u.RS256}catch{return!1}}async function xt(e){const t=Math.floor(Date.now()/1e3),n=t+(e.ttlSec??600);return l.sign({type:T.MCP_AUTHORIZATION_CODE,client_id:e.clientId,redirect_uri:e.redirectUri,id_token:e.idToken,...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},w,u.HS256)}async function gt(e){await l.verify(e,w,u.HS256);const{payload:t}=l.decode(e);if(t.type!==T.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");return t}async function It(e){const t=Math.floor(Date.now()/1e3);return l.sign({type:T.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},w,u.HS256)}async function Et(e){await l.verify(e,w,u.HS256);const{payload:t}=l.decode(e);if(t.type!==T.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 kt(e){const t=e||re(),n=t.startsWith("mcp_")?t:`mcp_${t}`;return{id:n,object:"mcpSession",uri:`urn:redocly:realm:mcp:session:${n}`}}function W(e){const t=B(e);if(!t)return e;const n=Oe(t.hostname);if(n)return t.hostname=`previewauth--${n.previewBranch}${n.after}`,J(e,t);const r=q(t.hostname);return r?(t.hostname=`${r.projectSlug}.previewauth.${r.after}`,J(e,t)):e}function Re(e){const t=B(e);if(t)return q(t.hostname)?.previewBranch}function J(e,t){return e.replace(/^https?:\/\/[^/?#]+/i,`${t.protocol}//${t.host}`)}function q(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),a=n.slice(o+2);return!s||!a||a.includes(".")?null:{projectSlug:s,previewBranch:a,after:r}}function Oe(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 Me(e){return e.type===p.OIDC}function Ce(e){return e.type===p.SAML2}function Rt(e,t,n,r,o){return Me(e)?Ie(t,e,n,r,{uiLocales:o}):Ce(e)?Le(t,e,n,r,o):{}}function Le(e,t,n,r,o){const a=`<samlp:AuthnRequest xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
|
|
2
2
|
xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
|
|
3
3
|
Version="2.0"
|
|
4
|
-
ID="_${
|
|
4
|
+
ID="_${H()}"
|
|
5
5
|
IssueInstant="${new Date().toISOString()}"
|
|
6
|
-
AssertionConsumerServiceURL="${e}${
|
|
6
|
+
AssertionConsumerServiceURL="${e}${j.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>`,
|
|
12
|
+
</samlp:AuthnRequest>`,f=Ne(a);return{loginUrl:me(t.ssoUrl,{SAMLRequest:f,RelayState:JSON.stringify({idpId:t.idpId,redirectTo:n,inviteCode:r,source:"portal",uiLocales:o})})}}function Ne(e){return Ae(ee(new TextEncoder().encode(e)).buffer)}function Ot(e){const t=$(e);if(t.startsWith("<samlp:Response")||t.indexOf("<saml2p:Response")>-1)return t;const n=te(new Uint8Array(atob(e).split("").map(r=>r.charCodeAt(0))));return new TextDecoder().decode(n)}function Mt(e){try{return JSON.parse($(e||""))}catch{throw new Error("Invalid OAuth2 state")}}function Ct(e){const t=new v().parseFromString(e,"application/xml"),r=c(t,"//*[local-name(.)='StatusCode']/@Value")[0]?.nodeValue?.endsWith("Success")||!1,s=c(t,"//*[local-name(.)='Response']/@Destination")[0]?.nodeValue||"",a=c(t,"//*[local-name(.)='Assertion']//*[local-name(.)='Issuer']/text()")[0],f=a&&a.nodeValue||void 0,d=c(t,"//*[local-name(.)='Audience']/text()")[0],h=d&&d.nodeValue||void 0,i=c(t,"//*[local-name(.)='Assertion']//*[local-name(.)='X509Certificate']/text()")[0]?.nodeValue||"",A=c(t,"//*[local-name(.)='Subject']//*[local-name(.)='NameID']/text()")[0],S=A&&A.nodeValue||"",_=c(t,"//*[local-name(.)='Subject']//*[local-name(.)='NameID']/@Format")[0],y=_&&_.nodeValue||"",I=c(t,"//*[local-name(.)='Conditions']/@NotOnOrAfter")[0],E=De(I),L={},N=c(t,"//*[local-name(.)='AttributeStatement']//*[local-name(.)='Attribute']");if(N.length)for(const D of N){const b=c(D,"./@Name")[0];if(b.nodeValue){const P=c(D,"./*[local-name(.)='AttributeValue']/text()")[0];P?.nodeValue&&(L[b.nodeValue]=P.nodeValue)}}return{uid:S,success:r,expiresAt:E,issuerId:f,entityId:h,attrs:L,cert:i,nameFormat:y,destination:s}}function De(e){const t=typeof e?.nodeValue=="string"&&M(Date.parse(e.nodeValue)),n=M(Date.now()),r=M(Date.now()+720*60*1e3);return t?t>n&&t<r?r:t:n}function M(e){return Math.floor(e/1e3)}const C={},x={jwks:{}};async function Y(e,t){if(!C[e]){const n=t.configurationUrl?await G(t.configurationUrl):t.configuration;C[e]=be()?ve(n):n}return C[e]}function be(){const e=ie.REDOCLY_ENFORCE_RESIDENCY;return!!e&&e.includes("host.docker.internal")}const Pe=["authorization_endpoint","end_session_endpoint"];function ve(e){if(typeof e!="object"||e===null)return e;const t={...e};for(const n of Object.keys(t)){if(Pe.includes(String(n)))continue;const r=t[n];typeof r=="string"&&r.includes("://localhost")&&(t[n]=r.replace("://localhost","://host.docker.internal"))}return t}async function Ue(e){for(const t of Object.keys(e)){const n=e[t];if(!O(n))continue;const r=await Y(t,n);if(r.jwks_uri){const o=await G(r.jwks_uri);for(const s of o.keys)x.jwks[s.kid]={...s,idpId:t}}}}async function G(e){return fetch(e,{headers:{Accept:"application/json"}}).then(t=>t.json())}async function Lt(e){return fetch(`${se}/oidc/userinfo`,{headers:{Accept:"application/json",Authorization:`Bearer ${e}`}}).then(t=>t.status===200?t.json():void 0).catch(()=>{})}function je(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=>Ve(t.hostname,r))}function Ve(e,t){return e===t||e.endsWith(`.${t}`)}async function Nt(e,t){const n=new v().parseFromString(e,"application/xml"),r=c(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=Se(t),s=new Z({publicCert:o});s.loadSignature(r);try{return s.checkSignature(e)}catch{return!1}}function Be(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 He(e,t,n){if(!t)return e;const r=Be(t),o=s=>{const a=n?.[s]||s;return r.has(a)||!!ye(t,a)};return[...e.filter(o),...e.filter(s=>!o(s))]}async function Dt(e,t,n,r){const o=n?e[n]:void 0,s=Array.isArray(o)?He(o.map(String),r?.rbacConfig,r?.teamsMapping):[];let a=s.length;const f=s.length+1;for(let d=0;d<f;d++){const h={...e,idpId:t};n&&s.length&&(h[n]=s.slice(0,a));const m=await l.sign(h,w,u.HS256),i=Buffer.byteLength(m)-ae;if(i<=0)return{token:m,teamsTotal:s.length,teamsKept:a,droppedTeams:s.slice(a)};if(a===0)return null;const A=Buffer.byteLength(JSON.stringify(s.slice(0,a))),S=Math.max(1,A/a*4/3);a=Math.max(0,a-Math.max(1,Math.ceil(i/S)))}return null}function bt(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(/.+@.+/)&&(o=e);const s=n["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name"],a=s?.match(/.+@.+/);return o=o||n["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress"]||(a?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?he(n[r]):[]}}function X(e,t={}){return e.map(n=>t[n]||n)}async function Pt(e,t){if(!t)return{};const n=t[g.AUTHORIZATION];if(!n)return{};try{const r=l.decode(n);if(typeof r.payload.type=="string"&&_e.has(r.payload.type))return{};if(r.header.alg===u.RS256){x.jwks[r.header.kid]===void 0&&await Ue(e);const h=x.jwks[r.header.kid];if(!h)return x.jwks[r.header.kid]=null,{};await l.verify(n,h,u.RS256)}else await l.verify(n,w,u.HS256);const s=r.payload.idpId||x.jwks[r.header.kid]?.idpId,a=e[s]||{};if(r.header.alg===u.RS256&&typeof r.payload.exp!="number")return R.warn("Rejected id_token: it has no exp claim"),{};if(r.header.alg===u.RS256&&!(Ee(r.payload,a)&&ke(r.payload,a)))return R.warn("Rejected id_token: it was issued for another project"),{};const f=Ke(a),d=Fe(a);return{...r.payload,email:r.payload.email?.toLowerCase(),idpId:s,teams:Array.from(new Set([...X(r.payload.teams||[],d),..."defaultTeams"in a&&a.defaultTeams||[],...X("teamsClaimName"in a&&r.payload[f||""]||[],d),de])),name:$e(r.payload),isAuthenticated:!0,idpAccessToken:ce(r.payload.idp_access_token,w)||t[g.IDP_ACCESS_TOKEN],federatedAccessToken:t[g.FEDERATED_ACCESS_TOKEN],federatedIdToken:t[g.FEDERATED_ID_TOKEN],authCookie:n}}catch(r){r instanceof fe||R.error("Malformed JWT token: %s",r.message)}return{}}function $e(e){return(e.firstName&&e.lastName?`${e.firstName} ${e.lastName}`:e.name||e.given_name||e.firstName||e.lastName)||e.email}function Fe(e){switch(e.type){case p.SAML2:return e.teamsAttributeMap;case p.OIDC:return e.teamsClaimMap;default:return}}function Ke(e){switch(e.type){case p.SAML2:return e.teamsAttributeName??U;case p.OIDC:return e.teamsClaimName;default:return U}}function c(e,t){return Q.select(t,e)||[]}export{Rt as buildLoginUrl,Ie as buildOidcLoginUrl,_t as buildOidcLogoutUrl,Le as buildSAML2LoginUrl,xt as createMcpAuthorizationCode,It as createMcpRefreshToken,kt as createMcpSessionResource,Ot as decodeSamlResponse,Ue as discoverJwks,Ne as encodeSAML2,bt as extractUserClaims,At as getAuthProviderLoginParams,xe as getOidcLoginParams,Y as getOidcMetadata,Lt as getRedoclyTokenPayload,ge as getSaml2LoginParams,Pt as getUserParamsFromCookies,$e as getUsernameFromPayload,Ee as idTokenAudienceIsAllowed,Tt as isIdpIssuedToken,O as isOidcProviderConfig,je as isRedoclySso,Te as isSaml2ProviderConfig,wt as oidcExchangeCodeForToken,x as oidcJwksCache,C as oidcMetadataCache,St as oidcRefreshTokenGrant,He as orderTeamsRbacFirst,Mt as parseOidcState,Re as parsePreviewBranch,Ct as parseSamlResponse,W as rewritePreviewAuthRedirectUri,Dt as signTokenWithinCookieSizeLimit,gt as verifyMcpAuthorizationCode,Et as verifyMcpRefreshToken,Nt as verifySAMLResponse};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"../../node-crypto-polyfill.js";import{utf8ToUint8Array as u,encodeBase64URL as
|
|
1
|
+
import"../../node-crypto-polyfill.js";import{timingSafeEqual as H}from"node:crypto";import{utf8ToUint8Array as u,encodeBase64URL as m,arrayBufferToBase64URL as w,decodeBase64URL as S}from"./encode.js";import{decodeJwtSignature as b}from"./decode-jwt-signature.js";import{AlgorithmTypes as s,JwtAlgorithmNotImplemented as E,JwtTokenInvalid as d,JwtTokenNotBefore as K,JwtTokenExpired as T,JwtTokenSignatureMismatched as B,CryptoKeyFormat as h,CryptoKeyUsage as l}from"./types.js";const p=e=>{switch(e.toUpperCase()){case"HS256":return{name:"HMAC",hash:{name:"SHA-256"}};case"HS384":return{name:"HMAC",hash:{name:"SHA-384"}};case"HS512":return{name:"HMAC",hash:{name:"SHA-512"}};case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"ES256":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw new E(e)}},g=async(e,t,n=s.HS256)=>{if(!crypto.subtle||!crypto.subtle.importKey)throw new Error("`crypto.subtle.importKey` is undefined. JWT auth middleware requires it.");t.startsWith("-----BEGIN PRIVATE KEY-----")&&(t=t.replace("-----BEGIN PRIVATE KEY-----","").replace("-----END PRIVATE KEY-----","").split(/\\n|\n/).join("").trim(),t=atob(t));const r=n===s.RS256||n===s.ES256,o=await crypto.subtle.importKey(r?h.PKCS8:h.RAW,r?C(t):u(t),p(n),!1,[l.Sign]);return await crypto.subtle.sign(p(n),o,u(e))};function C(e){const t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let r=0,o=e.length;r<o;r++)n[r]=e.charCodeAt(r);return t}const V=async(e,t,n=s.HS256,r)=>{const o=await m(JSON.stringify(e)),i=`${await m(JSON.stringify({alg:n,typ:"JWT",kid:r}))}.${o}`,c=await w(await g(i,t,n));return`${i}.${c}`},k=async(e,t,n=s.HS256,r=!1)=>{const o=e.split(".");if(o.length!==3)throw new d;const{payload:a}=J(e),i=Math.floor(Date.now()/1e3);if(typeof a.nbf=="number"&&a.nbf>i)throw new K;if(!r&&typeof a.exp=="number"&&a.exp<=i)throw new T;const c=o.slice(0,2).join("."),y=o[2];let f=!1;if(typeof t!="string")f=await N(c,y,t,n);else{const A=await w(await g(c,t,n));f=R(A,y)}if(!f)throw new B;return!0};function R(e,t){const n=Buffer.from(e),r=Buffer.from(t);return n.length===r.length&&H(n,r)}const J=e=>{try{const[t,n]=e.split("."),r=JSON.parse(S(t)),o=JSON.parse(S(n));return{header:r,payload:o}}catch{throw new d}},N=async(e,t,n,r)=>{const o=await crypto.subtle.importKey("jwk",n,p(r),!1,[l.Verify]);return await crypto.subtle.verify(p(r),o,b(t),u(e))};export{J as decode,V as sign,k as verify};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export declare const InternalTokenTypes: {
|
|
2
|
+
readonly MCP_CONTEXT: 'mcp_context';
|
|
3
|
+
readonly MCP_AUTHORIZATION_CODE: 'mcp_auth_code';
|
|
4
|
+
readonly MCP_REFRESH_TOKEN: 'mcp_refresh_token';
|
|
5
|
+
readonly AI_ASSISTANT_ANONYMOUS: 'ai_assistant_anonymous';
|
|
6
|
+
};
|
|
7
|
+
export declare const McpAccessTokenMarker: {
|
|
8
|
+
readonly CLAIM: 'token_use';
|
|
9
|
+
readonly VALUE: 'mcp_access_token';
|
|
10
|
+
};
|
|
11
|
+
//# sourceMappingURL=token-types.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const e={MCP_CONTEXT:"mcp_context",MCP_AUTHORIZATION_CODE:"mcp_auth_code",MCP_REFRESH_TOKEN:"mcp_refresh_token",AI_ASSISTANT_ANONYMOUS:"ai_assistant_anonymous"},_={CLAIM:"token_use",VALUE:"mcp_access_token"};export{e as InternalTokenTypes,_ as McpAccessTokenMarker};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{setCookie as L,deleteCookie as P}from"hono/cookie";import{AuthProviderType as ee,DEFAULT_TEAM_CLAIM_NAME as re}from"@redocly/config";import{withPathPrefix as w,getPathPrefix as A}from"@redocly/theme/core/utils";import{compareURIs as oe}from"../../../utils/url/compare-uris.js";import{ensureArray as N}from"../../../utils/array/ensure-array.js";import{ALTERNATIVE_AUD_CLAIM_NAME as H,JWT_SECRET_KEY as U,MAX_AUTH_TOKEN_COOKIE_BYTES as F,ORG_SLUG as te,ORG_ID as ne}from"../../constants/common.js";import{AUTH_SEGMENT as ie,ServerRoutes as D}from"../../../constants/api.js";import{AuthCookieNames as _,DEFAULT_COOKIE_EXPIRATION as K}from"../../../constants/common.js";import{sanitizeRedirectPathname as z}from"../../../utils/url/sanitize-redirect-pathname.js";import{telemetry as k}from"../../telemetry/index.js";import{envConfig as j}from"../../config/env-config.js";import{fetchWithClient as se}from"../../utils/fetch-with-client.js";import{clearAuthCookies as J,clearPostLogoutCookie as v,hasPostLogoutCookie as ae,setPostLogoutCookie as G}from"../../utils/cookie.js";import{getAuthProviderLoginParams as de,isOidcProviderConfig as b,isSaml2ProviderConfig as le,oidcExchangeCodeForToken as ce,buildLoginUrl as ue,decodeSamlResponse as pe,extractUserClaims as ge,parseSamlResponse as fe,parseOidcState as me,verifySAMLResponse as he,getUsernameFromPayload as Ce,buildOidcLogoutUrl as Ie,isIdpIssuedToken as _e,getOidcMetadata as Z,getRedoclyTokenPayload as Ae,isRedoclySso as Re,rewritePreviewAuthRedirectUri as Oe,parsePreviewBranch as V,buildOidcLoginUrl as Te,createMcpSessionResource as M,signTokenWithinCookieSizeLimit as W}from"../auth.js";import*as E from"../jwt/jwt.js";import{AlgorithmTypes as $}from"../jwt/types.js";import{handleErrorPageRender as ye}from"../utils.js";import{encodeBase64URL as Le}from"../jwt/encode.js";import{resolveUiLocalesForIdpLogin as we}from"./helpers/resolve-ui-locales-for-idp-login.js";async function Je(n){if(j.isProductionEnv)return n.newResponse(null,404,{});const{password:e,...r}=await n.req.json(),d=await E.sign({...r,name:r.username||r.email||"Unknown"},U,$.HS256);return L(n,_.AUTHORIZATION,d,{path:A()||"/",httpOnly:!0,secure:!0,sameSite:"none"}),v(n),n.newResponse(null,200,{})}function Ge(){return async n=>{const e=n.get("logger"),r=encodeURIComponent(n.req.query("message")||"");e.error(`Login error: ${r}`);const d=`${D.LOGIN}/?error=${encodeURIComponent(r)}`;return n.newResponse(null,301,{Location:d})}}function X(n){if(!n||!n.includes(D.MCP_CALLBACK))return null;try{const e=n.split("/"),r=e[e.length-1];if(r){const d=Buffer.from(r,"base64url").toString("utf-8");return JSON.parse(d).mcpSessionId||null}}catch{}return null}function Ze(n){return async e=>{const r=e.get("logger"),d=n.getConfig().ssoDirect;let o;try{o=me(e.req.query("state"))}catch{return r.warn("OIDC login error: Invalid OAuth2 state"),e.text("Bad request: Invalid OAuth2 state",400)}const h=o.idpId,i=o.source==="mcp"||o.redirectTo&&typeof o.redirectTo=="string"&&o.redirectTo.includes(D.MCP_CALLBACK),u=i?X(typeof o.redirectTo=="string"?o.redirectTo:void 0):null,s=d?.[h];if(!b(s))return r.error("OIDC login error: missing OIDC provider config"),e.text("Forbidden",403);const p=await Z(h,s);if(d&&!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,g=e.req.query("code"),C=e.req.query("error");if(C)return i&&k.sendMcpAuthorizationFailedMessage([{...M(u),error:`OIDC error: ${C}`,error_details:e.req.query("error_description")||null}]),ye(e,n,{slug:"/"},403,"403OIDC");if(!g){const f="Code is expected but not present";return r.error(`OIDC login error: ${f}`),i&&k.sendMcpAuthorizationFailedMessage([{...M(u),error:f,error_details:null}]),new Response(`Forbidden: ${f}`,{status:403})}const O=typeof o.redirectUri=="string"?o.redirectUri:new URL(w(D.OIDC_CALLBACK),e.req.url).toString(),I=e.get("cookies")?.code_verifier,a=await ce(m,g,O,s,{...s.tokenRequestCustomParams,...I?{code_verifier:I}:{}});if(a.error)return r.error(`Error from OIDC provider: "${a.error}"`),i&&k.sendMcpAuthorizationFailedMessage([{...M(u),error:`Token exchange error: ${a.error}`,error_details:a.error_description||null}]),e.text(`Forbidden: ${a.error_description||a.error}`,403);if(!a?.id_token){const f="No id_token, please, add openid to scopes";return r.error(`OIDC login error: ${f}`),i&&k.sendMcpAuthorizationFailedMessage([{...M(u),error:f,error_details:null}]),new Response(`Forbidden: ${f}`,{status:403})}const{payload:l,header:y}=E.decode(a.id_token),t=y.alg===$.RS256;if(s.audience?.length&&![...N(l.aud||[]),...N(l[H]||[])].some(T=>s.audience?.includes(T))){const T="No valid audience found in id_token";return r.error(`OIDC login error: ${T}`),i&&k.sendMcpAuthorizationFailedMessage([{...M(u),error:T,error_details:null}]),new Response(`Forbidden: ${T}`)}let c=t?a.id_token:await E.sign({...l,idpId:h},U,$.HS256);if(Buffer.byteLength(c)>F){const f=await W(l,h,s.teamsClaimName,{rbacConfig:n.getConfig().access?.rbac,teamsMapping:s.teamsClaimMap});if(!f){const T=`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: ${T}`),i&&k.sendMcpAuthorizationFailedMessage([{...M(u),error:T,error_details:null}]),e.text(`Forbidden: ${T}`,403)}f.teamsKept<f.teamsTotal&&r.warn(`OIDC login: the "${s.teamsClaimName}" claim is too large for the session cookie size limit; kept ${f.teamsKept} of ${f.teamsTotal} values, with teams from the RBAC configuration first; RBAC ignores the dropped teams: ${JSON.stringify(f.droppedTeams)}`),c=f.token}Ce(l)||r.warn("To display your username, the required 'email' or 'full_profile' scope must be added to the identity provider configuration");const S=s?.tokenExpirationTime?Date.now()+s.tokenExpirationTime*1e3:l.exp*1e3||Date.now()+K*1e3;if(s.introspectEndpoint){const f=await fetch(s.introspectEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({access_token:a.access_token})});if(f.ok){const q=(await f.json()).ext?.federatedIdentity;q&&(L(e,_.FEDERATED_ACCESS_TOKEN,q.access_token||"",{path:A()||"/",httpOnly:!1,expires:new Date(S)}),L(e,_.FEDERATED_ID_TOKEN,q.id_token||"",{path:A()||"/",httpOnly:!1,expires:new Date(S)}))}else r.warn(`OIDC introspect error: ${f.statusText}`)}if(L(e,_.AUTHORIZATION,c,{path:A()||"/",httpOnly:!0,expires:new Date(S)}),c!==a.id_token&&Buffer.byteLength(a.id_token)<=F?L(e,_.IDP_ID_TOKEN,a.id_token||"",{path:A()||"/",httpOnly:!0,expires:new Date(S)}):P(e,_.IDP_ID_TOKEN,{path:A()||"/"}),L(e,_.IDP_ACCESS_TOKEN,a.access_token||"",{path:A()||"/",httpOnly:!0,expires:new Date(S)}),a.refresh_token?L(e,_.IDP_REFRESH_TOKEN,a.refresh_token,{path:A()||"/",httpOnly:!0,expires:new Date(S)}):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(D.MCP_CALLBACK)){const T=`${e.req.url.split("?")[0].replace(D.OIDC_CALLBACK,"")}${o.redirectTo}`;return e.newResponse(null,302,{Location:T})}const Y=typeof o.redirectTo=="string"?o.redirectTo:void 0;let Q=z(new URL(Y||"/",e.req.url).pathname);const x=e.newResponse(null,302,{Location:Q});return r.updateContext({email:l.email,subject:l.sub}),r.info("OIDC login successful"),x}catch(m){const g=m instanceof Error?m.message:String(m),C=m instanceof Error?m.stack:String(m);if(r.error(`OIDC login error: ${g}`),i&&k.sendMcpAuthorizationFailedMessage([{...M(u),error:g,error_details:C}]),m.error==="access_denied")return r.info("Access denied"),e.text("Forbidden",403)}const R="Something went wrong";return r.error(`OIDC login error: ${R}`),i&&k.sendMcpAuthorizationFailedMessage([{...M(u),error:R,error_details:null}]),e.text(R,500)}}function Ve(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)||(J(e),G(e)),r.info("Logout successful"),e.newResponse(null,200,{});let u;if(b(i)){const s=(await Z(o,i)).end_session_endpoint;if(s){const p=new URL(e.req.url),R=e.req.header("x-forwarded-proto")||p.protocol.slice(0,-1)||"https",m=e.req.header("x-forwarded-host")||p.host,g=`${R}://${m}`,C=V(g),O=C?Le(JSON.stringify({branch:V(g)})):void 0,I=C?`${Oe(g)}/${ie}/logout`:`${g}${w(D.POST_LOGOUT)}`,a=e.get("cookies"),l=a?.[_.AUTHORIZATION],y=a?.[_.IDP_ID_TOKEN]||(_e(l)?l:void 0);u=Ie(s,I,y,O)}}return r.info("Logout successful"),J(e),G(e),e.newResponse(null,302,{Location:u||w("/")})}}function We(n){return async e=>{const r=n.getConfig().access?.logoutReturnUrl,d=r||w("/");return e.newResponse(null,302,{Location:d})}}function Xe(n){return async e=>{const r=e.get("logger"),d=e.req.param("code"),o=j.BH_API_URL,h=(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 se(`${o}/public-user-invites/${d}`);if(!u.ok)return u.status===404?(r.warn(`Invite ${d} 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",d),p.searchParams.set("org",s.organization.name),p.searchParams.set("invitedBy",h(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:d}),e.text(i.message||"Failed to process invite",400)}}}function Ye(n){return async e=>{const r=e.get("logger"),d=n.getConfig().ssoDirect,o=new URL(e.req.url),h=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 R=o.searchParams.get("redirectTo"),m=Object.keys(d||{})[0];p=p||m;const g=o.searchParams.get("mcp_redirect_uri"),C=!!g;if(!d?.[p]){const c="Invalid idpId";if(r.error(`IdP login error: ${c}`),C){const B=X(R||void 0);k.sendMcpAuthorizationFailedMessage([{...M(B),error:c,error_details:null}])}return e.text(`Forbidden: ${c}`,403)}const I=we({localePrefixParam:o.searchParams.get("localePrefix"),l10n:n.getGlobalData()?.l10n}),a=p&&d?await de(p,d[p]):void 0,l={};for(const c of Object.keys(a?.extraParams||{}))l[c]=o.searchParams.get(c)||a?.extraParams?.[c]||void 0;ae(e)&&(l.prompt="login",l.post_logout="1");let y,t={};if(C&&g&&a&&a.type===ee.OIDC){r.info(`Building MCP OAuth login URL with redirect_uri: ${g}`);const c=Te("",{...a,extraParams:l},R,h,{redirectUriOverride:g,sourceOverride:"mcp",branchOverride:void 0,uiLocales:I});y=c.loginUrl,t=c.cookies||{}}else if(a){const c=ue({...a,extraParams:l},s,R,h,I);y=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:y||new URL(e.req.url).pathname})}}function Qe(n){return async e=>{const r=e.get("logger"),d=await e.req.formData(),o=d.get("SAMLResponse"),h=d.get("RelayState");if(typeof o!="string"||typeof h!="string"){const t="SAMLResponse is required";return r.error(`SAML2 login error: ${t}`),e.text(`Bad request: ${t}`,400)}const i=pe(o),{success:u,uid:s,nameFormat:p,attrs:R,issuerId:m,expiresAt:g}=fe(i),{idpId:C,redirectTo:O}=JSON.parse(h);if(!u){const t="SAML2 assertion is not successful";return r.error(`SAML2 login error: ${t}`),e.text(`Permission denied: ${t}`,401)}if(!g||Math.ceil(Date.now()/1e3)>=g){const t="SAML2 Token Expired";return r.error(`SAML2 login error: ${t}`),e.text(t,401)}const I=n.getConfig().ssoDirect?.[C];if(!I||!le(I)){const t="Cannot find valid IdP";return r.error(`SAML2 login error: ${t}`),e.text(`Permission denied: ${t}`,401)}if(!(I.issuerId&&m&&oe(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 he(i,I.x509PublicCert)){const t="SAMLResponse signature invalid";return r.error(`SAML2 login error: ${t}`),e.text(t,401)}const l=ge(s,p,R,I.teamsAttributeName??re);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 y=await E.sign({...l,idpId:C},U,$.HS256);if(Buffer.byteLength(y)>F){const t=await W({...l},C,"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)}`),y=t.token}return L(e,_.AUTHORIZATION,y,{path:A()||"/",httpOnly:!0,expires:new Date(g*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:O||"/"})}}function xe(n){return async e=>{const r=e.get("logger"),d=new URL(e.req.query("redirectTo")||"/",e.req.url),o=w(z(d.pathname)),h=n.getConfig().ssoDirect,i=Object.entries(h||{}).find(([,O])=>b(O)&&Re(O));if(!(h&&i))return e.newResponse(null,302,{Location:o});const s=e.req.query("token"),p=s&&await Ae(s);if(!p)return e.newResponse(null,302,{Location:o});if(!N(p[H]||[]).some(O=>O===te||O===ne))return e.newResponse(null,302,{Location:o});const g=await E.sign({...p,idpId:i?.at(0)},U,$.HS256),C=Date.now()+K*1e3;return L(e,_.AUTHORIZATION,g,{path:A()||"/",httpOnly:!0,expires:new Date(C),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{Je as authorizeHandler,Ye as idpLoginHandler,Xe as inviteHandler,Ve as logoutHandler,Ze as oidcCallbackHandler,We as postLogoutHandler,Ge as redoclyLoginCallbackHandler,xe as redoclyTokenLoginHandler,Qe as samlCallbackHandler};
|
|
1
|
+
import{setCookie as w,deleteCookie as P}from"hono/cookie";import{AuthProviderType as Q,DEFAULT_TEAM_CLAIM_NAME as x}from"@redocly/config";import{withPathPrefix as y,getPathPrefix as A}from"@redocly/theme/core/utils";import{compareURIs as ee}from"../../../utils/url/compare-uris.js";import{ensureArray as re}from"../../../utils/array/ensure-array.js";import{ALTERNATIVE_AUD_CLAIM_NAME as oe,JWT_SECRET_KEY as U,MAX_AUTH_TOKEN_COOKIE_BYTES as N,ORG_SLUG as te,ORG_ID as ne}from"../../constants/common.js";import{AUTH_SEGMENT as ie,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 L}from"../../telemetry/index.js";import{envConfig as K}from"../../config/env-config.js";import{fetchWithClient as se}from"../../utils/fetch-with-client.js";import{clearAuthCookies as z,clearPostLogoutCookie as v,hasPostLogoutCookie as ae,setPostLogoutCookie as j}from"../../utils/cookie.js";import{getAuthProviderLoginParams as de,isOidcProviderConfig as b,isSaml2ProviderConfig as le,oidcExchangeCodeForToken as ce,buildLoginUrl as ue,decodeSamlResponse as pe,extractUserClaims as ge,parseSamlResponse as fe,parseOidcState as me,verifySAMLResponse as he,getUsernameFromPayload as Ce,buildOidcLogoutUrl as Ie,isIdpIssuedToken as _e,getOidcMetadata as J,getRedoclyTokenPayload as Ae,idTokenAudienceIsAllowed as Re,isRedoclySso as Oe,rewritePreviewAuthRedirectUri as Te,parsePreviewBranch as G,buildOidcLoginUrl as we,createMcpSessionResource as M,signTokenWithinCookieSizeLimit as Z}from"../auth.js";import*as E from"../jwt/jwt.js";import{AlgorithmTypes as $}from"../jwt/types.js";import{handleErrorPageRender as ye}from"../utils.js";import{encodeBase64URL as Le}from"../jwt/encode.js";import{resolveUiLocalesForIdpLogin as Me}from"./helpers/resolve-ui-locales-for-idp-login.js";async function Ge(n){if(K.isProductionEnv)return n.newResponse(null,404,{});const{password:e,...r}=await n.req.json(),d=await E.sign({...r,name:r.username||r.email||"Unknown"},U,$.HS256);return w(n,_.AUTHORIZATION,d,{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 d=`${k.LOGIN}/?error=${encodeURIComponent(r)}`;return n.newResponse(null,301,{Location:d})}}function V(n){if(!n||!n.includes(k.MCP_CALLBACK))return null;try{const e=n.split("/"),r=e[e.length-1];if(r){const d=Buffer.from(r,"base64url").toString("utf-8");return JSON.parse(d).mcpSessionId||null}}catch{}return null}function Ve(n){return async e=>{const r=e.get("logger"),d=n.getConfig().ssoDirect;let o;try{o=me(e.req.query("state"))}catch{return r.warn("OIDC login error: Invalid OAuth2 state"),e.text("Bad request: Invalid OAuth2 state",400)}const h=o.idpId,i=o.source==="mcp"||o.redirectTo&&typeof o.redirectTo=="string"&&o.redirectTo.includes(k.MCP_CALLBACK),u=i?V(typeof o.redirectTo=="string"?o.redirectTo:void 0):null,s=d?.[h];if(!b(s))return r.error("OIDC login error: missing OIDC provider config"),e.text("Forbidden",403);const p=await J(h,s);if(d&&!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"),C=e.req.query("error");if(C)return i&&L.sendMcpAuthorizationFailedMessage([{...M(u),error:`OIDC error: ${C}`,error_details:e.req.query("error_description")||null}]),ye(e,n,{slug:"/"},403,"403OIDC");if(!f){const g="Code is expected but not present";return r.error(`OIDC login error: ${g}`),i&&L.sendMcpAuthorizationFailedMessage([{...M(u),error:g,error_details:null}]),new Response(`Forbidden: ${g}`,{status:403})}const O=typeof o.redirectUri=="string"?o.redirectUri:new URL(y(k.OIDC_CALLBACK),e.req.url).toString(),I=e.get("cookies")?.code_verifier,a=await ce(m,f,O,s,{...s.tokenRequestCustomParams,...I?{code_verifier:I}:{}});if(a.error)return r.error(`Error from OIDC provider: "${a.error}"`),i&&L.sendMcpAuthorizationFailedMessage([{...M(u),error:`Token exchange error: ${a.error}`,error_details:a.error_description||null}]),e.text(`Forbidden: ${a.error_description||a.error}`,403);if(!a?.id_token){const g="No id_token, please, add openid to scopes";return r.error(`OIDC login error: ${g}`),i&&L.sendMcpAuthorizationFailedMessage([{...M(u),error:g,error_details:null}]),new Response(`Forbidden: ${g}`,{status:403})}const{payload:l,header:T}=E.decode(a.id_token),t=T.alg===$.RS256;if(s.audience?.length&&!Re(l,s)){const g="No valid audience found in id_token";return r.error(`OIDC login error: ${g}`),i&&L.sendMcpAuthorizationFailedMessage([{...M(u),error:g,error_details:null}]),new Response(`Forbidden: ${g}`)}let c=t?a.id_token:await E.sign({...l,idpId:h},U,$.HS256);if(Buffer.byteLength(c)>N){const g=await Z(l,h,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&&L.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}Ce(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:a.access_token})});if(g.ok){const q=(await g.json()).ext?.federatedIdentity;q&&(w(e,_.FEDERATED_ACCESS_TOKEN,q.access_token||"",{path:A()||"/",httpOnly:!1,expires:new Date(D)}),w(e,_.FEDERATED_ID_TOKEN,q.id_token||"",{path:A()||"/",httpOnly:!1,expires:new Date(D)}))}else r.warn(`OIDC introspect error: ${g.statusText}`)}if(w(e,_.AUTHORIZATION,c,{path:A()||"/",httpOnly:!0,expires:new Date(D)}),c!==a.id_token&&Buffer.byteLength(a.id_token)<=N?w(e,_.IDP_ID_TOKEN,a.id_token||"",{path:A()||"/",httpOnly:!0,expires:new Date(D)}):P(e,_.IDP_ID_TOKEN,{path:A()||"/"}),w(e,_.IDP_ACCESS_TOKEN,a.access_token||"",{path:A()||"/",httpOnly:!0,expires:new Date(D)}),a.refresh_token?w(e,_.IDP_REFRESH_TOKEN,a.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 W=typeof o.redirectTo=="string"?o.redirectTo:void 0;let X=H(new URL(W||"/",e.req.url).pathname);const Y=e.newResponse(null,302,{Location:X});return r.updateContext({email:l.email,subject:l.sub}),r.info("OIDC login successful"),Y}catch(m){const f=m instanceof Error?m.message:String(m),C=m instanceof Error?m.stack:String(m);if(r.error(`OIDC login error: ${f}`),i&&L.sendMcpAuthorizationFailedMessage([{...M(u),error:f,error_details:C}]),m.error==="access_denied")return r.info("Access denied"),e.text("Forbidden",403)}const R="Something went wrong";return r.error(`OIDC login error: ${R}`),i&&L.sendMcpAuthorizationFailedMessage([{...M(u),error:R,error_details:null}]),e.text(R,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),R=e.req.header("x-forwarded-proto")||p.protocol.slice(0,-1)||"https",m=e.req.header("x-forwarded-host")||p.host,f=`${R}://${m}`,C=G(f),O=C?Le(JSON.stringify({branch:G(f)})):void 0,I=C?`${Te(f)}/${ie}/logout`:`${f}${y(k.POST_LOGOUT)}`,a=e.get("cookies"),l=a?.[_.AUTHORIZATION],T=a?.[_.IDP_ID_TOKEN]||(_e(l)?l:void 0);u=Ie(s,I,T,O)}}return r.info("Logout successful"),z(e),j(e),e.newResponse(null,302,{Location:u||y("/")})}}function Xe(n){return async e=>{const r=n.getConfig().access?.logoutReturnUrl,d=r||y("/");return e.newResponse(null,302,{Location:d})}}function Ye(n){return async e=>{const r=e.get("logger"),d=e.req.param("code"),o=K.BH_API_URL,h=(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(y("/"));const u=await se(`${o}/public-user-invites/${d}`);if(!u.ok)return u.status===404?(r.warn(`Invite ${d} not found redirect to homepage`),e.redirect(y("/"))):(r.error("Invite error",await u.text()),e.redirect(y("/")));const s=await u.json(),p=new URL(y("/invite"),e.req.url);return p.searchParams.set("code",d),p.searchParams.set("org",s.organization.name),p.searchParams.set("invitedBy",h(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:d}),e.text(i.message||"Failed to process invite",400)}}}function Qe(n){return async e=>{const r=e.get("logger"),d=n.getConfig().ssoDirect,o=new URL(e.req.url),h=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 R=o.searchParams.get("redirectTo"),m=Object.keys(d||{})[0];p=p||m;const f=o.searchParams.get("mcp_redirect_uri"),C=!!f;if(!d?.[p]){const c="Invalid idpId";if(r.error(`IdP login error: ${c}`),C){const F=V(R||void 0);L.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}),a=p&&d?await de(p,d[p]):void 0,l={};for(const c of Object.keys(a?.extraParams||{}))l[c]=o.searchParams.get(c)||a?.extraParams?.[c]||void 0;ae(e)&&(l.prompt="login",l.post_logout="1");let T,t={};if(C&&f&&a&&a.type===Q.OIDC){r.info(`Building MCP OAuth login URL with redirect_uri: ${f}`);const c=we("",{...a,extraParams:l},R,h,{redirectUriOverride:f,sourceOverride:"mcp",branchOverride:void 0,uiLocales:I});T=c.loginUrl,t=c.cookies||{}}else if(a){const c=ue({...a,extraParams:l},s,R,h,I);T=c.loginUrl,t=c.cookies||{}}return Object.keys(t).forEach(c=>{w(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"),d=await e.req.formData(),o=d.get("SAMLResponse"),h=d.get("RelayState");if(typeof o!="string"||typeof h!="string"){const t="SAMLResponse is required";return r.error(`SAML2 login error: ${t}`),e.text(`Bad request: ${t}`,400)}const i=pe(o),{success:u,uid:s,nameFormat:p,attrs:R,issuerId:m,expiresAt:f}=fe(i),{idpId:C,redirectTo:O}=JSON.parse(h);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?.[C];if(!I||!le(I)){const t="Cannot find valid IdP";return r.error(`SAML2 login error: ${t}`),e.text(`Permission denied: ${t}`,401)}if(!(I.issuerId&&m&&ee(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 he(i,I.x509PublicCert)){const t="SAMLResponse signature invalid";return r.error(`SAML2 login error: ${t}`),e.text(t,401)}const l=ge(s,p,R,I.teamsAttributeName??x);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 E.sign({...l,idpId:C},U,$.HS256);if(Buffer.byteLength(T)>N){const t=await Z({...l},C,"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 w(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:O||"/"})}}function er(n){return async e=>{const r=e.get("logger"),d=new URL(e.req.query("redirectTo")||"/",e.req.url),o=y(H(d.pathname)),h=n.getConfig().ssoDirect,i=Object.entries(h||{}).find(([,O])=>b(O)&&Oe(O));if(!(h&&i))return e.newResponse(null,302,{Location:o});const s=e.req.query("token"),p=s&&await Ae(s);if(!p)return e.newResponse(null,302,{Location:o});if(!re(p[oe]||[]).some(O=>O===te||O===ne))return e.newResponse(null,302,{Location:o});const f=await E.sign({...p,idpId:i?.at(0)},U,$.HS256),C=Date.now()+B*1e3;return w(e,_.AUTHORIZATION,f,{path:A()||"/",httpOnly:!0,expires:new Date(C),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 +1 @@
|
|
|
1
|
-
import m from"path";import{REDOCLY_ROUTE_RBAC as
|
|
1
|
+
import m from"path";import{realpath as N}from"fs/promises";import{REDOCLY_ROUTE_RBAC as Y,REDOCLY_TEAMS_RBAC as z}from"@redocly/config";import{combineUrls as $,withoutPathPrefix as ne,withPathPrefix as T}from"@redocly/theme/core/utils";import{CACHE_CONTROL_NO_STORE_HEADER_VALUE as k,CACHE_CONTROL_PUBLIC_HTML as oe,DEFAULT_IMMUTABLE_CACHE_MAX_AGE as re,STATIC_DATA_FOLDER as ie,X_REDOCLY_CACHE_CONTROL_HEADER as ae,X_REDOCLY_CACHE_CONTROL_PUBLIC_HTML as se}from"../../constants/common.js";import{removeTrailingSlash as ce}from"../../../utils/url/remove-trailing-slash.js";import{findInIterable as le}from"../../../utils/collection/find-in-iterable.js";import{sanitizeRedirectPathname as me}from"../../../utils/url/sanitize-redirect-pathname.js";import{envConfig as ue}from"../../config/env-config.js";import{sanitizePath as de}from"../../../utils/path/sanitize-path.js";import{normalizeRouteSlug as fe}from"../../../utils/path/normalize-route-slug.js";import{isPathInFolder as G}from"../../../utils/path/is-path-in-folder.js";import{getLlmsTxtMdPathBySlug as ge}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 pe}from"../../../utils/url/remove-leading-slash.js";import{AI_INDEX_EXPORT_FOLDER as he,SEARCH_DATA_EXPORT_FOLDER as Re}from"../../constants/plugins/search.js";import{processRedirects as Ce}from"./helpers/process-redirects.js";import{renderPage as Ae,getServerProps as Ee}from"../../ssr/index.js";import{canAccessAsset as Le,canAccessResource as V}from"../../utils/rbac.js";import{handleErrorPageRender as w,handleUnauthorized as W,handleUnauthorizedAsset as Z}from"../utils.js";import{DEFAULT_MAX_AGE_FOR_MIME_TYPE as _e,MIME_TYPES as Te}from"../mime-types.js";import{fileExistsAsync as we}from"../../utils/index.js";import{isAiAgentRequest as Oe}from"../../utils/ai-agent-detection.js";import{getRedirectRoute as Pe}from"../utils/legacy-openapi-redirects.js";import{getContentTypeHeaderValue as x}from"../utils/content-type.js";import{telemetry as ye}from"../../../cli/telemetry/index.js";import{telemetry as Ue}from"../../telemetry/index.js";const Me=[Re,he,ie];async function be(e,p){if(m.extname(e)===".md")return!1;try{const[h,u]=await Promise.all([N(e),N(p)]);return Me.some(t=>G(h,m.join(u,t)))}catch{return!1}}function at(e,p,h,u){return async t=>{const O=t.get("logger"),r=t.req,c=new URL(r.url),i=ne(de(decodeURIComponent(c.pathname))),P=m.parse(i).ext===".md",y=Oe({accept:r.header("accept"),signatureAgent:r.header("signature-agent"),signature:r.header("signature"),signatureInput:r.header("signature-input"),userAgent:r.header("user-agent")}),a=fe(i),o=(r.method==="GET"||r.method==="HEAD")&&!P?e.getRouteBySlug(a,{followRedirect:!1})||le(e.routesBySlug?.values(),n=>n.hasClientRoutes&&(i===n.slug||i.startsWith(n.slug+"/"))):void 0,U=e.getRedirect(a);if(U){const n=Ce({redirect:U,reqUrlSearch:c.search});return Ue.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})}const R=ue.isProductionEnv?301:302;if(o?.metadata?.type==="openapi"){const n=Pe(c.pathname);if(n)return O.info("Legacy OpenAPI docs redirect from "+c.pathname),t.newResponse(null,R,{Location:encodeURI(n)});if(c.pathname.match(/[A-Z]/))return O.warn("Redirect to lowercase route to avoid 404 error"),t.newResponse(null,R,{Location:encodeURI(c.pathname.toLowerCase())})}if(i.endsWith("/")&&i!=="/"){const n=me(new URL(a||"/",t.req.url).pathname);return t.newResponse(null,R,{Location:encodeURI(T((n==="/"?"/":ce(n))+c.search))})}const{isAuthenticated:d,teams:C,claims:{email:A}}=t.get("auth");if(o&&!V(o,{isAuthenticated:d,email:A,teams:C},e.config.access?.rbac,e.config.access?.requiresLogin))return d?w(t,e,{slug:o.slug,[z]:o[z],[Y]:o[Y]},403):W(t,e,o.slug);const f=o&&y?ge(o.slug):void 0,M=f?await j(f,e,u):void 0,b=M?.exists??!1;if(o&&(!y||!b)){const n=await p(o),K=await Ee(o,t,n,e),{html:Q,statusCode:q,error:ee}=await Ae(o,K,t,e,ye),v=e.config.access?.rbac,B=!e.config.access?.requiresLogin&&(!v||!Object.keys(v).length),X=q>=400||!!ee||!!e.compilationErrors?.length,te=B&&!X;let g;return X?g=k:B?g=oe:g="private",t.html(Q,q,{"Cache-Control":g,...te&&{[ae]:se}})}const E=f&&b?f:i,J=pe(E),s=m.resolve(e.outdir,J);if(!G(s,e.outdir))return Z(t);if(await be(s,e.outdir))return w(t,e,{slug:a},404);let l,D;if(P){const n=await j(i,e,u);if(l=n.route,D=n.content,l&&!V(l,{isAuthenticated:d,email:A,teams:C},e.config.access?.rbac,e.config.access?.requiresLogin))return W(t,e,i)}const I=e.getGlobalConfig("access");if(!Le(E,I?.rbac||{},I?.requiresLogin||!1,e.getGlobalConfig("directoryPaths"),{isAuthenticated:d,email:A,teams:C}))return Z(t);const L=Te[m.extname(s)]||"text/plain",_=s.match(/assets\/.*\.[a-f0-9]{8,}\..+/)||s.match(/runtime\/chunks\/.*/)?re:_e[L],S=_?{"Cache-Control":`public, max-age=${_}, immutable`,Expires:new Date(Date.now()+_*1e3).toUTCString()}:{"Cache-Control":k},F=r.query("download")!=null,H=M?.content??D;if(H!==void 0)return t.newResponse(H,200,{"Content-Type":x(L),"Access-Control-Allow-Origin":"*",...S,...l&&{"X-Robots-Tag":"noindex, follow",...e.config.seo?.siteUrl&&{Link:`<${$(e.config.seo.siteUrl,T(l.slug))}>; rel="canonical"`}},...F&&{"Content-Disposition":`attachment; filename="${m.basename(E)}"`}});if(await we(s)){const n=await h(s);return t.newResponse(n,200,{"Content-Type":x(L),"Access-Control-Allow-Origin":"*",...S,...l&&{"X-Robots-Tag":"noindex, follow",...e.config.seo?.siteUrl&&{Link:`<${$(e.config.seo.siteUrl,T(l.slug))}>; rel="canonical"`}},...F&&{"Content-Disposition":`attachment; filename="${m.basename(s)}"`}})}else return w(t,e,{slug:a},404)}}export{at as dynamicRouteHandler};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{getCookie as A}from"hono/cookie";import{createHash as J,timingSafeEqual as K}from"node:crypto";import{ulid as V}from"ulid";import{isRedoclySso as Y,isOidcProviderConfig as P,createMcpAuthorizationCode as Z,verifyMcpAuthorizationCode as W,createMcpRefreshToken as $,verifyMcpRefreshToken as x,createMcpSessionResource as y,oidcJwksCache as j,oidcRefreshTokenGrant as Q,getOidcMetadata as X,discoverJwks as ee}from"../../auth.js";import{isMcpContentProtected as v}from"../../../plugins/mcp/auth/auth-handlers.js";import{SUPPORTED_MCP_SCOPES as M}from"../../../plugins/mcp/constants.js";import{AUTH_URL as re,JWT_SECRET_KEY as m,MCP_ACCESS_TOKEN_TTL_SEC as z,MCP_REFRESH_SESSION_LIFETIME_SEC as te}from"../../../constants/common.js";import{ServerRoutes as T}from"../../../../constants/api.js";import{AuthCookieNames as R}from"../../../../constants/common.js";import{withPathPrefix as I}from"@redocly/theme/core/utils";import{telemetry as w}from"../../../telemetry/index.js";import{envConfig as U}from"../../../config/env-config.js";import*as S from"../../jwt/jwt.js";import{AlgorithmTypes as D,JwtAlgorithmNotImplemented as ne,JwtTokenExpired as oe,JwtTokenInvalid as ie,JwtTokenNotBefore as se,JwtTokenSignatureMismatched as ce}from"../../jwt/types.js";import{getRequestOrigin as q}from"../../utils/get-request-origin.js";import{encryptClaimValue as L}from"../../../utils/crypto/encrypt-claim-value.js";import{decryptAesGcm as de}from"../../../utils/crypto/decrypt-aes-gcm.js";import{encryptAesGcm as F}from"../../../utils/crypto/encrypt-aes-gcm.js";import{fetchClientMetadataDocument as ae,isClientMetadataDocumentUrl as N,isRedirectUriRegistered as le}from"./mcp-client-metadata.js";const s=(r,e,t=200,o)=>r.json(e,t,{"Content-Type":"application/json",...o??{}}),H=new Set(["S256"]),b=["authorization_code","refresh_token"],pe="https://claude.ai/oauth/claude-code-client-metadata";function _e(r,e,t){if(!H.has(e||""))return!1;const o=J("sha256").update(t).digest("base64url"),c=Buffer.from(o),i=Buffer.from(r);return c.length!==i.length?!1:K(c,i)}async function ue(r){const e=Math.floor(Date.now()/1e3);return S.sign({type:"mcp_context",...r,iat:e,exp:e+600},m,D.HS256)}async function fe(r){await S.verify(r,m,D.HS256);const{payload:e}=S.decode(r);if(e.type!=="mcp_context")throw new Error("Invalid context token type");return e}function Ne(r){return async e=>{if(!v(r))return s(e,{error:"not_found"},404);if(e.req.method!=="GET")return s(e,{error:"Method not allowed"},405,{Allow:"GET"});const t=q(e);return s(e,{resource:`${t}${I("/mcp")}`,authorization_servers:[t],bearer_methods_supported:["header"],resource_documentation:`${t}${T.MCP_OAUTH_AUTHORIZATION_SERVER}`,scopes_supported:[...M],bearer_token_types_supported:["Bearer"]},200,{"Access-Control-Allow-Origin":"*"})}}function He(r){return async e=>{if(!v(r))return s(e,{error:"not_found"},404);const t=q(e);return s(e,{issuer:t,authorization_endpoint:`${t}${I(T.MCP_AUTHORIZATION)}`,token_endpoint:`${t}${I(T.MCP_TOKEN_PORTAL)}`,scopes_supported:[...M],registration_endpoint:`${t}${I(T.MCP_DYNAMIC_CLIENT_REGISTRATION)}`,response_types_supported:["code"],grant_types_supported:[...b],subject_types_supported:["public"],id_token_signing_alg_values_supported:["RS256"],code_challenge_methods_supported:["S256"],token_endpoint_auth_methods_supported:["none"],client_id_metadata_document_supported:!0},200,{"Access-Control-Allow-Origin":"*"})}}function be(r){return async e=>{if(!v(r))return s(e,{error:"not_found"},404);if(e.req.method!=="POST")return s(e,{error:"Method not allowed"},405);try{return s(e,{client_id:U.OAUTH_CLIENT_ID||"",client_name:"MCP Client",redirect_uris:[],grant_types:[...b],response_types:["code"],scope:M.join(" "),subject_type:"public",token_endpoint_auth_method:"none",created_at:new Date().toISOString(),updated_at:new Date().toISOString()},201,{"Access-Control-Allow-Origin":"*"})}catch(t){return s(e,{error:"invalid_request",error_description:t?.message||"Unable to register client"},500,{"Access-Control-Allow-Origin":"*"})}}}function G(r){const e=r||{},t=Object.keys(e),o=t.find(i=>P(e[i])&&Y(e[i])),c=t.find(i=>P(e[i]));return o||c||t[0]}function $e(r){return async e=>{if(!v(r))return s(e,{error:"not_found"},404);const t=new URL(e.req.url),{searchParams:o}=t,c=o.get("redirect_uri"),i=o.get("client_id"),a=o.get("code_challenge"),n=o.get("code_challenge_method"),l=V();if(a&&!H.has(n||""))return s(e,{error:"invalid_request",error_description:`Unsupported code_challenge_method. Supported: ${[...H].join(", ")}`},400);if(N(i)&&!a)return s(e,{error:"invalid_request",error_description:"code_challenge is required for client_id_metadata_document clients"},400);if(N(i)&&c)try{const d=await ae(i),p=i===pe;if(!le(c,d.redirect_uris,{ignorePort:p}))return s(e,{error:"invalid_request",error_description:"redirect_uri is not registered for this client"},400)}catch(d){const p=d instanceof Error?d.message:String(d);return s(e,{error:"invalid_client",error_description:`Unable to resolve client metadata document: ${p}`},400)}w.sendMcpAuthorizationStartedMessage([{...y(l),redirect_uri:c||null}]);const f=q(e),_={isMcpFlow:!0,originalRedirectUri:c,mcpClientId:i,mcpState:o.get("state"),mcpSessionId:l,mcpCodeChallenge:a,mcpCodeChallengeMethod:a?n:null,timestamp:Date.now()};try{const d=await ue(_),p=new URL(I(T.IDP_LOGIN),f);p.searchParams.set("redirectTo",`${T.MCP_CALLBACK}/${d}`);const k=G(r.getConfig().ssoDirect);return k?(p.searchParams.set("idpId",k),e.redirect(p.toString())):s(e,{error:"not_found"},404)}catch(d){const p=d instanceof Error?d.message:String(d),k=d instanceof Error?d.stack:String(d);w.sendMcpAuthorizationFailedMessage([{...y(l),error:p,error_details:k}]);const C=new URL(I(`${re}/oauth2/auth`));return C.search=o.toString(),e.redirect(C.toString())}}}async function B(r){const e=Math.floor(Date.now()/1e3),t=await S.sign({...r.claims,...r.idpId?{idpId:r.idpId}:{},...r.idpAccessTokenEnc?{idp_access_token:r.idpAccessTokenEnc}:{},...r.ttlSec?{iat:e,exp:e+r.ttlSec}:{}},m,D.HS256,r.kid),o=r.ttlSec??(typeof r.claims.exp=="number"?Math.max(r.claims.exp-e,0):z);return{accessToken:t,expiresIn:o}}async function he(r,e,t){const o=g=>s(r,{error:"invalid_grant",error_description:g},400),c=r.get("logger"),i=t.get("refresh_token"),a=t.get("client_id")||void 0;if(!i)return s(r,{error:"invalid_request",error_description:"refresh_token is required"},400);let n;try{n=await x(i)}catch(g){return c?.warn("MCP refresh token rejected: %s",g instanceof Error?g.message:String(g)),o("Invalid refresh token")}if(a&&a!==n.client_id)return o("Client mismatch");const l=n.idp_id?e.getConfig().ssoDirect?.[n.idp_id]:void 0;let f,_,d=n.idp_access_token_enc,p=n.idp_refresh_token_enc;if(n.idp_refresh_token_enc){let g;try{g=de(n.idp_refresh_token_enc,m)}catch{return o("Invalid refresh token")}if(!n.idp_id||!P(l))return o("Unknown identity provider");let u;try{const h=await X(n.idp_id,l);if(!h?.token_endpoint)return o("Identity provider has no token endpoint");u=await Q(h.token_endpoint,g,l)}catch(h){return c?.warn("MCP refresh failed to reach the IdP token endpoint: %s",h instanceof Error?h.message:String(h)),s(r,{error:"server_error",error_description:"Failed to refresh session"},500)}if(u.error||!(u.id_token||u.access_token))return c?.warn("MCP refresh rejected by IdP: %s",u.error||"empty token response"),o("Refresh rejected by identity provider");if(u.refresh_token&&(p=F(u.refresh_token,m)),u.access_token&&(d=L(u.access_token,m)),u.id_token)try{const h=S.decode(u.id_token);f=h.payload,_=h.header.kid}catch{return o("Invalid token response from identity provider")}}const k=P(l)&&l.tokenExpirationTime||z,C=f??n.claims,E=await B({claims:C,kid:_,idpId:n.idp_id,idpAccessTokenEnc:d,ttlSec:f?void 0:k}),O=await $({clientId:n.client_id,idpId:n.idp_id,claims:C,idpAccessTokenEnc:d,idpRefreshTokenEnc:p,sessionExp:n.session_exp});return s(r,{access_token:E.accessToken,token_type:"Bearer",expires_in:E.expiresIn,refresh_token:O,scope:M.join(" ")},200,{"Cache-Control":"no-store",Pragma:"no-cache"})}function je(r){return async e=>{if(e.req.method!=="POST")return s(e,{error:"Method not allowed"},405);try{const t=await e.req.formData(),o=t.get("grant_type"),c=t.get("code"),i=t.get("redirect_uri")||void 0,a=t.get("code_verifier")||void 0;if(!b.includes(o))return s(e,{error:"invalid_request",error_description:"Invalid grant type"},400);if(o==="refresh_token")return await he(e,r,t);if(!c)return s(e,{error:"invalid_request",error_description:"Missing authorization code"},400);try{const n=await W(c);if(i&&i!==n.redirect_uri)return s(e,{error:"invalid_grant",error_description:"redirect_uri mismatch"},400);if(n.code_challenge){if(!a)return s(e,{error:"invalid_grant",error_description:"code_verifier required"},400);if(!_e(n.code_challenge,n.code_challenge_method,a))return s(e,{error:"invalid_grant",error_description:"code_verifier mismatch"},400)}if(U.OAUTH_CLIENT_ID&&n.client_id&&!N(n.client_id)&&n.client_id!==U.OAUTH_CLIENT_ID)return s(e,{error:"invalid_client",error_description:"Client mismatch"},400);const l=n.id_token;if(typeof l!="string"||l.length===0)return s(e,{error:"invalid_grant",error_description:"Missing id_token in authorization code"},400);const f=n.idp_access_token_enc??(n.idp_access_token?L(n.idp_access_token,m):void 0),_=S.decode(l),{accessToken:d,expiresIn:p}=await B({claims:_.payload,kid:_.header.kid,idpId:n.idp_id,idpAccessTokenEnc:f}),C=Math.floor(Date.now()/1e3)+te,E=await $({clientId:n.client_id,idpId:n.idp_id,claims:_.payload,idpAccessTokenEnc:f,idpRefreshTokenEnc:n.idp_refresh_token_enc,sessionExp:C}),O={access_token:d,token_type:"Bearer",expires_in:p,refresh_token:E,scope:M.join(" "),id_token:l};return s(e,O,200,{"Cache-Control":"no-store",Pragma:"no-cache"})}catch(n){return e.get("logger")?.warn("MCP token exchange failed: %s",n instanceof Error?n.message:String(n)),s(e,{error:"invalid_grant",error_description:"Invalid authorization code"},400)}}catch(t){const o=t instanceof Error?t.message:String(t);return s(e,{error:"server_error",error_description:"Failed to process token request",error_details:o},500)}}}async function me(r,e){try{const{payload:t,header:o}=S.decode(r);if(typeof t.idpId=="string"&&t.idpId)return t.idpId;if(o.kid){j.jwks[o.kid]==null&&await ee(e||{});const c=j.jwks[o.kid];if(c?.idpId)return c.idpId}}catch{}return G(e)}function ze(r){return async e=>{const t=new URL(e.req.url);let o=t.searchParams.get("context");if(!o&&t.pathname.startsWith(I(`${T.MCP_CALLBACK}/`))){const i=t.pathname.split("/");o=i[i.length-1]}if(!o)return e.text("Missing context parameter",400);let c=null;try{const i=await fe(o);if(c=i.mcpSessionId||null,!i.isMcpFlow||!i.originalRedirectUri)throw new Error("Invalid MCP context");const a=A(e,R.IDP_ID_TOKEN)||A(e,R.AUTHORIZATION),n=A(e,R.IDP_ACCESS_TOKEN),l=A(e,R.IDP_REFRESH_TOKEN);if(!a)return w.sendMcpAuthorizationFailedMessage([{...y(c),error:"Authentication required",error_details:null}]),e.text("Authentication required",401);const f=await Z({idToken:a,idpId:await me(a,r.getConfig().ssoDirect),idpAccessTokenEnc:n?L(n,m):void 0,idpRefreshTokenEnc:l?F(l,m):void 0,clientId:i.mcpClientId||"",redirectUri:i.originalRedirectUri,codeChallenge:i.mcpCodeChallenge||void 0,codeChallengeMethod:i.mcpCodeChallengeMethod||void 0,ttlSec:600}),_=new URL(i.originalRedirectUri);return _.searchParams.set("code",f),i.mcpState&&_.searchParams.set("state",i.mcpState),w.sendMcpAuthorizationCompletedMessage([{...y(c),redirect_uri:i.originalRedirectUri||null}]),e.redirect(_.toString())}catch(i){const a=ge(i);return w.sendMcpAuthorizationFailedMessage([{...y(c),...a}]),e.text(`Invalid MCP callback: ${a.error}`,400)}}}function ge(r){return r instanceof Error&&[ne,oe,ie,se,ce].some(e=>r instanceof e)?{error:r.name,error_details:null}:r instanceof Error?{error:r.message,error_details:r.stack??null}:{error:String(r),error_details:null}}export{b as SUPPORTED_MCP_GRANT_TYPES,ue as createMcpContextToken,$e as mcpAuthorizationHandler,ze as mcpCallbackHandler,be as mcpDynamicClientRegistrationHandler,He as mcpOAuthAuthorizationServerHandler,Ne as mcpOAuthProtectedResourceHandler,je as mcpTokenPortalHandler,G as resolveMcpIdpId,fe as verifyAndParseMcpContextToken,_e as verifyPkce};
|
|
1
|
+
import{getCookie as U}from"hono/cookie";import{createHash as V,timingSafeEqual as Z}from"node:crypto";import{ulid as Y}from"ulid";import{isRedoclySso as W,isOidcProviderConfig as w,createMcpAuthorizationCode as X,verifyMcpAuthorizationCode as Q,createMcpRefreshToken as z,verifyMcpRefreshToken as x,createMcpSessionResource as S,oidcRefreshTokenGrant as ee,getOidcMetadata as re,getUserParamsFromCookies as te}from"../../auth.js";import{isMcpContentProtected as P}from"../../../plugins/mcp/auth/auth-handlers.js";import{SUPPORTED_MCP_SCOPES as y}from"../../../plugins/mcp/constants.js";import{AUTH_URL as ne,JWT_SECRET_KEY as m,MCP_ACCESS_TOKEN_TTL_SEC as j,MCP_REFRESH_SESSION_LIFETIME_SEC as oe}from"../../../constants/common.js";import{ServerRoutes as T}from"../../../../constants/api.js";import{AuthCookieNames as v}from"../../../../constants/common.js";import{withPathPrefix as I}from"@redocly/theme/core/utils";import{telemetry as A}from"../../../telemetry/index.js";import{envConfig as D}from"../../../config/env-config.js";import*as M from"../../jwt/jwt.js";import{InternalTokenTypes as F,McpAccessTokenMarker as R}from"../../jwt/token-types.js";import{AlgorithmTypes as L,JwtAlgorithmNotImplemented as ie,JwtTokenExpired as se,JwtTokenInvalid as ce,JwtTokenNotBefore as de,JwtTokenSignatureMismatched as ae}from"../../jwt/types.js";import{getRequestOrigin as N}from"../../utils/get-request-origin.js";import{encryptClaimValue as q}from"../../../utils/crypto/encrypt-claim-value.js";import{decryptAesGcm as le}from"../../../utils/crypto/decrypt-aes-gcm.js";import{encryptAesGcm as G}from"../../../utils/crypto/encrypt-aes-gcm.js";import{fetchClientMetadataDocument as pe,isClientMetadataDocumentUrl as H,isRedirectUriRegistered as _e}from"./mcp-client-metadata.js";const s=(r,e,t=200,i)=>r.json(e,t,{"Content-Type":"application/json",...i??{}}),b=new Set(["S256"]),$=["authorization_code","refresh_token"],ue="https://claude.ai/oauth/claude-code-client-metadata";function fe(r,e,t){if(!b.has(e||""))return!1;const i=V("sha256").update(t).digest("base64url"),c=Buffer.from(i),o=Buffer.from(r);return c.length!==o.length?!1:Z(c,o)}async function he(r){const e=Math.floor(Date.now()/1e3);return M.sign({type:F.MCP_CONTEXT,...r,iat:e,exp:e+600},m,L.HS256)}async function me(r){await M.verify(r,m,L.HS256);const{payload:e}=M.decode(r);if(e.type!==F.MCP_CONTEXT)throw new Error("Invalid context token type");return e}function be(r){return async e=>{if(!P(r))return s(e,{error:"not_found"},404);if(e.req.method!=="GET")return s(e,{error:"Method not allowed"},405,{Allow:"GET"});const t=N(e);return s(e,{resource:`${t}${I("/mcp")}`,authorization_servers:[t],bearer_methods_supported:["header"],resource_documentation:`${t}${T.MCP_OAUTH_AUTHORIZATION_SERVER}`,scopes_supported:[...y],bearer_token_types_supported:["Bearer"]},200,{"Access-Control-Allow-Origin":"*"})}}function $e(r){return async e=>{if(!P(r))return s(e,{error:"not_found"},404);const t=N(e);return s(e,{issuer:t,authorization_endpoint:`${t}${I(T.MCP_AUTHORIZATION)}`,token_endpoint:`${t}${I(T.MCP_TOKEN_PORTAL)}`,scopes_supported:[...y],registration_endpoint:`${t}${I(T.MCP_DYNAMIC_CLIENT_REGISTRATION)}`,response_types_supported:["code"],grant_types_supported:[...$],subject_types_supported:["public"],id_token_signing_alg_values_supported:["RS256"],code_challenge_methods_supported:["S256"],token_endpoint_auth_methods_supported:["none"],client_id_metadata_document_supported:!0},200,{"Access-Control-Allow-Origin":"*"})}}function ze(r){return async e=>{if(!P(r))return s(e,{error:"not_found"},404);if(e.req.method!=="POST")return s(e,{error:"Method not allowed"},405);try{return s(e,{client_id:D.OAUTH_CLIENT_ID||"",client_name:"MCP Client",redirect_uris:[],grant_types:[...$],response_types:["code"],scope:y.join(" "),subject_type:"public",token_endpoint_auth_method:"none",created_at:new Date().toISOString(),updated_at:new Date().toISOString()},201,{"Access-Control-Allow-Origin":"*"})}catch(t){return s(e,{error:"invalid_request",error_description:t?.message||"Unable to register client"},500,{"Access-Control-Allow-Origin":"*"})}}}function B(r){const e=r||{},t=Object.keys(e),i=t.find(o=>w(e[o])&&W(e[o])),c=t.find(o=>w(e[o]));return i||c||t[0]}function je(r){return async e=>{if(!P(r))return s(e,{error:"not_found"},404);const t=new URL(e.req.url),{searchParams:i}=t,c=i.get("redirect_uri"),o=i.get("client_id"),l=i.get("code_challenge"),n=i.get("code_challenge_method"),p=Y();if(l&&!b.has(n||""))return s(e,{error:"invalid_request",error_description:`Unsupported code_challenge_method. Supported: ${[...b].join(", ")}`},400);if(H(o)&&!l)return s(e,{error:"invalid_request",error_description:"code_challenge is required for client_id_metadata_document clients"},400);if(H(o)&&c)try{const d=await pe(o),a=o===ue;if(!_e(c,d.redirect_uris,{ignorePort:a}))return s(e,{error:"invalid_request",error_description:"redirect_uri is not registered for this client"},400)}catch(d){const a=d instanceof Error?d.message:String(d);return s(e,{error:"invalid_client",error_description:`Unable to resolve client metadata document: ${a}`},400)}A.sendMcpAuthorizationStartedMessage([{...S(p),redirect_uri:c||null}]);const _=N(e),f={isMcpFlow:!0,originalRedirectUri:c,mcpClientId:o,mcpState:i.get("state"),mcpSessionId:p,mcpCodeChallenge:l,mcpCodeChallengeMethod:l?n:null,timestamp:Date.now()};try{const d=await he(f),a=new URL(I(T.IDP_LOGIN),_);a.searchParams.set("redirectTo",`${T.MCP_CALLBACK}/${d}`);const k=B(r.getConfig().ssoDirect);return k?(a.searchParams.set("idpId",k),e.redirect(a.toString())):s(e,{error:"not_found"},404)}catch(d){const a=d instanceof Error?d.message:String(d),k=d instanceof Error?d.stack:String(d);A.sendMcpAuthorizationFailedMessage([{...S(p),error:a,error_details:k}]);const C=new URL(I(`${ne}/oauth2/auth`));return C.search=i.toString(),e.redirect(C.toString())}}}async function K(r){const e=Math.floor(Date.now()/1e3),t=await M.sign({...r.claims,[R.CLAIM]:R.VALUE,...r.idpId?{idpId:r.idpId}:{},...r.idpAccessTokenEnc?{idp_access_token:r.idpAccessTokenEnc}:{},...r.ttlSec?{iat:e,exp:e+r.ttlSec}:{}},m,L.HS256,r.kid),i=r.ttlSec??(typeof r.claims.exp=="number"?Math.max(r.claims.exp-e,0):j);return{accessToken:t,expiresIn:i}}async function ge(r,e,t){const i=g=>s(r,{error:"invalid_grant",error_description:g},400),c=r.get("logger"),o=t.get("refresh_token"),l=t.get("client_id")||void 0;if(!o)return s(r,{error:"invalid_request",error_description:"refresh_token is required"},400);let n;try{n=await x(o)}catch(g){return c?.warn("MCP refresh token rejected: %s",g instanceof Error?g.message:String(g)),i("Invalid refresh token")}if(l&&l!==n.client_id)return i("Client mismatch");const p=n.idp_id?e.getConfig().ssoDirect?.[n.idp_id]:void 0;let _,f,d=n.idp_access_token_enc,a=n.idp_refresh_token_enc;if(n.idp_refresh_token_enc){let g;try{g=le(n.idp_refresh_token_enc,m)}catch{return i("Invalid refresh token")}if(!n.idp_id||!w(p))return i("Unknown identity provider");let u;try{const h=await re(n.idp_id,p);if(!h?.token_endpoint)return i("Identity provider has no token endpoint");u=await ee(h.token_endpoint,g,p)}catch(h){return c?.warn("MCP refresh failed to reach the IdP token endpoint: %s",h instanceof Error?h.message:String(h)),s(r,{error:"server_error",error_description:"Failed to refresh session"},500)}if(u.error||!(u.id_token||u.access_token))return c?.warn("MCP refresh rejected by IdP: %s",u.error||"empty token response"),i("Refresh rejected by identity provider");if(u.refresh_token&&(a=G(u.refresh_token,m)),u.access_token&&(d=q(u.access_token,m)),u.id_token)try{const h=M.decode(u.id_token);_=h.payload,f=h.header.kid}catch{return i("Invalid token response from identity provider")}}const k=w(p)&&p.tokenExpirationTime||j,C=_??n.claims,E=await K({claims:C,kid:f,idpId:n.idp_id,idpAccessTokenEnc:d,ttlSec:_?void 0:k}),O=await z({clientId:n.client_id,idpId:n.idp_id,claims:C,idpAccessTokenEnc:d,idpRefreshTokenEnc:a,sessionExp:n.session_exp});return s(r,{access_token:E.accessToken,token_type:"Bearer",expires_in:E.expiresIn,refresh_token:O,scope:y.join(" ")},200,{"Cache-Control":"no-store",Pragma:"no-cache"})}function Fe(r){return async e=>{if(e.req.method!=="POST")return s(e,{error:"Method not allowed"},405);try{const t=await e.req.formData(),i=t.get("grant_type"),c=t.get("code"),o=t.get("redirect_uri")||void 0,l=t.get("code_verifier")||void 0;if(!$.includes(i))return s(e,{error:"invalid_request",error_description:"Invalid grant type"},400);if(i==="refresh_token")return await ge(e,r,t);if(!c)return s(e,{error:"invalid_request",error_description:"Missing authorization code"},400);try{const n=await Q(c);if(o&&o!==n.redirect_uri)return s(e,{error:"invalid_grant",error_description:"redirect_uri mismatch"},400);if(n.code_challenge){if(!l)return s(e,{error:"invalid_grant",error_description:"code_verifier required"},400);if(!fe(n.code_challenge,n.code_challenge_method,l))return s(e,{error:"invalid_grant",error_description:"code_verifier mismatch"},400)}if(D.OAUTH_CLIENT_ID&&n.client_id&&!H(n.client_id)&&n.client_id!==D.OAUTH_CLIENT_ID)return s(e,{error:"invalid_client",error_description:"Client mismatch"},400);const p=n.id_token;if(typeof p!="string"||p.length===0)return s(e,{error:"invalid_grant",error_description:"Missing id_token in authorization code"},400);const _=await J(p,r.getConfig().ssoDirect);if(!_)return s(e,{error:"invalid_grant",error_description:"Invalid authorization code"},400);const f=n.idp_access_token_enc??(n.idp_access_token?q(n.idp_access_token,m):void 0),{accessToken:d,expiresIn:a}=await K({claims:_.payload,kid:_.kid,idpId:n.idp_id,idpAccessTokenEnc:f}),C=Math.floor(Date.now()/1e3)+oe,E=await z({clientId:n.client_id,idpId:n.idp_id,claims:_.payload,idpAccessTokenEnc:f,idpRefreshTokenEnc:n.idp_refresh_token_enc,sessionExp:C}),O={access_token:d,token_type:"Bearer",expires_in:a,refresh_token:E,scope:y.join(" ")};return s(e,O,200,{"Cache-Control":"no-store",Pragma:"no-cache"})}catch(n){return e.get("logger")?.warn("MCP token exchange failed: %s",n instanceof Error?n.message:String(n)),s(e,{error:"invalid_grant",error_description:"Invalid authorization code"},400)}}catch(t){const i=t instanceof Error?t.message:String(t);return s(e,{error:"server_error",error_description:"Failed to process token request",error_details:i},500)}}}async function J(r,e){const t=await te(e||{},{[v.AUTHORIZATION]:r});if(t.isAuthenticated!==!0)return;const{payload:i,header:c}=M.decode(r);if(i[R.CLAIM]!==R.VALUE)return{payload:i,kid:c.kid,idpId:typeof t.idpId=="string"?t.idpId:void 0}}function Ge(r){return async e=>{const t=new URL(e.req.url);let i=t.searchParams.get("context");if(!i&&t.pathname.startsWith(I(`${T.MCP_CALLBACK}/`))){const o=t.pathname.split("/");i=o[o.length-1]}if(!i)return e.text("Missing context parameter",400);let c=null;try{const o=await me(i);if(c=o.mcpSessionId||null,!o.isMcpFlow||!o.originalRedirectUri)throw new Error("Invalid MCP context");const l=r.getConfig().ssoDirect,n=U(e,v.AUTHORIZATION),p=n?await J(n,l):void 0,_=U(e,v.IDP_ACCESS_TOKEN),f=U(e,v.IDP_REFRESH_TOKEN);if(!n||!p)return A.sendMcpAuthorizationFailedMessage([{...S(c),error:"Authentication required",error_details:null}]),e.text("Authentication required",401);const d=await X({idToken:n,idpId:p.idpId??B(l),idpAccessTokenEnc:_?q(_,m):void 0,idpRefreshTokenEnc:f?G(f,m):void 0,clientId:o.mcpClientId||"",redirectUri:o.originalRedirectUri,codeChallenge:o.mcpCodeChallenge||void 0,codeChallengeMethod:o.mcpCodeChallengeMethod||void 0,ttlSec:600}),a=new URL(o.originalRedirectUri);return a.searchParams.set("code",d),o.mcpState&&a.searchParams.set("state",o.mcpState),A.sendMcpAuthorizationCompletedMessage([{...S(c),redirect_uri:o.originalRedirectUri||null}]),e.redirect(a.toString())}catch(o){const l=ke(o);return A.sendMcpAuthorizationFailedMessage([{...S(c),...l}]),e.text(`Invalid MCP callback: ${l.error}`,400)}}}function ke(r){return r instanceof Error&&[ie,se,ce,de,ae].some(e=>r instanceof e)?{error:r.name,error_details:null}:r instanceof Error?{error:r.message,error_details:r.stack??null}:{error:String(r),error_details:null}}export{$ as SUPPORTED_MCP_GRANT_TYPES,he as createMcpContextToken,je as mcpAuthorizationHandler,Ge as mcpCallbackHandler,ze as mcpDynamicClientRegistrationHandler,$e as mcpOAuthAuthorizationServerHandler,be as mcpOAuthProtectedResourceHandler,Fe as mcpTokenPortalHandler,B as resolveMcpIdpId,me as verifyAndParseMcpContextToken,fe as verifyPkce};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import type { Handler } from 'hono';
|
|
2
2
|
import type { Store } from '../../store';
|
|
3
|
-
export declare function semanticSearchHandler(
|
|
3
|
+
export declare function semanticSearchHandler(store: Store): Handler;
|
|
4
4
|
//# sourceMappingURL=semantic-search.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{withPathPrefix as p}from"@redocly/theme/core/utils";import{SEMANTIC_SEARCH_API_URL as s}from"../../constants/common.js";import{fetchWithClient as
|
|
1
|
+
import{withPathPrefix as p}from"@redocly/theme/core/utils";import{SEMANTIC_SEARCH_API_URL as s}from"../../constants/common.js";import{fetchWithClient as d}from"../../utils/fetch-with-client.js";import{handleUnauthorizedApiRequest as h}from"../utils.js";function y(i){return async e=>{if(!s)return e.newResponse(null,404);const n=e.get("auth");if(i.getConfig().access?.requiresLogin&&!n.isAuthenticated)return h(e);const o={"Content-Type":"application/json"};n.idpAccessToken&&(o.Cookie=`accessToken=${n.idpAccessToken}`);const a=await e.req.json();try{const t=await d(s,{method:"POST",body:JSON.stringify(a),headers:o});if(t.ok){const u=(await t.json()).documents.map(r=>({...r,url:p(r.url)}));return e.json(u)}const c=await t.text();return e.newResponse(c,t.status,{"Content-Type":"application/json"})}catch(t){return e.json({error:"Failed to fetch semantic search results",details:String(t)},500)}}}export{y as semanticSearchHandler};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import
|
|
1
|
+
import o from"path";import{REDOCLY_ROUTE_RBAC as C}from"@redocly/config";import{PUBLIC_STATIC_FOLDER as r}from"../../constants/common.js";import{isPathInFolder as g}from"../../../utils/path/is-path-in-folder.js";import{fileExistsAsync as T}from"../../utils/index.js";import{handleUnauthorizedAsset as h}from"../utils.js";import{MIME_TYPES as w}from"../mime-types.js";import{getContentTypeHeaderValue as y}from"../utils/content-type.js";import{canAccessResource as E}from"../../utils/rbac.js";const U=async(e,n,s,a)=>{const c=n.req,{isAuthenticated:m,teams:l,claims:{email:u}}=n.get("auth"),i=o.join(r,r);e.startsWith(i)&&(e=e.replace(i,r));const t=o.resolve(s.outdir,e);if(!g(t,o.join(s.outdir,r)))return null;if(await T(t)){const p={[C]:{slug:e,fsPath:t},slug:e};if(!E(p,{isAuthenticated:m,email:u,teams:l},s.config.access?.rbac,s.config.access?.requiresLogin))return h(n);const f=c.query("download")!=null,d=w[o.extname(t)]||"text/plain",A=await a(t);return n.newResponse(A,200,{"Content-Type":y(d),"Access-Control-Allow-Origin":"*",...f&&{"Content-Disposition":`attachment; filename="${o.basename(t)}"`}})}else return null};export{U as staticContentHandler};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@redocly/revel",
|
|
3
|
-
"version": "0.138.0-next.
|
|
3
|
+
"version": "0.138.0-next.4",
|
|
4
4
|
"description": "",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -92,7 +92,7 @@
|
|
|
92
92
|
"tty-browserify": "0.0.1",
|
|
93
93
|
"typesense": "2.1.0",
|
|
94
94
|
"ulid": "^2.3.0",
|
|
95
|
-
"undici": "^6.
|
|
95
|
+
"undici": "^6.28.0",
|
|
96
96
|
"web-vitals": "3.3.1",
|
|
97
97
|
"workerpool": "9.2.0",
|
|
98
98
|
"ws": "^8.21.0",
|