Skip to content

The open-source agent harness - the runtime layer that turns an LLM into a working agent.

chore: Replace MCP authorize `redirect_url` with a same-origin `return_to` path (#319)

Srajan Asthana45dc6cd5a57f
diff --git a/.changeset/20260818161225-mcp-authorize-return-to.md b/.changeset/20260818161225-mcp-authorize-return-to.md
new file mode 100644
index 000000000..eb3b71eb0
--- /dev/null
+++ b/.changeset/20260818161225-mcp-authorize-return-to.md
@@ -0,0 +1,7 @@
+---
+'@truefoundry/trueforge': patch
+'@truefoundry/trueforge-sdk': patch
+'@truefoundry/trueforge-ui': patch
+---
+
+Replace MCP authorize `redirect_url` with a same-origin `return_to` path to prevent open redirects after OAuth.
diff --git a/.github/fern/openapi/openapi.json b/.github/fern/openapi/openapi.json
index 2bac566a8..2ae8326ac 100644
--- a/.github/fern/openapi/openapi.json
+++ b/.github/fern/openapi/openapi.json
@@ -4815,7 +4815,7 @@
},
"/api/v1/mcp-servers/oauth/callback": {
"get": {
- "description": "Browser redirect target for MCP server OAuth. The authorization server redirects here with `code`/`state` (or `error`). Exchanges the code for tokens, then either returns JSON or redirects to the `redirect_url` supplied at authorize time. Not called by the SDK — browsers hit this URL directly.",
+ "description": "Browser redirect target for MCP server OAuth. The authorization server redirects here with `code`/`state` (or `error`). Exchanges the code for tokens, then either returns JSON or redirects to the `return_to` path supplied at authorize time. Not called by the SDK — browsers hit this URL directly.",
"parameters": [
{
"description": "Authorization code, present when the user granted consent.",
@@ -4867,7 +4867,7 @@
"schema": {
"properties": {
"success": {
- "description": "Present when the OAuth callback completed without a redirect_url.",
+ "description": "Present when the OAuth callback completed without a return_to.",
"enum": [
true
],
@@ -4881,10 +4881,10 @@
}
}
},
- "description": "Token exchanged successfully and no `redirect_url` was given at authorize time."
+ "description": "Token exchanged successfully and no `return_to` was given at authorize time."
},
"302": {
- "description": "Redirect to the `redirect_url` given at authorize time, with `isSuccess` (and `reason` when it failed) appended to its existing query params."
+ "description": "Redirect to the `return_to` path given at authorize time, with `isSuccess` (and `reason` when it failed) appended to its existing query params."
},
"400": {
"content": {
@@ -4962,7 +4962,7 @@
"x-fern-sdk-method-name": "delete_authorization"
},
"get": {
- "description": "For servers without auth returns not_required, and for header credentials returns authenticated (no browser flow). For auth.type dcr, returns authenticated when a usable (or refreshable) token exists; otherwise runs DCR if needed and returns auth_required with an authorization URL. Optional redirect_url is where the OAuth callback then redirects the browser; without it the callback returns JSON.",
+ "description": "For servers without auth returns not_required, and for header credentials returns authenticated (no browser flow). For auth.type dcr, returns authenticated when a usable (or refreshable) token exists; otherwise runs DCR if needed and returns auth_required with an authorization URL. Optional return_to is where the OAuth callback then redirects the browser; without it the callback returns JSON.",
"parameters": [
{
"description": "MCP server name.",
@@ -4976,13 +4976,12 @@
}
},
{
- "description": "Optional FE landing URL the OAuth callback redirects to, with `isSuccess`/`reason` appended.",
+ "description": "Optional path to return to after OAuth. Must be a same-origin relative path; the OAuth callback redirects here with `isSuccess`/`reason` appended.",
"in": "query",
- "name": "redirect_url",
+ "name": "return_to",
"required": false,
"schema": {
- "description": "Optional FE landing URL the OAuth callback redirects to, with `isSuccess`/`reason` appended.",
- "format": "uri",
+ "description": "Optional path to return to after OAuth. Must be a same-origin relative path; the OAuth callback redirects here with `isSuccess`/`reason` appended.",
"type": "string"
}
}
@@ -5006,7 +5005,7 @@
}
}
},
- "description": "Invalid redirect_url."
+ "description": "Invalid return_to."
},
"404": {
"content": {
diff --git a/docs/openapi.json b/docs/openapi.json
index 2bac566a8..2ae8326ac 100644
--- a/docs/openapi.json
+++ b/docs/openapi.json
@@ -4815,7 +4815,7 @@
},
"/api/v1/mcp-servers/oauth/callback": {
"get": {
- "description": "Browser redirect target for MCP server OAuth. The authorization server redirects here with `code`/`state` (or `error`). Exchanges the code for tokens, then either returns JSON or redirects to the `redirect_url` supplied at authorize time. Not called by the SDK — browsers hit this URL directly.",
+ "description": "Browser redirect target for MCP server OAuth. The authorization server redirects here with `code`/`state` (or `error`). Exchanges the code for tokens, then either returns JSON or redirects to the `return_to` path supplied at authorize time. Not called by the SDK — browsers hit this URL directly.",
"parameters": [
{
"description": "Authorization code, present when the user granted consent.",
@@ -4867,7 +4867,7 @@
"schema": {
"properties": {
"success": {
- "description": "Present when the OAuth callback completed without a redirect_url.",
+ "description": "Present when the OAuth callback completed without a return_to.",
"enum": [
true
],
@@ -4881,10 +4881,10 @@
}
}
},
- "description": "Token exchanged successfully and no `redirect_url` was given at authorize time."
+ "description": "Token exchanged successfully and no `return_to` was given at authorize time."
},
"302": {
- "description": "Redirect to the `redirect_url` given at authorize time, with `isSuccess` (and `reason` when it failed) appended to its existing query params."
+ "description": "Redirect to the `return_to` path given at authorize time, with `isSuccess` (and `reason` when it failed) appended to its existing query params."
},
"400": {
"content": {
@@ -4962,7 +4962,7 @@
"x-fern-sdk-method-name": "delete_authorization"
},
"get": {
- "description": "For servers without auth returns not_required, and for header credentials returns authenticated (no browser flow). For auth.type dcr, returns authenticated when a usable (or refreshable) token exists; otherwise runs DCR if needed and returns auth_required with an authorization URL. Optional redirect_url is where the OAuth callback then redirects the browser; without it the callback returns JSON.",
+ "description": "For servers without auth returns not_required, and for header credentials returns authenticated (no browser flow). For auth.type dcr, returns authenticated when a usable (or refreshable) token exists; otherwise runs DCR if needed and returns auth_required with an authorization URL. Optional return_to is where the OAuth callback then redirects the browser; without it the callback returns JSON.",
"parameters": [
{
"description": "MCP server name.",
@@ -4976,13 +4976,12 @@
}
},
{
- "description": "Optional FE landing URL the OAuth callback redirects to, with `isSuccess`/`reason` appended.",
+ "description": "Optional path to return to after OAuth. Must be a same-origin relative path; the OAuth callback redirects here with `isSuccess`/`reason` appended.",
"in": "query",
- "name": "redirect_url",
+ "name": "return_to",
"required": false,
"schema": {
- "description": "Optional FE landing URL the OAuth callback redirects to, with `isSuccess`/`reason` appended.",
- "format": "uri",
+ "description": "Optional path to return to after OAuth. Must be a same-origin relative path; the OAuth callback redirects here with `isSuccess`/`reason` appended.",
"type": "string"
}
}
@@ -5006,7 +5005,7 @@
}
}
},
- "description": "Invalid redirect_url."
+ "description": "Invalid return_to."
},
"404": {
"content": {
diff --git a/packages/frontend/package.json b/packages/frontend/package.json
index f88499702..cde558600 100644
--- a/packages/frontend/package.json
+++ b/packages/frontend/package.json
@@ -27,7 +27,7 @@
"@assistant-ui/core": "0.2.22",
"@assistant-ui/react": "^0.14.24",
"@assistant-ui/store": "0.2.21",
- "@truefoundry/assistant-ui-runtime": "0.1.18",
+ "@truefoundry/assistant-ui-runtime": "0.1.20",
"@truefoundry/trueforge-sdk": "workspace:*",
"@truefoundry/trueforge-ui": "workspace:*",
"monaco-editor": "^0.52.0",
diff --git a/packages/trueforge-sdk/reference.md b/packages/trueforge-sdk/reference.md
index f1f992c73..c4f0cb802 100644
--- a/packages/trueforge-sdk/reference.md
+++ b/packages/trueforge-sdk/reference.md
@@ -563,7 +563,7 @@ await client.mcpServers.list();
<dl>
<dd>
-For servers without auth returns not_required, and for header credentials returns authenticated (no browser flow). For auth.type dcr, returns authenticated when a usable (or refreshable) token exists; otherwise runs DCR if needed and returns auth_required with an authorization URL. Optional redirect_url is where the OAuth callback then redirects the browser; without it the callback returns JSON.
+For servers without auth returns not_required, and for header credentials returns authenticated (no browser flow). For auth.type dcr, returns authenticated when a usable (or refreshable) token exists; otherwise runs DCR if needed and returns auth_required with an authorization URL. Optional return_to is where the OAuth callback then redirects the browser; without it the callback returns JSON.
</dd>
</dl>
</dd>
diff --git a/packages/trueforge-sdk/src/api/resources/mcpServers/client/Client.ts b/packages/trueforge-sdk/src/api/resources/mcpServers/client/Client.ts
index 4042a08c6..effe7a704 100644
--- a/packages/trueforge-sdk/src/api/resources/mcpServers/client/Client.ts
+++ b/packages/trueforge-sdk/src/api/resources/mcpServers/client/Client.ts
@@ -103,7 +103,7 @@ export class McpServersClient {
}
/**
- * For servers without auth returns not_required, and for header credentials returns authenticated (no browser flow). For auth.type dcr, returns authenticated when a usable (or refreshable) token exists; otherwise runs DCR if needed and returns auth_required with an authorization URL. Optional redirect_url is where the OAuth callback then redirects the browser; without it the callback returns JSON.
+ * For servers without auth returns not_required, and for header credentials returns authenticated (no browser flow). For auth.type dcr, returns authenticated when a usable (or refreshable) token exists; otherwise runs DCR if needed and returns auth_required with an authorization URL. Optional return_to is where the OAuth callback then redirects the browser; without it the callback returns JSON.
*
* @param {string} name - MCP server name.
* @param {TrueForge.AuthorizeMcpServersRequest} request
@@ -133,9 +133,9 @@ export class McpServersClient {
request: TrueForge.AuthorizeMcpServersRequest = {},
requestOptions?: McpServersClient.RequestOptions,
): Promise<core.WithRawResponse<TrueForge.McpAuthStatus>> {
- const { redirectUrl } = request;
+ const { returnTo } = request;
const _queryParams: Record<string, unknown> = {
- redirect_url: redirectUrl,
+ return_to: returnTo,
};
const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest();
const _headers: core.Fetcher.Args["headers"] = mergeHeaders(
diff --git a/packages/trueforge-sdk/src/api/resources/mcpServers/client/requests/AuthorizeMcpServersRequest.ts b/packages/trueforge-sdk/src/api/resources/mcpServers/client/requests/AuthorizeMcpServersRequest.ts
index dae9b1e8b..1393c70f6 100644
--- a/packages/trueforge-sdk/src/api/resources/mcpServers/client/requests/AuthorizeMcpServersRequest.ts
+++ b/packages/trueforge-sdk/src/api/resources/mcpServers/client/requests/AuthorizeMcpServersRequest.ts
@@ -5,6 +5,6 @@
* {}
*/
export interface AuthorizeMcpServersRequest {
- /** Optional FE landing URL the OAuth callback redirects to, with `isSuccess`/`reason` appended. */
- redirectUrl?: string;
+ /** Optional path to return to after OAuth. Must be a same-origin relative path; the OAuth callback redirects here with `isSuccess`/`reason` appended. */
+ returnTo?: string;
}
diff --git a/packages/trueforge-ui/example/package.json b/packages/trueforge-ui/example/package.json
index 1bff0b7d8..18853ad7f 100644
--- a/packages/trueforge-ui/example/package.json
+++ b/packages/trueforge-ui/example/package.json
@@ -15,7 +15,7 @@
"dependencies": {
"@assistant-ui/core": "^0.2.22",
"@assistant-ui/react": "^0.14.24",
- "@truefoundry/assistant-ui-runtime": "0.1.18",
+ "@truefoundry/assistant-ui-runtime": "0.1.20",
"@truefoundry/trueforge-ui": "link:..",
"react": "^19.2.4",
"react-dom": "^19.2.4",
diff --git a/packages/trueforge-ui/package.json b/packages/trueforge-ui/package.json
index 4ffe3f240..b2a8072a6 100644
--- a/packages/trueforge-ui/package.json
+++ b/packages/trueforge-ui/package.json
@@ -97,7 +97,7 @@
"@openuidev/react-headless": "^0.9.4",
"@openuidev/react-lang": "^0.2.9",
"@openuidev/react-ui": "^0.13.2",
- "@truefoundry/assistant-ui-runtime": "0.1.18",
+ "@truefoundry/assistant-ui-runtime": "0.1.20",
"@truefoundry/trueforge-sdk": "workspace:*",
"clsx": "^2.1.1",
"lucide-react": "^0.562.0",
diff --git a/packages/trueforge-ui/src/hooks/useMcpAuth.ts b/packages/trueforge-ui/src/hooks/useMcpAuth.ts
index 9545c2c17..41315940a 100644
--- a/packages/trueforge-ui/src/hooks/useMcpAuth.ts
+++ b/packages/trueforge-ui/src/hooks/useMcpAuth.ts
@@ -85,7 +85,7 @@ export const useMCPAuth = ({ callbackPath }: UseMCPAuthOptions = {}) => {
const result = await connectorCatalog.authenticateConnector({
id: integrationId,
- redirectURL: callbackUrl.toString(),
+ returnTo: `${callbackUrl.pathname}${callbackUrl.search}`,
});
if (
diff --git a/packages/trueforge-ui/src/plugins/trueforge-agent-server-adapter/catalogs/connectorCatalog.ts b/packages/trueforge-ui/src/plugins/trueforge-agent-server-adapter/catalogs/connectorCatalog.ts
index 6d1465827..76a053e57 100644
--- a/packages/trueforge-ui/src/plugins/trueforge-agent-server-adapter/catalogs/connectorCatalog.ts
+++ b/packages/trueforge-ui/src/plugins/trueforge-agent-server-adapter/catalogs/connectorCatalog.ts
@@ -216,7 +216,7 @@ export function createConnectorCatalog(
authenticateConnector: async req => {
const result = await client.mcpServers.authorize(
req.id,
- req.redirectURL === undefined ? {} : { redirectUrl: req.redirectURL },
+ req.returnTo === undefined ? {} : { returnTo: req.returnTo },
);
return { status: result.status, authorization_endpoint: result.authorizationUrl };
},
diff --git a/packages/trueforge-ui/test/hooks/useMcpAuth.test.ts b/packages/trueforge-ui/test/hooks/useMcpAuth.test.ts
index 66120fb79..3d5ede323 100644
--- a/packages/trueforge-ui/test/hooks/useMcpAuth.test.ts
+++ b/packages/trueforge-ui/test/hooks/useMcpAuth.test.ts
@@ -49,11 +49,11 @@ function getPopupUid(): string {
const call = authenticateConnector.mock.calls.at(-1);
if (!call) throw new Error('Expected authenticateConnector to be called');
- const redirectURL = call[0].redirectURL;
- if (!redirectURL) throw new Error('Expected authenticateConnector to receive a redirect URL');
+ const returnTo = call[0].returnTo;
+ if (!returnTo) throw new Error('Expected authenticateConnector to receive a returnTo');
- const popupUid = new URL(redirectURL).searchParams.get('pUid');
- if (!popupUid) throw new Error('Expected the redirect URL to contain a popup UID');
+ const popupUid = new URL(returnTo, window.location.origin).searchParams.get('pUid');
+ if (!popupUid) throw new Error('Expected returnTo to contain a popup UID');
return popupUid;
}
@@ -90,7 +90,7 @@ describe('useMCPAuth', () => {
expect(authenticateConnector).toHaveBeenCalledWith({
id: 'connector-1',
- redirectURL: expect.any(String),
+ returnTo: expect.stringMatching(/^\/chat\?/),
});
expect(callback).toHaveBeenCalledOnce();
expect(callback).toHaveBeenCalledWith(true);
@@ -120,11 +120,14 @@ describe('useMCPAuth', () => {
expect(channels[0]?.name).toBe(MCP_AUTH_POPUP_CHANNEL);
const redirectCall = authenticateConnector.mock.calls[0];
- if (!redirectCall?.[0].redirectURL) throw new Error('Expected a redirect URL');
- const redirectURL = new URL(redirectCall[0].redirectURL);
- expect(redirectURL.pathname).toBe('/oauth/callback');
- expect(redirectURL.searchParams.get('screenType')).toBe('mcp-auth');
- expect(redirectURL.searchParams.get('integrationId')).toBe('connector-2');
+ const returnTo = redirectCall?.[0].returnTo;
+ if (!returnTo) throw new Error('Expected a returnTo');
+ expect(returnTo.startsWith('/')).toBe(true);
+ expect(returnTo.includes('://')).toBe(false);
+ const returnToUrl = new URL(returnTo, window.location.origin);
+ expect(returnToUrl.pathname).toBe('/oauth/callback');
+ expect(returnToUrl.searchParams.get('screenType')).toBe('mcp-auth');
+ expect(returnToUrl.searchParams.get('integrationId')).toBe('connector-2');
const channel = channels[0];
if (!channel) throw new Error('Expected an authorization channel');
diff --git a/packages/trueforge/src/apis/auth.ts b/packages/trueforge/src/apis/auth.ts
index b6e0ab881..a6a553baa 100644
--- a/packages/trueforge/src/apis/auth.ts
+++ b/packages/trueforge/src/apis/auth.ts
@@ -5,7 +5,8 @@ import type { Logger } from 'winston';
import { clearAuthCookie, ID_TOKEN_COOKIE, OAUTH_STATE_COOKIE, readOAuthStateCookie } from '../auth/cookies';
import { resolveUserContext } from '../auth/identity';
import { authMiddleware } from '../auth/middleware';
-import { buildLoginAuthorization, exchangeAuthorizationCode, getOidcVerify, safeReturnTo } from '../auth/oidc';
+import { buildLoginAuthorization, exchangeAuthorizationCode, getOidcVerify } from '../auth/oidc';
+import { safeReturnTo } from '../auth/safeReturnTo';
import { authLoginRoute, authLogoutRoute, meRoute, oAuthCallbackRoute } from '../routes/authRoutes';
import type { MeResponse } from '../schemas/auth';
diff --git a/packages/trueforge/src/apis/mcpOAuth.ts b/packages/trueforge/src/apis/mcpOAuth.ts
index 7165497a9..022687bbf 100644
--- a/packages/trueforge/src/apis/mcpOAuth.ts
+++ b/packages/trueforge/src/apis/mcpOAuth.ts
@@ -13,25 +13,35 @@ export interface McpOAuthRouterDeps<TTransaction> {
type McpOAuthCallbackContext = Parameters<RouteHandler<typeof mcpOAuthCallbackRoute>>[0];
-/** Landing URL with the outcome appended to whatever query params it already carries. */
-function callbackLandingUrl(params: { redirectUrl: string; isSuccess: boolean; reason?: string }): string {
- const url = new URL(params.redirectUrl);
+/**
+ * Landing path with the outcome appended to whatever query params it already carries.
+ * `returnTo` is resolved against the callback request URL only so `URL` can parse the
+ * relative path; the redirect stays relative (`pathname + search`), so the browser
+ * keeps whatever origin it is already on.
+ */
+function callbackLandingPath(params: {
+ c: McpOAuthCallbackContext;
+ returnTo: string;
+ isSuccess: boolean;
+ reason?: string;
+}): string {
+ const url = new URL(params.returnTo, params.c.req.url);
url.searchParams.set('isSuccess', String(params.isSuccess));
if (params.reason) {
url.searchParams.set('reason', params.reason);
}
- return url.href;
+ return `${url.pathname}${url.search}`;
}
/**
- * JSON is the answer whenever there is no landing URL to return to: authorize was called without
- * `redirect_url`, or the pending row that carried it is gone (TTL expired, already redeemed, unknown
+ * JSON is the answer whenever there is no landing path to return to: authorize was called without
+ * `return_to`, or the pending row that carried it is gone (TTL expired, already redeemed, unknown
* `state`) — the OAuth callback URL is never a page we send the user to on purpose.
*/
function callbackSuccess(params: { c: McpOAuthCallbackContext; pending: OAuthPendingAuthorization }) {
- const redirectUrl = params.pending.redirectUrl;
- if (redirectUrl) {
- return params.c.redirect(callbackLandingUrl({ redirectUrl, isSuccess: true }), 302);
+ const returnTo = params.pending.returnTo;
+ if (returnTo) {
+ return params.c.redirect(callbackLandingPath({ c: params.c, returnTo, isSuccess: true }), 302);
}
return params.c.json({ success: true as const }, 200);
}
@@ -42,9 +52,12 @@ function callbackFailure(params: {
message: string;
jsonStatus?: 400 | 500;
}) {
- const redirectUrl = params.pending?.redirectUrl;
- if (redirectUrl) {
- return params.c.redirect(callbackLandingUrl({ redirectUrl, isSuccess: false, reason: params.message }), 302);
+ const returnTo = params.pending?.returnTo;
+ if (returnTo) {
+ return params.c.redirect(
+ callbackLandingPath({ c: params.c, returnTo, isSuccess: false, reason: params.message }),
+ 302,
+ );
}
return params.c.json({ error: { message: params.message } }, params.jsonStatus ?? 400);
}
@@ -54,7 +67,7 @@ export function createMcpOAuthRouter<TTransaction>(deps: McpOAuthRouterDeps<TTra
const callbackHandler: RouteHandler<typeof mcpOAuthCallbackRoute> = async c => {
const { state, code, error, error_description: errorDescription } = c.req.valid('query');
- // Claimed up front: this row carries the FE landing URL every branch below returns to, and
+ // Claimed up front: this row carries the FE landing path every branch below returns to, and
// claiming it atomically means a duplicate callback loses the race.
const pending = await deps.tokenStore.consumePendingAuthorization({ state });
if (!pending) {
diff --git a/packages/trueforge/src/apis/mcpServers.ts b/packages/trueforge/src/apis/mcpServers.ts
index ee5cd721c..1ffe38115 100644
--- a/packages/trueforge/src/apis/mcpServers.ts
+++ b/packages/trueforge/src/apis/mcpServers.ts
@@ -2,11 +2,12 @@ import { OpenAPIHono, type RouteHandler } from '@hono/zod-openapi';
import { extractErrorLogFields, isAuthRequired, McpConnectionError, RemoteMCP } from '@truefoundry/trueforge-core/core';
import type { Logger } from 'winston';
import type { ResolveUserContext } from '../auth/identity';
+import { safeReturnTo } from '../auth/safeReturnTo';
import configuration from '../config';
import { McpServerNameConflictError, type IMcpServerStore, type McpServerRecord } from '../db/mcpServerStore';
import type { WithTransaction } from '../db/transaction';
import { createMcpOAuthClient, isMcpAuthRequired, resolveMcpAuth } from '../mcp/auth/mcpDcr';
-import { mcpOAuthCallbackUrl, validateRedirectUris } from '../mcp/auth/mcpOAuthHelpers';
+import { mcpOAuthCallbackUrl } from '../mcp/auth/mcpOAuthHelpers';
import type { IOAuthTokenStore, OAuthClientRecord, OAuthToken } from '../mcp/auth/types';
import {
authorizeMcpServerRoute,
@@ -364,7 +365,7 @@ export function createSettingsMcpServersRouter<TTransaction>(deps: McpServersRou
export function createMcpServersRouter<TTransaction>(deps: McpServersRouterDeps<TTransaction>) {
const authorizeHandler: RouteHandler<typeof authorizeMcpServerRoute> = async c => {
const { name } = c.req.valid('param');
- const { redirect_url: redirectUrl } = c.req.valid('query');
+ const { return_to: returnTo } = c.req.valid('query');
const userRef = deps.resolveUserContext(c).userRef;
const record = await deps.mcpServerStore.getServer({ tenant_id: TENANT_ID, name });
if (!record) {
@@ -375,10 +376,11 @@ export function createMcpServersRouter<TTransaction>(deps: McpServersRouterDeps<
return c.json(resolveMcpAuthStatus({ manifest: record.manifest }), 200);
}
+ if (returnTo && safeReturnTo(returnTo) !== returnTo) {
+ return c.json({ error: { message: 'Invalid return_to: must be a same-origin relative path' } }, 400);
+ }
+
try {
- if (redirectUrl) {
- validateRedirectUris({ redirectUris: [redirectUrl] });
- }
// Reuses a usable/refreshable token when present; only builds an auth URL when needed.
// Client is usually already registered at create/put; concurrent Connect races are harmless
// (last saveClient wins; rare orphan AS registration).
@@ -390,7 +392,7 @@ export function createMcpServersRouter<TTransaction>(deps: McpServersRouterDeps<
mcpServerUrl: record.manifest.url,
mcpServerName: record.name,
clientName: configuration.MCP_DCR_OAUTH_CLIENT_NAME,
- ...(redirectUrl !== undefined ? { redirectUrl } : {}),
+ ...(returnTo !== undefined ? { returnTo } : {}),
});
const authStatus: McpAuthStatus = isMcpAuthRequired(result)
? { status: 'auth_required', authorization_url: result.authUrl.href }
diff --git a/packages/trueforge/src/auth/oidc.ts b/packages/trueforge/src/auth/oidc.ts
index 362bfaad6..5d17c4308 100644
--- a/packages/trueforge/src/auth/oidc.ts
+++ b/packages/trueforge/src/auth/oidc.ts
@@ -12,6 +12,7 @@ import {
import { getPublicBaseUrl, type OIDCConfig } from '../config';
import { buildAuthorizationRequestParams } from './claims';
import { ID_TOKEN_COOKIE, OAUTH_STATE_COOKIE, setAuthCookie } from './cookies';
+import { safeReturnTo } from './safeReturnTo';
const CALLBACK_PATH = '/api/v1/auth/callback';
const OAUTH_STATE_MAX_AGE_SECONDS = 10 * 60;
@@ -70,21 +71,6 @@ function authCallbackUrl(): string {
return `${publicBaseUrl}${CALLBACK_PATH}`;
}
-/**
- * Same-origin relative path only.
- * - starts with `/`
- * - not `//…` (open redirect)
- * - not `/api` or `/api/…`
- */
-const SAFE_RETURN_TO = /^\/(?!\/|api(?:\/|$)).*/;
-
-export function safeReturnTo(value: string | undefined): string {
- if (value && SAFE_RETURN_TO.test(value)) {
- return value;
- }
- return '/';
-}
-
export async function buildLoginAuthorization(params: {
context: Context;
client: Configuration;
diff --git a/packages/trueforge/src/auth/safeReturnTo.ts b/packages/trueforge/src/auth/safeReturnTo.ts
new file mode 100644
index 000000000..3be30bf4d
--- /dev/null
+++ b/packages/trueforge/src/auth/safeReturnTo.ts
@@ -0,0 +1,19 @@
+/**
+ * Same-origin relative path only.
+ * - starts with `/`
+ * - not `//…` (open redirect)
+ * - not `/api` or `/api/…`
+ */
+const SAFE_RETURN_TO = /^\/(?!\/|api(?:\/|$)).*/;
+
+function isSafeReturnTo(value: string): boolean {
+ return SAFE_RETURN_TO.test(value);
+}
+
+/** Same-origin path, or `/` when missing or unsafe. */
+export function safeReturnTo(value: string | undefined): string {
+ if (value && isSafeReturnTo(value)) {
+ return value;
+ }
+ return '/';
+}
diff --git a/packages/trueforge/src/db/mcpServerStore.ts b/packages/trueforge/src/db/mcpServerStore.ts
index 64f1aa792..762f736c8 100644
--- a/packages/trueforge/src/db/mcpServerStore.ts
+++ b/packages/trueforge/src/db/mcpServerStore.ts
@@ -105,7 +105,7 @@ export interface OAuthPendingAuthorizationData {
/** MCP server URL from authorize time — needed by the shared callback for RFC 8707 `resource`. */
mcp_server_url: string;
code_verifier: string | null;
- redirect_url: string | null;
+ return_to: string | null;
}
/** `oauth_token.token` JSONB. */
@@ -176,16 +176,16 @@ export function toStoredOAuthPendingAuthorizationData(
return {
mcp_server_url: pending.mcpServerUrl,
code_verifier: pending.codeVerifier,
- redirect_url: pending.redirectUrl,
+ return_to: pending.returnTo,
};
}
export function fromStoredOAuthPendingAuthorizationData(
stored: OAuthPendingAuthorizationData,
-): Pick<ContractOAuthPendingAuthorization, 'mcpServerUrl' | 'codeVerifier' | 'redirectUrl'> {
+): Pick<ContractOAuthPendingAuthorization, 'mcpServerUrl' | 'codeVerifier' | 'returnTo'> {
return {
mcpServerUrl: stored.mcp_server_url,
codeVerifier: stored.code_verifier,
- redirectUrl: stored.redirect_url,
+ returnTo: stored.return_to,
};
}
diff --git a/packages/trueforge/src/db/postgres/migrations/20260818_000001_mcp_pending_auth_return_to.ts b/packages/trueforge/src/db/postgres/migrations/20260818_000001_mcp_pending_auth_return_to.ts
new file mode 100644
index 000000000..7a20670c2
--- /dev/null
+++ b/packages/trueforge/src/db/postgres/migrations/20260818_000001_mcp_pending_auth_return_to.ts
@@ -0,0 +1,19 @@
+import { sql, type Kysely } from 'kysely';
+
+/**
+ * Pending-authorization `auth_data` jsonb key `redirect_url` → `return_to` (path).
+ * In-flight rows are short-lived and cannot be rewritten safely; drop them so
+ * callers restart authorize with the new shape.
+ */
+export async function up(db: Kysely<unknown>): Promise<void> {
+ await sql`SET LOCAL lock_timeout = '5s'`.execute(db);
+ await sql`LOCK TABLE oauth_pending_authorization IN ACCESS EXCLUSIVE MODE`.execute(db);
+ await sql`DELETE FROM oauth_pending_authorization`.execute(db);
+}
+
+export async function down(db: Kysely<unknown>): Promise<void> {
+ await sql`SET LOCAL lock_timeout = '5s'`.execute(db);
+ // Rows written with `return_to` are incompatible with the prior shape; clear them.
+ await sql`LOCK TABLE oauth_pending_authorization IN ACCESS EXCLUSIVE MODE`.execute(db);
+ await sql`DELETE FROM oauth_pending_authorization`.execute(db);
+}
diff --git a/packages/trueforge/src/db/sqlite/migrations/20260818_000001_mcp_pending_auth_return_to.ts b/packages/trueforge/src/db/sqlite/migrations/20260818_000001_mcp_pending_auth_return_to.ts
new file mode 100644
index 000000000..4c6d4f6bd
--- /dev/null
+++ b/packages/trueforge/src/db/sqlite/migrations/20260818_000001_mcp_pending_auth_return_to.ts
@@ -0,0 +1,25 @@
+import { type Kysely, sql } from 'kysely';
+
+/**
+ * Pending-authorization `auth_data` jsonb key `redirect_url` → `return_to` (path).
+ * In-flight rows are short-lived and cannot be rewritten safely; drop them so
+ * callers restart authorize with the new shape.
+ * Mirrors db/postgres/migrations/20260818_000001_mcp_pending_auth_return_to.ts.
+ *
+ * Wrapped in a transaction. SQLite has no LOCK TABLE; a no-op UPDATE escalates
+ * the deferred txn to a RESERVED write lock before the delete.
+ */
+export async function up(db: Kysely<unknown>): Promise<void> {
+ await db.transaction().execute(async trx => {
+ await sql`UPDATE oauth_pending_authorization SET created_at = created_at WHERE false`.execute(trx);
+ await sql`DELETE FROM oauth_pending_authorization`.execute(trx);
+ });
+}
+
+export async function down(db: Kysely<unknown>): Promise<void> {
+ await db.transaction().execute(async trx => {
+ // Rows written with `return_to` are incompatible with the prior shape; clear them.
+ await sql`UPDATE oauth_pending_authorization SET created_at = created_at WHERE false`.execute(trx);
+ await sql`DELETE FROM oauth_pending_authorization`.execute(trx);
+ });
+}
diff --git a/packages/trueforge/src/db/sqlite/types.ts b/packages/trueforge/src/db/sqlite/types.ts
index 3b795dc40..4da8ba290 100644
--- a/packages/trueforge/src/db/sqlite/types.ts
+++ b/packages/trueforge/src/db/sqlite/types.ts
@@ -263,7 +263,7 @@ export interface OAuthPendingAuthorizationTable {
/** FK -> mcp_server.id, ON DELETE CASCADE */
oauth_server_id: string;
user_id: string;
- /** { mcp_server_url, code_verifier, redirect_url } — same writer/lifecycle, so merged into one column */
+ /** { mcp_server_url, code_verifier, return_to } — same writer/lifecycle, so merged into one column */
auth_data: JsonbColumn<OAuthPendingAuthorizationData>;
created_at: string;
}
diff --git a/packages/trueforge/src/mcp/auth/mcpDcr.ts b/packages/trueforge/src/mcp/auth/mcpDcr.ts
index 6b87c2258..e754ae4d7 100644
--- a/packages/trueforge/src/mcp/auth/mcpDcr.ts
+++ b/packages/trueforge/src/mcp/auth/mcpDcr.ts
@@ -208,7 +208,7 @@ export async function buildMcpAuthorizationUrl(params: {
userRef: string;
mcpServerUrl: string;
mcpServerName: string;
- redirectUrl?: string;
+ returnTo?: string;
}): Promise<URL> {
const state = randomBytes(32).toString('base64url');
const redirectUri = mcpOAuthCallbackUrl();
@@ -232,7 +232,7 @@ export async function buildMcpAuthorizationUrl(params: {
userRef: params.userRef,
mcpServerUrl: params.mcpServerUrl,
codeVerifier: started.codeVerifier,
- redirectUrl: params.redirectUrl ?? null,
+ returnTo: params.returnTo ?? null,
});
return started.authorizationUrl;
}
@@ -245,7 +245,7 @@ export async function resolveMcpAuth(params: {
mcpServerUrl: string;
mcpServerName: string;
clientName: string;
- redirectUrl?: string;
+ returnTo?: string;
}): Promise<ResolveMcpAuthResult> {
const nowMs = Date.now();
const tokenKey = { id: params.serverId, userRef: params.userRef };
@@ -286,7 +286,7 @@ export async function resolveMcpAuth(params: {
userRef: params.userRef,
mcpServerUrl: params.mcpServerUrl,
mcpServerName: params.mcpServerName,
- ...(params.redirectUrl !== undefined ? { redirectUrl: params.redirectUrl } : {}),
+ ...(params.returnTo !== undefined ? { returnTo: params.returnTo } : {}),
});
return { authUrl };
}
diff --git a/packages/trueforge/src/mcp/auth/mcpOAuthHelpers.ts b/packages/trueforge/src/mcp/auth/mcpOAuthHelpers.ts
index a259155b7..a49edd73a 100644
--- a/packages/trueforge/src/mcp/auth/mcpOAuthHelpers.ts
+++ b/packages/trueforge/src/mcp/auth/mcpOAuthHelpers.ts
@@ -75,18 +75,3 @@ export function isOAuthAccessTokenUsable(expiresAtIso: string, nowMs: number): b
const expiresAtMs = Date.parse(expiresAtIso);
return !Number.isNaN(expiresAtMs) && expiresAtMs > nowMs;
}
-
-/** Validates redirect URLs parse as HTTP(S). */
-export function validateRedirectUris({ redirectUris }: { redirectUris: string[] }): void {
- for (const redirectUri of redirectUris) {
- let parsed: URL;
- try {
- parsed = new URL(redirectUri);
- } catch (error) {
- throw new McpConnectionError(`Invalid redirect URI: ${redirectUri}. Must be a valid URL.`, 400, { cause: error });
- }
- if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
- throw new McpConnectionError(`Invalid redirect URI: ${redirectUri}. Must be a valid URL.`, 400);
- }
- }
-}
diff --git a/packages/trueforge/src/mcp/auth/types.ts b/packages/trueforge/src/mcp/auth/types.ts
index a47d22eb1..659f35ff4 100644
--- a/packages/trueforge/src/mcp/auth/types.ts
+++ b/packages/trueforge/src/mcp/auth/types.ts
@@ -5,7 +5,7 @@ export interface OAuthPendingAuthorization {
userRef: string;
mcpServerUrl: string;
codeVerifier: string | null;
- redirectUrl: string | null;
+ returnTo: string | null;
}
/** Stored access token for one (MCP server, user) pair. */
diff --git a/packages/trueforge/src/routes/mcpOAuthRoutes.ts b/packages/trueforge/src/routes/mcpOAuthRoutes.ts
index 5f0abb3bd..ea60206ed 100644
--- a/packages/trueforge/src/routes/mcpOAuthRoutes.ts
+++ b/packages/trueforge/src/routes/mcpOAuthRoutes.ts
@@ -11,7 +11,7 @@ export const mcpOAuthCallbackRoute = createRoute({
summary: 'OAuth callback for MCP authorization',
description:
'Browser redirect target for MCP server OAuth. The authorization server redirects here with `code`/`state` (or `error`). ' +
- 'Exchanges the code for tokens, then either returns JSON or redirects to the `redirect_url` supplied at authorize time. ' +
+ 'Exchanges the code for tokens, then either returns JSON or redirects to the `return_to` path supplied at authorize time. ' +
'Not called by the SDK — browsers hit this URL directly.',
// Browser-redirect target hit directly by the authorization server, never called by SDK.
'x-fern-ignore': true,
@@ -21,11 +21,11 @@ export const mcpOAuthCallbackRoute = createRoute({
responses: {
200: {
content: { 'application/json': { schema: OAuthCallbackSuccessSchema } },
- description: 'Token exchanged successfully and no `redirect_url` was given at authorize time.',
+ description: 'Token exchanged successfully and no `return_to` was given at authorize time.',
},
302: {
description:
- 'Redirect to the `redirect_url` given at authorize time, with `isSuccess` (and `reason` when it failed) appended to its existing query params.',
+ 'Redirect to the `return_to` path given at authorize time, with `isSuccess` (and `reason` when it failed) appended to its existing query params.',
},
400: {
content: { 'application/json': { schema: RequestErrorResponseSchema } },
diff --git a/packages/trueforge/src/routes/mcpServerRoutes.ts b/packages/trueforge/src/routes/mcpServerRoutes.ts
index 6eec95552..8c2b51392 100644
--- a/packages/trueforge/src/routes/mcpServerRoutes.ts
+++ b/packages/trueforge/src/routes/mcpServerRoutes.ts
@@ -203,10 +203,12 @@ export const listMcpServerToolsRoute = createRoute({
});
const McpAuthorizeQuerySchema = z.object({
- redirect_url: z
- .url()
+ return_to: z
+ .string()
.optional()
- .describe('Optional FE landing URL the OAuth callback redirects to, with `isSuccess`/`reason` appended.'),
+ .describe(
+ 'Optional path to return to after OAuth. Must be a same-origin relative path; the OAuth callback redirects here with `isSuccess`/`reason` appended.',
+ ),
});
export const authorizeMcpServerRoute = createRoute({
@@ -220,7 +222,7 @@ export const authorizeMcpServerRoute = createRoute({
'For servers without auth returns not_required, and for header credentials returns authenticated ' +
'(no browser flow). For auth.type dcr, returns authenticated when a usable (or refreshable) token ' +
'exists; otherwise runs DCR if needed and returns auth_required with an authorization URL. ' +
- 'Optional redirect_url is where the OAuth callback then redirects the browser; without it the callback returns JSON.',
+ 'Optional return_to is where the OAuth callback then redirects the browser; without it the callback returns JSON.',
request: {
params: McpServerNameParamsSchema,
query: McpAuthorizeQuerySchema,
@@ -232,7 +234,7 @@ export const authorizeMcpServerRoute = createRoute({
},
400: {
content: { 'application/json': { schema: RequestErrorResponseSchema } },
- description: 'Invalid redirect_url.',
+ description: 'Invalid return_to.',
},
404: {
content: { 'application/json': { schema: RequestErrorResponseSchema } },
diff --git a/packages/trueforge/src/schemas/auth.ts b/packages/trueforge/src/schemas/auth.ts
index 756c74334..53211bf89 100644
--- a/packages/trueforge/src/schemas/auth.ts
+++ b/packages/trueforge/src/schemas/auth.ts
@@ -25,7 +25,7 @@ export const OAuthCallbackQuerySchema = z.object({
});
export const OAuthCallbackSuccessSchema = z.object({
- success: z.literal(true).describe('Present when the OAuth callback completed without a redirect_url.'),
+ success: z.literal(true).describe('Present when the OAuth callback completed without a return_to.'),
});
export const MeResponseSchema = z
diff --git a/packages/trueforge/tests/db/oauthTokenStoreContractSuite.ts b/packages/trueforge/tests/db/oauthTokenStoreContractSuite.ts
index 24a0f312c..3bb872a34 100644
--- a/packages/trueforge/tests/db/oauthTokenStoreContractSuite.ts
+++ b/packages/trueforge/tests/db/oauthTokenStoreContractSuite.ts
@@ -36,7 +36,7 @@ function pending(overrides: Partial<OAuthPendingAuthorization> = {}): OAuthPendi
userRef: USER_REF,
mcpServerUrl: 'https://mcp.example.com/sse',
codeVerifier: 'verifier-1',
- redirectUrl: 'https://app.example.com/done',
+ returnTo: '/done',
...overrides,
};
}
@@ -148,7 +148,7 @@ export function runOAuthTokenStoreContractSuite(getHarness: () => OAuthTokenStor
it('savePendingAuthorization + consumePendingAuthorization round-trips, including null fields', async () => {
const h = getHarness();
await h.seedResource(RESOURCE_ID);
- const saved = pending({ codeVerifier: null, redirectUrl: null });
+ const saved = pending({ codeVerifier: null, returnTo: null });
await h.store.savePendingAuthorization(saved);
diff --git a/packages/trueforge/tests/unit/apis/mcpOAuth.test.ts b/packages/trueforge/tests/unit/apis/mcpOAuth.test.ts
index 8dc38cf8d..d340f3f7d 100644
--- a/packages/trueforge/tests/unit/apis/mcpOAuth.test.ts
+++ b/packages/trueforge/tests/unit/apis/mcpOAuth.test.ts
@@ -14,7 +14,7 @@ import { mcpOAuthCallbackUrl } from '../../../src/mcp/auth/mcpOAuthHelpers';
const AS_ORIGIN = 'https://auth.example.com';
const MCP_URL = 'https://mcp.example.com/sse';
-const FE_REDIRECT = 'https://app.example.com/mcp/connected';
+const FE_RETURN_TO = '/mcp/connected';
const AS_METADATA = {
issuer: AS_ORIGIN,
@@ -117,7 +117,7 @@ describe('MCP OAuth authorize + callback', () => {
});
/** Registers a dcr server and authorizes it, returning the pending authorization's `state`. */
- async function pendingState(name: string, redirectUrl?: string): Promise<string> {
+ async function pendingState(name: string, returnTo?: string): Promise<string> {
const put = await settingsRouter.request('/', {
method: 'PUT',
headers: { 'content-type': 'application/json' },
@@ -134,8 +134,8 @@ describe('MCP OAuth authorize + callback', () => {
expect(put.status).toBe(200);
let query = '';
- if (redirectUrl) {
- query = `?redirect_url=${encodeURIComponent(redirectUrl)}`;
+ if (returnTo) {
+ query = `?return_to=${encodeURIComponent(returnTo)}`;
}
const authorize = await mcpServersRouter.request(`/${name}/authorize${query}`);
expect(authorize.status).toBe(200);
@@ -160,7 +160,7 @@ describe('MCP OAuth authorize + callback', () => {
expect(put.status).toBe(200);
const authorize = await mcpServersRouter.request(
- `/oauth-mcp/authorize?redirect_url=${encodeURIComponent(FE_REDIRECT)}`,
+ `/oauth-mcp/authorize?return_to=${encodeURIComponent(FE_RETURN_TO)}`,
);
expect(authorize.status).toBe(200);
const authorizeBody = (await authorize.json()) as { status: string; authorization_url?: string };
@@ -175,7 +175,7 @@ describe('MCP OAuth authorize + callback', () => {
const callback = await oauthRouter.request(`/callback?state=${encodeURIComponent(state ?? '')}&code=auth-code-1`);
expect(callback.status).toBe(302);
- expect(callback.headers.get('location')).toBe(`${FE_REDIRECT}?isSuccess=true`);
+ expect(callback.headers.get('location')).toBe(`${FE_RETURN_TO}?isSuccess=true`);
const record = await mcpServerStore.getServer({ tenant_id: 'default', name: 'oauth-mcp' });
expect(record).toBeDefined();
@@ -184,13 +184,13 @@ describe('MCP OAuth authorize + callback', () => {
expect(token?.refreshToken).toBe('refresh-1');
const reauthorize = await mcpServersRouter.request(
- `/oauth-mcp/authorize?redirect_url=${encodeURIComponent(FE_REDIRECT)}`,
+ `/oauth-mcp/authorize?return_to=${encodeURIComponent(FE_RETURN_TO)}`,
);
expect(reauthorize.status).toBe(200);
expect(await reauthorize.json()).toEqual({ status: 'authenticated' });
});
- it('callback returns 400 JSON when the pending row is gone, since its landing URL went with it', async () => {
+ it('callback returns 400 JSON when the pending row is gone, since its landing path went with it', async () => {
const unknown = await oauthRouter.request('/callback?state=no-such-state&code=x');
expect(unknown.status).toBe(400);
expect(await unknown.json()).toEqual({ error: { message: 'Unknown or expired OAuth state' } });
@@ -202,7 +202,7 @@ describe('MCP OAuth authorize + callback', () => {
});
it('callback redirects with the failure reason when the IdP denies consent', async () => {
- const landing = 'https://app.example.com/mcp/connected?tab=mcp';
+ const landing = '/mcp/connected?tab=mcp';
const state = await pendingState('oauth-mcp-denied', landing);
const denied = await oauthRouter.request(
@@ -212,7 +212,7 @@ describe('MCP OAuth authorize + callback', () => {
expect(denied.headers.get('location')).toBe(`${landing}&isSuccess=false&reason=access_denied`);
});
- it('callback returns success JSON when authorize supplied no redirect_url', async () => {
+ it('callback returns success JSON when authorize supplied no return_to', async () => {
const state = await pendingState('oauth-mcp-no-redirect');
const callback = await oauthRouter.request(`/callback?state=${encodeURIComponent(state)}&code=auth-code-1`);
@@ -245,7 +245,7 @@ describe('MCP OAuth authorize + callback', () => {
expect(put.status).toBe(200);
const authorizeA = await mcpServersRouter.request(
- `/oauth-mcp-scoped/authorize?redirect_url=${encodeURIComponent(FE_REDIRECT)}`,
+ `/oauth-mcp-scoped/authorize?return_to=${encodeURIComponent(FE_RETURN_TO)}`,
);
expect(authorizeA.status).toBe(200);
const authorizeABody = (await authorizeA.json()) as { authorization_url?: string };
diff --git a/packages/trueforge/tests/unit/apis/mcpServers.test.ts b/packages/trueforge/tests/unit/apis/mcpServers.test.ts
index 636f0c8e5..2cf41b1cb 100644
--- a/packages/trueforge/tests/unit/apis/mcpServers.test.ts
+++ b/packages/trueforge/tests/unit/apis/mcpServers.test.ts
@@ -334,7 +334,7 @@ describe('mcp-servers routers', () => {
userRef: LOCAL_USER_CONTEXT.userRef,
mcpServerUrl: putBodyWithDcr.url,
codeVerifier: 'stale-verifier',
- redirectUrl: null,
+ returnTo: null,
});
const newUrl = 'https://mcp.linear.app/v2/mcp';
@@ -644,20 +644,38 @@ describe('mcp-servers routers', () => {
});
it('GET /{name}/authorize short-circuits non-DCR servers and 404s unknowns', async () => {
- const noAuth = await mcpServersRouter.request('/deepwiki/authorize?redirect_url=https://example.com/callback');
+ const noAuth = await mcpServersRouter.request('/deepwiki/authorize?return_to=/settings');
expect(noAuth.status).toBe(200);
expect(await noAuth.json()).toEqual({ status: 'not_required' });
- const headerAuth = await mcpServersRouter.request(
- '/private-mcp/authorize?redirect_url=https://example.com/callback',
- );
+ const headerAuth = await mcpServersRouter.request('/private-mcp/authorize?return_to=/settings');
expect(headerAuth.status).toBe(200);
expect(await headerAuth.json()).toEqual({ status: 'authenticated' });
- const missing = await mcpServersRouter.request('/missing/authorize?redirect_url=https://example.com/callback');
+ const missing = await mcpServersRouter.request('/missing/authorize?return_to=/settings');
expect(missing.status).toBe(404);
});
+ it('GET /{name}/authorize rejects unsafe return_to values with 400', async () => {
+ await seedDcrServerWithClient();
+
+ for (const returnTo of [
+ 'https://evil.example.com/phish',
+ '//evil.example.com/phish',
+ '/api/v1/sessions',
+ '/api',
+ 'relative-not-absolute',
+ ]) {
+ const response = await mcpServersRouter.request(
+ `/${putBodyWithDcr.name}/authorize?return_to=${encodeURIComponent(returnTo)}`,
+ );
+ expect(response.status).toBe(400);
+ expect(await response.json()).toEqual({
+ error: { message: 'Invalid return_to: must be a same-origin relative path' },
+ });
+ }
+ });
+
it('GET /{name}/authorize returns 424 when upstream DCR registration fails', async () => {
const asOrigin = 'https://auth-failure.example.com';
const mcpUrl = 'https://mcp-failure.example.com/sse';
@@ -773,9 +791,7 @@ describe('mcp-servers routers', () => {
);
expect(put.status).toBe(200);
- const authorize = await mcpServersRouter.request(
- '/oauth-mcp/authorize?redirect_url=https://example.com/after-oauth',
- );
+ const authorize = await mcpServersRouter.request('/oauth-mcp/authorize?return_to=/settings/after-oauth');
expect(authorize.status).toBe(200);
const body = (await authorize.json()) as { status: string; authorization_url?: string };
expect(body.status).toBe('auth_required');
diff --git a/packages/trueforge/tests/unit/auth/safeReturnTo.test.ts b/packages/trueforge/tests/unit/auth/safeReturnTo.test.ts
new file mode 100644
index 000000000..c44d39de5
--- /dev/null
+++ b/packages/trueforge/tests/unit/auth/safeReturnTo.test.ts
@@ -0,0 +1,19 @@
+import { safeReturnTo } from '../../../src/auth/safeReturnTo';
+
+describe('safeReturnTo', () => {
+ it('returns same-origin relative paths unchanged', () => {
+ expect(safeReturnTo('/')).toBe('/');
+ expect(safeReturnTo('/settings')).toBe('/settings');
+ expect(safeReturnTo('/settings?tab=mcp&pUid=abc')).toBe('/settings?tab=mcp&pUid=abc');
+ expect(safeReturnTo('/chat')).toBe('/chat');
+ });
+
+ it('falls back to "/" for missing or unsafe values', () => {
+ expect(safeReturnTo('https://evil.example.com/')).toBe('/');
+ expect(safeReturnTo('//evil.example.com/')).toBe('/');
+ expect(safeReturnTo('/api')).toBe('/');
+ expect(safeReturnTo('/api/v1/auth/login')).toBe('/');
+ expect(safeReturnTo('relative')).toBe('/');
+ expect(safeReturnTo(undefined)).toBe('/');
+ });
+});
diff --git a/packages/trueforge/tests/unit/mcp/auth/mcpOAuth.test.ts b/packages/trueforge/tests/unit/mcp/auth/mcpOAuth.test.ts
index b450d4ce2..8d9fbe7fe 100644
--- a/packages/trueforge/tests/unit/mcp/auth/mcpOAuth.test.ts
+++ b/packages/trueforge/tests/unit/mcp/auth/mcpOAuth.test.ts
@@ -3,7 +3,6 @@
* Global fetch is stubbed; production code uses real fetch only.
*/
import { resourceUrlFromServerUrl } from '@modelcontextprotocol/sdk/shared/auth-utils.js';
-import { McpConnectionError } from '@truefoundry/trueforge-core/core';
import { InMemoryOAuthClientStore, InMemoryOAuthTokenStore } from '../../../../src/mcp/auth/inMemoryStores';
import {
buildMcpAuthorizationUrl,
@@ -13,11 +12,7 @@ import {
isMcpAuthRequired,
resolveMcpAuth,
} from '../../../../src/mcp/auth/mcpDcr';
-import {
- DEFAULT_MCP_ACCESS_TOKEN_TTL_SECONDS,
- mcpOAuthCallbackUrl,
- validateRedirectUris,
-} from '../../../../src/mcp/auth/mcpOAuthHelpers';
+import { DEFAULT_MCP_ACCESS_TOKEN_TTL_SECONDS, mcpOAuthCallbackUrl } from '../../../../src/mcp/auth/mcpOAuthHelpers';
import type { OAuthClientRecord } from '../../../../src/mcp/auth/types';
interface Stores {
@@ -311,7 +306,7 @@ describe('buildMcpAuthorizationUrl', () => {
userRef: USER_REF,
mcpServerUrl: SERVER_URL,
mcpServerName: SERVER_NAME,
- redirectUrl: 'https://app.example.com/after',
+ returnTo: '/after',
});
expect(authUrl).toBeInstanceOf(URL);
@@ -330,7 +325,7 @@ describe('buildMcpAuthorizationUrl', () => {
id: SERVER_ID,
userRef: USER_REF,
mcpServerUrl: SERVER_URL,
- redirectUrl: 'https://app.example.com/after',
+ returnTo: '/after',
});
expect(pending?.codeVerifier).toBeTruthy();
});
@@ -616,7 +611,7 @@ describe('completeMcpAuthorization', () => {
userRef: USER_REF,
mcpServerUrl: SERVER_URL,
mcpServerName: SERVER_NAME,
- redirectUrl: 'https://app.example.com/connected',
+ returnTo: '/connected',
});
const state = authUrl.searchParams.get('state')!;
@@ -633,7 +628,7 @@ describe('completeMcpAuthorization', () => {
if (!pending) {
throw new Error('expected buildMcpAuthorizationUrl to save a pending authorization');
}
- expect(pending.redirectUrl).toBe('https://app.example.com/connected');
+ expect(pending.returnTo).toBe('/connected');
const beforeMs = Date.now();
await completeMcpAuthorization({
@@ -672,7 +667,7 @@ describe('completeMcpAuthorization', () => {
userRef: USER_REF,
mcpServerUrl: SERVER_URL,
codeVerifier: 'verifier-1',
- redirectUrl: null,
+ returnTo: null,
},
code: 'code',
}),
@@ -693,7 +688,7 @@ describe('completeMcpAuthorization', () => {
userRef: USER_REF,
mcpServerUrl: SERVER_URL,
mcpServerName: SERVER_NAME,
- redirectUrl: 'https://app.example.com/after',
+ returnTo: '/after',
});
const state = authUrl.searchParams.get('state')!;
@@ -725,21 +720,3 @@ describe('completeMcpAuthorization', () => {
expect(await stores.mcpServerStore.getClient({ id: SERVER_ID })).toBeUndefined();
});
});
-
-describe('validateRedirectUris', () => {
- it('accepts http(s) URLs', () => {
- expect(() =>
- validateRedirectUris({
- redirectUris: ['https://harness.example.com/settings', 'http://localhost:3000/cb'],
- }),
- ).not.toThrow();
- });
-
- it('rejects non-http(s) URIs', () => {
- expect(() => validateRedirectUris({ redirectUris: ['javascript:alert(1)'] })).toThrow(/Must be a valid URL/);
- });
-
- it('rejects malformed URIs', () => {
- expect(() => validateRedirectUris({ redirectUris: ['not-a-url'] })).toThrow(McpConnectionError);
- });
-});
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 30f653c47..a594ff06e 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -61,8 +61,8 @@ importers:
specifier: 0.2.21
'@truefoundry/assistant-ui-runtime':
- specifier: 0.1.18
+ specifier: 0.1.20
'@truefoundry/trueforge-sdk':
specifier: workspace:*
version: link:../trueforge-sdk
@@ -371,8 +371,8 @@ importers:
specifier: ^0.13.2
'@truefoundry/assistant-ui-runtime':
- specifier: 0.1.18
+ specifier: 0.1.20
'@truefoundry/trueforge-sdk':
specifier: workspace:*
version: link:../trueforge-sdk
@@ -3480,8 +3480,8 @@ packages:
'@types/react-dom':
optional: true
- '@truefoundry/[email protected]':
- resolution: {integrity: sha512-xiEp2UwJfjqtRh2HmDLhyy5oBx4UOgKvxkOi4sYziTmStWNRg8JDTFoADu3ZV3Qr4MwRb8abQc1eoXvjzVoRNA==}
+ '@truefoundry/[email protected]':
+ resolution: {integrity: sha512-yJnc/YRiOy1otjMZMftGL0VUaJEc4md9LFlFwrz16yoW6poIhyAohNWjlZ/+5KiEenQCQLeQNr2WFDGdw3U3XQ==}
peerDependencies:
'@types/react': '*'
react: ^18 || ^19
@@ -10626,7 +10626,7 @@ snapshots:
'@types/react': 19.2.17
'@types/react-dom': 19.2.3(@types/[email protected])
dependencies:
'@assistant-ui/store': 0.2.21(@assistant-ui/[email protected](@types/[email protected])([email protected]))(@types/[email protected])([email protected])