Skip to content

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

Resolve ui proxy path from PUBLIC_BASE_URL at runtime instead of build time (#651)

Chirag Jaine307f15cb2d1
diff --git a/.changeset/runtime-ui-base-path.md b/.changeset/runtime-ui-base-path.md
new file mode 100644
index 000000000..840dd6302
--- /dev/null
+++ b/.changeset/runtime-ui-base-path.md
@@ -0,0 +1,5 @@
+---
+"@truefoundry/trueforge": patch
+---
+
+Derive the UI public prefix from the pathname of `PUBLIC_BASE_URL` at process start so one published frontend can run behind any path-stripping proxy.
diff --git a/.github/fern/openapi/openapi.json b/.github/fern/openapi/openapi.json
index e66a00e41..b15204a60 100644
--- a/.github/fern/openapi/openapi.json
+++ b/.github/fern/openapi/openapi.json
@@ -5667,12 +5667,12 @@
"description": "Redirects the browser to the configured identity provider. In local/single-binary mode, redirects straight back into the app — there is nothing to log into.",
"parameters": [
{
- "description": "Path to return to after login. Must be a same-origin relative path; anything else falls back to \"/\".",
+ "description": "Path to return to after login. Same-origin relative path; otherwise the public UI home.",
"in": "query",
"name": "return_to",
"required": false,
"schema": {
- "description": "Path to return to after login. Must be a same-origin relative path; anything else falls back to \"/\".",
+ "description": "Path to return to after login. Same-origin relative path; otherwise the public UI home.",
"type": "string"
}
}
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 45727e557..cc75166fc 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -155,7 +155,7 @@ See [`packages/trueforge/.env.example`](packages/trueforge/.env.example) for eve
- `PORT` - API port (default `8790`)
- `FRONTEND_PORT` - Vite UI port in dev (default `3000`); see [`packages/frontend/README.md`](packages/frontend/README.md)
- `VITE_SERVER_URL` - point the Vite proxy at a different API
-- `PUBLIC_BASE_URL` - public origin for MCP OAuth / OIDC callbacks. Required for `pnpm standalone:dev` / `pnpm dev` and for distributed mode (e.g. `http://localhost:3000` for Vite). Non-development standalone falls back to `http://localhost:$PORT`.
+- `PUBLIC_BASE_URL` - public application URL for MCP OAuth / OIDC callbacks. Required for `pnpm standalone:dev` / `pnpm dev` and for distributed mode (e.g. `http://localhost:3000` for Vite). Non-development standalone falls back to `http://localhost:$PORT`.
- `FRONTEND_DIR` - directory of a built UI for the server to serve
- `SQLITE_PATH` - SQLite file location in standalone mode
- `REDIS_URL` / `POSTGRES_*` - used when `STANDALONE=false`
diff --git a/Dockerfile.dev b/Dockerfile.dev
index f2401de9f..60ac1b891 100644
--- a/Dockerfile.dev
+++ b/Dockerfile.dev
@@ -63,9 +63,6 @@ RUN pnpm --filter @truefoundry/trueforge-core build && pnpm --filter @truefoundr
# tsc needs, so this stage never compiles SDK JavaScript.
# ---------------------------------------------------------------------------
FROM workspace AS frontend-builder
-# Optional UI public path for reverse-proxy mounts (e.g. /trueforge). See VITE_BASE_PATH.
-ARG VITE_BASE_PATH=/
-ENV VITE_BASE_PATH=$VITE_BASE_PATH
RUN pnpm install --frozen-lockfile --offline --filter frontend...
COPY packages/trueforge-sdk packages/trueforge-sdk
COPY packages/trueforge-ui packages/trueforge-ui
diff --git a/charts/trueforge/README.md b/charts/trueforge/README.md
index d1122ead7..275c9e48a 100644
--- a/charts/trueforge/README.md
+++ b/charts/trueforge/README.md
@@ -120,8 +120,10 @@ shared or public deployment. When enabled, set string `issuerUrl` and
`clientId`, and `clientSecret` as a string or `valueFrom.secretKeyRef`
(prefer valueFrom in production).
-Also set `server.publicBaseUrl` to the public origin and register
-`{publicBaseUrl}/api/v1/auth/callback` at your IdP.
+Also set `server.publicBaseUrl` to the public application URL (origin plus
+optional pathname) and register `{publicBaseUrl}/api/v1/auth/callback` at your IdP.
+A pathname such as `https://host/custom/proxy/path` is the UI/API public prefix when a reverse
+proxy strips it.
```yaml
server:
@@ -199,7 +201,7 @@ extraObjects:
| `server.replicaCount` | `1` | Number of server replicas. |
| `image.repository` | `tfy.jfrog.io/tfy-images/trueforge` | Image repository. |
| `image.tag` | chart `appVersion` | Image tag; stamped on release. |
-| `server.publicBaseUrl`| `""` | Public origin for OAuth/OIDC callbacks (required for MCP OAuth / OIDC). |
+| `server.publicBaseUrl`| `""` | Public application URL for OAuth/OIDC callbacks (required for MCP OAuth / OIDC). A pathname is the UI/API public prefix. |
| `configs.oidc.enabled`| `false` | Inject `OIDC_*` env for IdP login. |
| `postgresql.enabled` | `true` | Bundle the Bitnami Postgres subchart. |
| `redis.enabled` | `true` | Bundle the Bitnami Redis subchart. |
@@ -232,7 +234,7 @@ also sets the `/tmp` `emptyDir.sizeLimit`.
- **Enable `configs.oidc`** — leaving it off grants shared admin to anyone who can reach the server.
- **Replace the bundled Postgres password** (`trueforge`) or set `postgresql.auth.existingSecret`.
- Treat bundled Redis (`redis.auth.enabled: false`) as cluster-internal only, or switch to external passworded Redis via `externalRedis.url`.
-- Set `server.publicBaseUrl` to the real public origin before using MCP OAuth or OIDC.
+- Set `server.publicBaseUrl` to the real public application URL before using MCP OAuth or OIDC (include a pathname when the UI is served under a stripped prefix).
- Prefer `valueFrom.secretKeyRef` for Postgres password, Redis URL, and OIDC client secret; do not commit secrets in values files.
- Prefer external managed Postgres/Redis over the bundled subcharts for production HA.
- If enabling `mtls`, set `mtls.secretName` and ensure any reverse proxy dials HTTPS with a trusted client cert (see Caddy `internal_mtls`).
diff --git a/charts/trueforge/templates/NOTES.txt b/charts/trueforge/templates/NOTES.txt
index 739092f63..5a468fbc2 100644
--- a/charts/trueforge/templates/NOTES.txt
+++ b/charts/trueforge/templates/NOTES.txt
@@ -41,7 +41,7 @@ OIDC callbacks require PUBLIC_BASE_URL. Register
https://<your-public-origin>/api/v1/auth/callback at your IdP.
{{- else if not .Values.server.publicBaseUrl }}
-WARNING: server.publicBaseUrl is empty. MCP OAuth and OIDC callbacks will fail until you set it to the public origin (e.g. https://trueforge.example.com).
+WARNING: server.publicBaseUrl is empty. MCP OAuth and OIDC callbacks will fail until you set it to the public application URL (e.g. https://trueforge.example.com or https://host/custom/proxy/path).
{{- end }}
{{- if and (not .Values.postgresql.enabled) (not .Values.externalPostgres.host) }}
diff --git a/charts/trueforge/values.yaml b/charts/trueforge/values.yaml
index c8b8f21c6..d705ab9b2 100644
--- a/charts/trueforge/values.yaml
+++ b/charts/trueforge/values.yaml
@@ -51,8 +51,9 @@ server:
maxSurge: 1
# Container port the server listens on (PORT).
port: 8790
- # Public origin for MCP OAuth / OIDC callbacks (PUBLIC_BASE_URL).
- # Required for OIDC and MCP OAuth to work correctly.
+ # Public application URL for MCP OAuth / OIDC callbacks (PUBLIC_BASE_URL).
+ # May include a pathname (e.g. https://host/custom/proxy/path); that path is the UI/API
+ # public prefix when a reverse proxy strips it. Required for OIDC and MCP OAuth.
publicBaseUrl: ""
# Seconds the server is given to drain turns on SIGTERM (GRACEFUL_TIMEOUT_SECONDS).
gracefulTimeoutSeconds: 30
diff --git a/docs/openapi.json b/docs/openapi.json
index e66a00e41..b15204a60 100644
--- a/docs/openapi.json
+++ b/docs/openapi.json
@@ -5667,12 +5667,12 @@
"description": "Redirects the browser to the configured identity provider. In local/single-binary mode, redirects straight back into the app — there is nothing to log into.",
"parameters": [
{
- "description": "Path to return to after login. Must be a same-origin relative path; anything else falls back to \"/\".",
+ "description": "Path to return to after login. Same-origin relative path; otherwise the public UI home.",
"in": "query",
"name": "return_to",
"required": false,
"schema": {
- "description": "Path to return to after login. Must be a same-origin relative path; anything else falls back to \"/\".",
+ "description": "Path to return to after login. Same-origin relative path; otherwise the public UI home.",
"type": "string"
}
}
diff --git a/packages/frontend/index.html b/packages/frontend/index.html
index 7dcfb96b9..326b2f661 100644
--- a/packages/frontend/index.html
+++ b/packages/frontend/index.html
@@ -4,6 +4,9 @@
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>TrueForge</title>
+ <script>
+ window.__TRUEFORGE_BASE_PATH__ = '%%TRUEFORGE_BASE_PATH%%';
+ </script>
</head>
<body>
<div id="root"></div>
diff --git a/packages/frontend/src/App.tsx b/packages/frontend/src/App.tsx
index 691fe4497..a1768b6e0 100644
--- a/packages/frontend/src/App.tsx
+++ b/packages/frontend/src/App.tsx
@@ -23,7 +23,7 @@ import { API_BASE_URL, uiRouterBasename } from './publicPath';
/** Shared cookie/OIDC fetch for boot helpers and `<TrueForgeUI server />`. */
const authAwareFetch = createAuthAwareFetch();
-// UI + API share `VITE_BASE_PATH` / `BASE_URL`; Caddy strips it before Harness.
+// UI + API share the public prefix from `window.__TRUEFORGE_BASE_PATH__`.
const bootClient = createTrueForgeClient({ baseUrl: API_BASE_URL, fetch: authAwareFetch });
const routerBasename = uiRouterBasename();
diff --git a/packages/frontend/src/authFetch.ts b/packages/frontend/src/authFetch.ts
index 8c99c911c..2f75b89f6 100644
--- a/packages/frontend/src/authFetch.ts
+++ b/packages/frontend/src/authFetch.ts
@@ -2,9 +2,9 @@
* Browser auth entry points. Login and logout are not SDK methods (cookie session).
* On any HTTP 401, redirect to OIDC login (session required).
*
- * Auth URLs share `VITE_BASE_PATH` with the UI (e.g. `/trueforge/api/v1/auth/...`).
- * Caddy strips that prefix before Harness. Pass `return_to` so post-login lands
- * back under the UI path.
+ * Auth URLs share the public prefix with the UI (e.g. `/custom/proxy/path/api/v1/auth/...`).
+ * A reverse proxy strips that prefix before Harness. Pass `return_to` so post-login
+ * lands back under the UI path.
*/
import { apiPath, UI_BASE_PATH } from './publicPath';
diff --git a/packages/frontend/src/main.tsx b/packages/frontend/src/main.tsx
index 30e314522..c8aadfa65 100644
--- a/packages/frontend/src/main.tsx
+++ b/packages/frontend/src/main.tsx
@@ -2,6 +2,9 @@ import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import { App } from './App';
import './index.css';
+import { installMonacoWorkerPublicPath } from './publicPath';
+
+installMonacoWorkerPublicPath();
const root = document.getElementById('root');
if (!root) {
diff --git a/packages/frontend/src/publicPath.ts b/packages/frontend/src/publicPath.ts
index e72a8a025..8db061161 100644
--- a/packages/frontend/src/publicPath.ts
+++ b/packages/frontend/src/publicPath.ts
@@ -1,15 +1,33 @@
/**
- * Public path from Vite `base` (`VITE_BASE_PATH`). Always `/` or a path with a
- * trailing slash (e.g. `/trueforge/`). UI assets, React Router, and API/auth
- * share this prefix; Caddy strips it before Harness so the server still sees
- * `/` and `/api/...`.
+ * Public path from `window.__TRUEFORGE_BASE_PATH__` (the server substitutes
+ * `PUBLIC_BASE_URL`'s pathname into the app shell). Always `/` or a path with a
+ * trailing slash (e.g. `/custom/proxy/path/`). UI assets, React Router, and API/auth share
+ * this prefix; a reverse proxy strips it so the server still sees `/` and `/api/...`.
*/
-export const UI_BASE_PATH =
- typeof import.meta.env === 'object' &&
- typeof import.meta.env.BASE_URL === 'string' &&
- import.meta.env.BASE_URL.length > 0
- ? import.meta.env.BASE_URL
- : '/';
+declare global {
+ interface Window {
+ __TRUEFORGE_BASE_PATH__?: string;
+ MonacoEnvironment?: {
+ globalAPI?: boolean;
+ getWorkerUrl?: (moduleId: string, label: string) => string;
+ };
+ }
+}
+
+const SHELL_BASE_TOKEN = '%%TRUEFORGE_BASE_PATH%%';
+
+function documentUiBasePath(): string {
+ if (typeof window === 'undefined') {
+ return '/';
+ }
+ const href = window.__TRUEFORGE_BASE_PATH__?.trim();
+ if (href === undefined || href === '' || href.includes(SHELL_BASE_TOKEN)) {
+ return '/';
+ }
+ return href.endsWith('/') ? href : `${href}/`;
+}
+
+export const UI_BASE_PATH = documentUiBasePath();
/** SDK `baseUrl` — same public prefix as the UI. */
export const API_BASE_URL = UI_BASE_PATH;
@@ -27,3 +45,36 @@ export function apiPath(suffix: string): string {
}
return `${UI_BASE_PATH.replace(/\/$/, '')}${path}`;
}
+
+const MONACO_WORKER_DIR = 'monacoeditorwork';
+
+/** Origin-absolute Monaco worker URL, including the public UI prefix. */
+export function monacoWorkerUrl(filename: string): string {
+ const name = filename.split('/').pop();
+ if (name === undefined || name === '') {
+ return `${UI_BASE_PATH}${MONACO_WORKER_DIR}/`;
+ }
+ return `${UI_BASE_PATH}${MONACO_WORKER_DIR}/${name}`;
+}
+
+/**
+ * vite-plugin-monaco-editor-esm emits worker URLs from Vite `base` (`./` in
+ * production), so they stay page-relative. Rewrite them through the public
+ * prefix before Monaco loads a worker on a nested client route.
+ */
+export function installMonacoWorkerPublicPath(): void {
+ if (typeof window === 'undefined') {
+ return;
+ }
+ const previous = window.MonacoEnvironment?.getWorkerUrl;
+ window.MonacoEnvironment = {
+ ...window.MonacoEnvironment,
+ getWorkerUrl(moduleId: string, label: string) {
+ const raw = previous?.call(window.MonacoEnvironment, moduleId, label);
+ if (typeof raw === 'string' && raw.length > 0) {
+ return monacoWorkerUrl(raw);
+ }
+ return monacoWorkerUrl(`${label}.worker.bundle.js`);
+ },
+ };
+}
diff --git a/packages/frontend/tests/publicPath.test.ts b/packages/frontend/tests/publicPath.test.ts
index 86669c806..1620710a4 100644
--- a/packages/frontend/tests/publicPath.test.ts
+++ b/packages/frontend/tests/publicPath.test.ts
@@ -2,7 +2,7 @@ import assert from 'node:assert/strict';
import { describe, it } from 'node:test';
import { API_BASE_URL, apiPath, UI_BASE_PATH, uiRouterBasename } from '../src/publicPath';
-describe('publicPath (default Vite BASE_URL=/)', () => {
+describe('publicPath (default public prefix=/)', () => {
it('shares one public prefix for UI and API', () => {
assert.equal(UI_BASE_PATH, '/');
assert.equal(API_BASE_URL, UI_BASE_PATH);
diff --git a/packages/frontend/vite.config.ts b/packages/frontend/vite.config.ts
index 2658f2bd4..7e8c22eef 100644
--- a/packages/frontend/vite.config.ts
+++ b/packages/frontend/vite.config.ts
@@ -1,7 +1,7 @@
import react from '@vitejs/plugin-react';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
-import type { ProxyOptions } from 'vite';
+import type { Plugin, ProxyOptions } from 'vite';
import { defaultClientConditions, defineConfig } from 'vite';
import { compression } from 'vite-plugin-compression2';
// Maintained ESM fork of vite-plugin-monaco-editor (works with Vite 6 ESM config).
@@ -16,17 +16,8 @@ if (!Number.isInteger(PORT)) {
throw new Error(`FRONTEND_PORT must be an integer, got "${process.env.FRONTEND_PORT}"`);
}
-/** Optional public path (e.g. `/trueforge`). Empty/unset → `/`. Vite requires a trailing slash. */
-function resolveViteBase(raw: string | undefined): string {
- const trimmed = raw?.trim();
- if (trimmed === undefined || trimmed === '' || trimmed === '/') {
- return '/';
- }
- const withLead = trimmed.startsWith('/') ? trimmed : `/${trimmed}`;
- return withLead.endsWith('/') ? withLead : `${withLead}/`;
-}
-
-const BASE = resolveViteBase(process.env.VITE_BASE_PATH);
+/** Vite writes this into the production shell; the server substitutes at process start. Must not appear in JS identifiers. */
+const SHELL_BASE_TOKEN = '%%TRUEFORGE_BASE_PATH%%';
const apiProxy: ProxyOptions = {
target: SERVER,
@@ -42,32 +33,28 @@ const apiProxy: ProxyOptions = {
},
};
-/** When UI+API share a public path, strip it so Harness still sees `/api`. */
-const prefixedApiProxy: ProxyOptions =
- BASE === '/'
- ? apiProxy
- : {
- ...apiProxy,
- rewrite: requestPath => requestPath.slice(BASE.length - 1),
- };
-
-const proxy: Record<string, ProxyOptions> =
- BASE === '/'
- ? {
- '/api': apiProxy,
- }
- : {
- // Prefer the prefixed keys so `/trueforge/api` is not matched as a bare `/api` miss.
- [`${BASE}api`]: prefixedApiProxy,
- '/api': apiProxy,
- };
+function shellBaseTokenPlugin(): Plugin {
+ return {
+ name: 'trueforge-shell-base-token',
+ transformIndexHtml: {
+ order: 'post',
+ handler(html) {
+ return html
+ .replaceAll('src="./assets/', `src="${SHELL_BASE_TOKEN}assets/`)
+ .replaceAll('href="./assets/', `href="${SHELL_BASE_TOKEN}assets/`);
+ },
+ },
+ };
+}
-export default defineConfig({
- base: BASE,
+export default defineConfig(({ command }) => ({
+ base: command === 'build' ? './' : '/',
plugins: [
react(),
monacoEditorPlugin({
languageWorkers: ['editorWorkerService', 'css', 'html', 'json', 'typescript'],
+ // Production `base` is `./`; without this the plugin writes workers under `./monacoeditorwork`.
+ customDistPath: (root, buildOutDir) => path.join(root, buildOutDir, 'monacoeditorwork'),
}),
// The server serves these siblings instead of compressing per request.
compression({
@@ -75,6 +62,7 @@ export default defineConfig({
threshold: 1024,
skipIfLargerOrEqual: true,
}),
+ ...(command === 'build' ? [shellBaseTokenPlugin()] : []),
],
// Single React / assistant-ui Context instance (avoids "requires an AuiProvider").
resolve: {
@@ -93,6 +81,6 @@ export default defineConfig({
// Fail if FRONTEND_PORT is taken — never silently hop to 3001/3010/etc.
strictPort: true,
// Proxy API routes (including /api/internal) to the Harness.
- proxy,
+ proxy: { '/api': apiProxy },
},
-});
+}));
diff --git a/packages/trueforge/.env.example b/packages/trueforge/.env.example
index 3766f9e44..1dccca6ff 100644
--- a/packages/trueforge/.env.example
+++ b/packages/trueforge/.env.example
@@ -118,8 +118,10 @@ REDIS_URL=redis://localhost:6379
## A subscribe request stays open for 10 minutes by default.
# TURN_SUBSCRIBE_TIMEOUT_MS=600000
-## Used when STANDALONE=false (ignored in standalone). Public origin of the
-## fixed callback routes for server OIDC and MCP OAuth/DCR.
+## Used when STANDALONE=false (ignored in standalone). Public URL of the app
+## (origin plus optional pathname). Callbacks for server OIDC and MCP OAuth/DCR
+## use this value. The pathname is the UI/API public prefix when a reverse proxy
+## strips it (e.g. https://host/custom/proxy/path → assets/API/routes under /custom/proxy/path).
# PUBLIC_BASE_URL=http://localhost:3000
## Base URL the dedicated controller process (dist/controller-main.js) uses to
diff --git a/packages/trueforge/src/apis/auth.ts b/packages/trueforge/src/apis/auth.ts
index c7a89c599..cb501ad48 100644
--- a/packages/trueforge/src/apis/auth.ts
+++ b/packages/trueforge/src/apis/auth.ts
@@ -8,12 +8,13 @@ import { resolveRequestContext } from '../auth/identity';
import { resolveOidcRequestContext } from '../auth/middleware';
import { buildLoginAuthorization, exchangeAuthorizationCode } from '../auth/oidc';
import { safeReturnTo } from '../auth/safeReturnTo';
+import { getPublicUiBasePath } from '../config';
import { authLoginRoute, authLogoutRoute, meRoute, oAuthCallbackRoute } from '../routes/authRoutes';
import type { GetMeResponse } from '../schemas/auth';
-/** Login / OIDC failures land on `/?error=<reason>`. */
+/** Login / OIDC failures land on the public UI home with `?error=<reason>`. */
function oauthErrorRedirect(reason: string): string {
- return `/?error=${encodeURIComponent(reason)}`;
+ return `${getPublicUiBasePath()}?error=${encodeURIComponent(reason)}`;
}
/**
@@ -50,7 +51,7 @@ export function createAuthRouter(params: {
router.openapi(authLoginRoute, async c => {
// TODO: remove this checks once the middleware is implemented
if (!params.oidcClient) {
- return c.redirect('/', 302);
+ return c.redirect(getPublicUiBasePath(), 302);
}
try {
@@ -68,7 +69,7 @@ export function createAuthRouter(params: {
router.openapi(oAuthCallbackRoute, async c => {
if (!params.oidcClient) {
- return c.redirect('/', 302);
+ return c.redirect(getPublicUiBasePath(), 302);
}
const query = c.req.valid('query');
@@ -77,7 +78,10 @@ export function createAuthRouter(params: {
if (pending?.state !== query.state || query.error || !query.code) {
// If already authenticated, redirect home instead of showing an error.
- const soft = await redirectIfAlreadyAuthenticated({ context: c, whenAuthenticated: '/' });
+ const soft = await redirectIfAlreadyAuthenticated({
+ context: c,
+ whenAuthenticated: getPublicUiBasePath(),
+ });
if (soft) {
return soft;
}
diff --git a/packages/trueforge/src/app.ts b/packages/trueforge/src/app.ts
index b26d54f21..dc2c5afb2 100644
--- a/packages/trueforge/src/app.ts
+++ b/packages/trueforge/src/app.ts
@@ -31,7 +31,7 @@ import type { McpCatalog } from './catalog/McpCatalog';
import type { ModelCatalog } from './catalog/ModelCatalog';
import type { SandboxCatalog } from './catalog/SandboxCatalog';
import type { SkillCatalog } from './catalog/SkillCatalog';
-import configuration, { getTrueForgeAuthMode, TrueForgeAuthMode } from './config';
+import configuration, { getPublicUiBasePath, getTrueForgeAuthMode, TrueForgeAuthMode } from './config';
import type { AgentRecord, IAgentStore } from './db/agentStore';
import type { IMcpServerWithAuthStore } from './db/mcpServerStore';
import type { IModelProviderStore } from './db/modelProviderStore';
@@ -145,15 +145,18 @@ export function registerOpenApiBearerAuth(app: OpenAPIHono): void {
/**
* Single source for both the served document and the one the SDK is built from.
* When `authEnabled`, advertises required Bearer auth on operations that inherit global security.
+ * `serverUrl` is the public prefix for Try it out (e.g. `/custom/proxy/path`); omit for the SDK spec.
*/
-export function buildOpenApiDocument(app: OpenAPIHono, options?: { authEnabled?: boolean }) {
+export function buildOpenApiDocument(app: OpenAPIHono, options?: { authEnabled?: boolean; serverUrl?: string }) {
const authEnabled = options?.authEnabled ?? false;
if (authEnabled) {
registerOpenApiBearerAuth(app);
}
+ const serverUrl = options?.serverUrl;
return app.getOpenAPI31Document({
...openApiDocConfig,
...(authEnabled ? { security: [{ [BEARER_AUTH_SCHEME]: [] }] } : {}),
+ ...(serverUrl !== undefined && serverUrl !== '' ? { servers: [{ url: serverUrl }] } : {}),
});
}
@@ -422,8 +425,18 @@ export function createServerApp<TTransaction>(deps: ServerDeps<TTransaction>) {
),
);
- app.get('/api/v1/docs', swaggerUI({ url: '/api/v1/openapi.json' }));
- app.get('/api/v1/openapi.json', c => c.json(buildOpenApiDocument(app, { authEnabled })));
+ const uiBasePath = getPublicUiBasePath();
+ const openApiSpecPath = `${uiBasePath}api/v1/openapi.json`;
+ const openApiServerUrl = uiBasePath === '/' ? undefined : uiBasePath.replace(/\/$/, '');
+ app.get('/api/v1/docs', swaggerUI({ url: openApiSpecPath }));
+ app.get('/api/v1/openapi.json', c =>
+ c.json(
+ buildOpenApiDocument(app, {
+ authEnabled,
+ ...(openApiServerUrl === undefined ? {} : { serverUrl: openApiServerUrl }),
+ }),
+ ),
+ );
app.notFound(routeNotFound);
diff --git a/packages/trueforge/src/auth/safeReturnTo.ts b/packages/trueforge/src/auth/safeReturnTo.ts
index 3be30bf4d..3d897eef4 100644
--- a/packages/trueforge/src/auth/safeReturnTo.ts
+++ b/packages/trueforge/src/auth/safeReturnTo.ts
@@ -1,3 +1,5 @@
+import { getPublicUiBasePath } from '../config';
+
/**
* Same-origin relative path only.
* - starts with `/`
@@ -10,10 +12,10 @@ function isSafeReturnTo(value: string): boolean {
return SAFE_RETURN_TO.test(value);
}
-/** Same-origin path, or `/` when missing or unsafe. */
+/** Same-origin path, or the public UI home when missing or unsafe. */
export function safeReturnTo(value: string | undefined): string {
if (value && isSafeReturnTo(value)) {
return value;
}
- return '/';
+ return getPublicUiBasePath();
}
diff --git a/packages/trueforge/src/config.ts b/packages/trueforge/src/config.ts
index 74f0ebb9e..780e06b4f 100644
--- a/packages/trueforge/src/config.ts
+++ b/packages/trueforge/src/config.ts
@@ -141,6 +141,31 @@ function parseBoolean(options: { envKey: string; raw: string | undefined; defaul
throw new Error(`Environment variable ${envKey} must be "true" or "false", got "${raw}"`);
}
+/**
+ * Empty stays empty. Otherwise parse as a URL, store without a trailing slash
+ * (callers join with `/`), and reject query/hash or `.` / `..` path segments.
+ */
+function parsePublicBaseUrl(raw: string | undefined): string {
+ if (raw === undefined || raw.trim() === '') {
+ return '';
+ }
+ let parsed: URL;
+ try {
+ parsed = new URL(raw.trim());
+ } catch (error) {
+ throw new Error('PUBLIC_BASE_URL must be a valid URL', { cause: error });
+ }
+ if (parsed.search !== '' || parsed.hash !== '') {
+ throw new Error('PUBLIC_BASE_URL must not include a query or hash');
+ }
+ const segments = parsed.pathname.split('/').filter(part => part.length > 0);
+ if (segments.some(part => part === '.' || part === '..')) {
+ throw new Error('PUBLIC_BASE_URL path must not contain "." or ".." segments');
+ }
+ const path = segments.length === 0 ? '' : `/${segments.join('/')}`;
+ return `${parsed.origin}${path}`;
+}
+
function parseTrueFoundrySandboxProvider(raw: string | undefined): 'daytona' | 'truefoundry' | undefined {
if (raw === undefined || raw.trim() === '') {
return undefined;
@@ -483,9 +508,10 @@ export interface SharedServerConfiguration {
*/
REDIS_REQUEST_REPLY_POLL_INTERVAL_MS: number;
/**
- * Public base URL used as the origin of MCP OAuth and OIDC callbacks.
- * Optional at boot; MCP OAuth and OIDC callback construction fail if empty
- * outside standalone development. Env: `PUBLIC_BASE_URL`.
+ * Public application URL (origin plus optional pathname). Used as the origin of
+ * MCP OAuth and OIDC callbacks; the pathname is the UI/API public prefix when
+ * a reverse proxy strips it. Optional at boot; MCP OAuth and OIDC callback
+ * construction fail if empty outside standalone development. Env: `PUBLIC_BASE_URL`.
*/
PUBLIC_BASE_URL: string;
/**
@@ -720,7 +746,7 @@ const shared: SharedServerConfiguration = {
raw: getEnv('REDIS_REQUEST_REPLY_POLL_INTERVAL_MS'),
defaultValue: 500,
}),
- PUBLIC_BASE_URL: getEnv('PUBLIC_BASE_URL', { defaultValue: '' }) ?? '',
+ PUBLIC_BASE_URL: parsePublicBaseUrl(getEnv('PUBLIC_BASE_URL', { defaultValue: '' })),
SERVER_URL:
getEnv('SERVER_URL', { defaultValue: `http://localhost:${String(port)}` }) ?? `http://localhost:${String(port)}`,
TRUEFORGE_MTLS_ENABLED: parseBoolean({
@@ -879,19 +905,40 @@ if (isTrueFoundryModeEnabled(configuration)) {
}
}
+/**
+ * Effective public application URL. Empty `PUBLIC_BASE_URL` stays empty
+ * (callers that need a callback origin throw).
+ */
+function effectivePublicBaseUrl(config: ServerConfiguration): string {
+ // Standalone production is one process on $PORT. Ignore a leftover Vite
+ // PUBLIC_BASE_URL (e.g. http://localhost:3000) from the shared .env.
+ if (config.STANDALONE && config.NODE_ENV !== 'development') {
+ return `http://localhost:${String(config.PORT)}`;
+ }
+ return config.PUBLIC_BASE_URL;
+}
+
/**
* Public origin for OAuth callbacks.
* Standalone (non-development) → `http://localhost:$PORT`; otherwise `PUBLIC_BASE_URL`
* (required in development and distributed; throws if empty).
*/
export function getPublicBaseUrl(config: ServerConfiguration = configuration): string {
- if (config.STANDALONE && config.NODE_ENV !== 'development') {
- return `http://localhost:${String(config.PORT)}`;
- }
- if (config.PUBLIC_BASE_URL === '') {
+ const publicBaseUrl = effectivePublicBaseUrl(config);
+ if (publicBaseUrl === '') {
throw new Error('PUBLIC_BASE_URL is required for OIDC callbacks but was empty');
}
- return config.PUBLIC_BASE_URL;
+ return publicBaseUrl;
+}
+
+/** `/` or `/custom/proxy/path/` — trailing slash for asset URLs and the boot script. Empty / standalone non-dev → `/`. */
+export function getPublicUiBasePath(config: ServerConfiguration = configuration): string {
+ const publicBaseUrl = effectivePublicBaseUrl(config);
+ if (publicBaseUrl === '') {
+ return '/';
+ }
+ const path = new URL(publicBaseUrl).pathname;
+ return path === '/' ? '/' : `${path}/`;
}
export default configuration;
diff --git a/packages/trueforge/src/frontend.ts b/packages/trueforge/src/frontend.ts
index 7acf61425..cbaf39041 100644
--- a/packages/trueforge/src/frontend.ts
+++ b/packages/trueforge/src/frontend.ts
@@ -4,7 +4,7 @@ import type { OpenAPIHono } from '@hono/zod-openapi';
import type { MiddlewareHandler } from 'hono';
import { every } from 'hono/combine';
import { compress } from 'hono/compress';
-import { existsSync } from 'node:fs';
+import { existsSync, readFileSync } from 'node:fs';
import path from 'node:path';
/** Routes the server answers itself; never served from the build. /api covers every version below it. */
@@ -15,21 +15,47 @@ const HASHED_ASSET_PREFIX = '/assets/';
const IMMUTABLE_CACHE_CONTROL = 'public, max-age=31536000, immutable';
const REVALIDATE_CACHE_CONTROL = 'no-cache';
+/** Vite writes this into the production shell; replaced once at process start. Must not appear in JS identifiers. */
+const SHELL_BASE_TOKEN = '%%TRUEFORGE_BASE_PATH%%';
+
function isServerPath(pathname: string): boolean {
return SERVER_PATH_PREFIXES.some(prefix => pathname === prefix || pathname.startsWith(`${prefix}/`));
}
+function isAppShellPath(pathname: string): boolean {
+ return pathname === '/' || pathname === '/index.html';
+}
+
+function applyPublicUiBase(options: { html: string; uiBasePath: string }): string {
+ return options.html.replaceAll(SHELL_BASE_TOKEN, options.uiBasePath);
+}
+
+function createShellResponse(options: { html: string; method: string }): Response {
+ const headers = new Headers({
+ 'Content-Type': 'text/html; charset=utf-8',
+ 'Cache-Control': REVALIDATE_CACHE_CONTROL,
+ Vary: 'Accept-Encoding',
+ });
+ if (options.method === 'HEAD') {
+ return new Response(null, { status: 200, headers });
+ }
+ return new Response(options.html, { status: 200, headers });
+}
+
/**
* Must be called after the API routes are registered, so those always win over the static handler.
* Returns false when `dir` holds no build, leaving the server API-only for UI work behind Vite.
*/
-export function mountFrontend(app: OpenAPIHono, dir: string): boolean {
- if (!existsSync(path.join(dir, 'index.html'))) {
+export function mountFrontend(app: OpenAPIHono, options: { dir: string; uiBasePath: string }): boolean {
+ const indexPath = path.join(options.dir, 'index.html');
+ if (!existsSync(indexPath)) {
return false;
}
+ const shellHtml = applyPublicUiBase({ html: readFileSync(indexPath, 'utf8'), uiBasePath: options.uiBasePath });
+
// serveStatic joins `root` with the request path, so an absolute dir is working-directory proof.
- const serveFile = serveStatic({ root: dir, precompressed: true });
+ const serveFile = serveStatic({ root: options.dir, precompressed: true });
const serveWithCacheHeaders: MiddlewareHandler = async (c, next) => {
const response = await serveFile(c, next);
@@ -59,11 +85,12 @@ export function mountFrontend(app: OpenAPIHono, dir: string): boolean {
if (c.req.method !== 'GET' && c.req.method !== 'HEAD') {
return next();
}
+ if (isAppShellPath(c.req.path)) {
+ return createShellResponse({ html: shellHtml, method: c.req.method });
+ }
return serveCompressed(c, next);
};
- const serveAppShell = serveStatic({ root: dir, rewriteRequestPath: () => '/index.html', precompressed: true });
-
/**
* Client routes (`/sessions/{id}`, `/settings`, `/library`) have no file on disk, so a
* deep link only reaches the app when the shell answers the navigation.
@@ -81,12 +108,7 @@ export function mountFrontend(app: OpenAPIHono, dir: string): boolean {
return next();
}
- const response = await serveAppShell(c, next);
- if (response instanceof Response) {
- response.headers.set('Cache-Control', REVALIDATE_CACHE_CONTROL);
- response.headers.set('Vary', 'Accept-Encoding');
- }
- return response;
+ return createShellResponse({ html: shellHtml, method: c.req.method });
};
app.use('/*', serveBuild);
diff --git a/packages/trueforge/src/main.ts b/packages/trueforge/src/main.ts
index c16319812..fc8ef6e48 100644
--- a/packages/trueforge/src/main.ts
+++ b/packages/trueforge/src/main.ts
@@ -24,6 +24,7 @@ let configuration: typeof import('./config').default;
let isOidcConfigured: typeof import('./config').isOidcConfigured;
let isTrueFoundryModeEnabled: typeof import('./config').isTrueFoundryModeEnabled;
let getTrueForgeAuthMode: typeof import('./config').getTrueForgeAuthMode;
+let getPublicUiBasePath: typeof import('./config').getPublicUiBasePath;
let TrueForgeAuthMode: typeof import('./config').TrueForgeAuthMode;
try {
@@ -32,6 +33,7 @@ try {
isOidcConfigured,
isTrueFoundryModeEnabled,
getTrueForgeAuthMode,
+ getPublicUiBasePath,
TrueForgeAuthMode,
} = await import('./config'));
} catch (error) {
@@ -511,7 +513,7 @@ try {
)
: await createServerRuntime(await createDistributedPersistence({ configuration, logger }), logger);
- if (mountFrontend(app, configuration.FRONTEND_DIR)) {
+ if (mountFrontend(app, { dir: configuration.FRONTEND_DIR, uiBasePath: getPublicUiBasePath() })) {
logger.info(`Serving frontend from ${configuration.FRONTEND_DIR}`);
} else {
logger.warn(
diff --git a/packages/trueforge/src/schemas/auth.ts b/packages/trueforge/src/schemas/auth.ts
index 58a4be218..763ee1aa4 100644
--- a/packages/trueforge/src/schemas/auth.ts
+++ b/packages/trueforge/src/schemas/auth.ts
@@ -5,7 +5,7 @@ export const AuthLoginQuerySchema = z.object({
return_to: z
.string()
.optional()
- .describe('Path to return to after login. Must be a same-origin relative path; anything else falls back to "/".'),
+ .describe('Path to return to after login. Same-origin relative path; otherwise the public UI home.'),
});
export const OAuthCallbackQuerySchema = z.object({
diff --git a/packages/trueforge/src/truefoundry/TrueFoundryMcpServerStore.ts b/packages/trueforge/src/truefoundry/TrueFoundryMcpServerStore.ts
index 8e120b08a..b6badcd1b 100644
--- a/packages/trueforge/src/truefoundry/TrueFoundryMcpServerStore.ts
+++ b/packages/trueforge/src/truefoundry/TrueFoundryMcpServerStore.ts
@@ -49,10 +49,10 @@ function withoutAuthorization(headers: Record<string, string> | undefined): Reco
return Object.fromEntries(Object.entries(headers).filter(([name]) => name.toLowerCase() !== 'authorization'));
}
-/** Absolute FE landing for the upstream authorize `redirectURL` from `PUBLIC_BASE_URL` + safe `return_to`. */
+/** Absolute FE landing for the upstream authorize `redirectURL`. `return_to` is a browser path. */
export function resolveAuthorizeRedirectURL(input: { returnTo?: string }): string {
try {
- return new URL(safeReturnTo(input.returnTo), `${getPublicBaseUrl()}/`).href;
+ return new URL(safeReturnTo(input.returnTo), `${new URL(getPublicBaseUrl()).origin}/`).href;
} catch (error) {
throw new McpConnectionError('PUBLIC_BASE_URL is required for TrueFoundry MCP OAuth but was empty', 500, {
cause: error,
diff --git a/packages/trueforge/tests/unit/apis/auth.test.ts b/packages/trueforge/tests/unit/apis/auth.test.ts
index 8f607ca21..f04f035ea 100644
--- a/packages/trueforge/tests/unit/apis/auth.test.ts
+++ b/packages/trueforge/tests/unit/apis/auth.test.ts
@@ -11,6 +11,7 @@ import { StandaloneAuthenticator } from '../../../src/auth/standaloneAuthenticat
import configuration from '../../../src/config';
jest.mock('../../../src/config', () => {
+ const actual = jest.requireActual<typeof import('../../../src/config')>('../../../src/config');
const OIDC = {
OIDC_ISSUER_URL: 'https://issuer.example.com/',
OIDC_CLIENT_ID: 'harness-client',
@@ -29,18 +30,17 @@ jest.mock('../../../src/config', () => {
OIDC,
PORT: 8790,
};
+ const publicBase = {
+ ...actual.default,
+ PUBLIC_BASE_URL: config.PUBLIC_BASE_URL,
+ NODE_ENV: 'development',
+ };
return {
+ ...actual,
__esModule: true,
default: config,
- getPublicBaseUrl: (value = config) => {
- if (value.STANDALONE && value.NODE_ENV !== 'development') {
- return `http://localhost:${String(value.PORT)}`;
- }
- if (value.PUBLIC_BASE_URL === '') {
- throw new Error('PUBLIC_BASE_URL is required for OIDC callbacks but was empty');
- }
- return value.PUBLIC_BASE_URL;
- },
+ getPublicBaseUrl: () => actual.getPublicBaseUrl(publicBase),
+ getPublicUiBasePath: () => actual.getPublicUiBasePath(publicBase),
};
});
diff --git a/packages/trueforge/tests/unit/auth/safeReturnTo.test.ts b/packages/trueforge/tests/unit/auth/safeReturnTo.test.ts
index c44d39de5..e96996805 100644
--- a/packages/trueforge/tests/unit/auth/safeReturnTo.test.ts
+++ b/packages/trueforge/tests/unit/auth/safeReturnTo.test.ts
@@ -8,7 +8,7 @@ describe('safeReturnTo', () => {
expect(safeReturnTo('/chat')).toBe('/chat');
});
- it('falls back to "/" for missing or unsafe values', () => {
+ it('falls back to the public UI home for missing or unsafe values', () => {
expect(safeReturnTo('https://evil.example.com/')).toBe('/');
expect(safeReturnTo('//evil.example.com/')).toBe('/');
expect(safeReturnTo('/api')).toBe('/');
diff --git a/packages/trueforge/tests/unit/config/config.test.ts b/packages/trueforge/tests/unit/config/config.test.ts
index 769af31ee..9b0dbe016 100644
--- a/packages/trueforge/tests/unit/config/config.test.ts
+++ b/packages/trueforge/tests/unit/config/config.test.ts
@@ -1,4 +1,4 @@
-import type { ServerConfiguration } from '../../../src/config';
+import { getPublicUiBasePath, type ServerConfiguration } from '../../../src/config';
import { resolveTrueFoundrySandboxProviderConfig } from '../../../src/truefoundry/resolveTrueFoundrySandboxProviderConfig';
/** Minimal distributed config slice for resolve tests (unused fields are irrelevant). */
@@ -106,3 +106,26 @@ describe('resolveTrueFoundrySandboxProviderConfig', () => {
).toThrow(/TRUEFOUNDRY_SANDBOX_SETTINGS must be valid JSON/);
});
});
+
+describe('getPublicUiBasePath', () => {
+ it('ignores a path-bearing PUBLIC_BASE_URL in standalone non-development', () => {
+ expect(
+ getPublicUiBasePath({
+ STANDALONE: true,
+ NODE_ENV: 'production',
+ PORT: 8790,
+ PUBLIC_BASE_URL: 'https://host.example/custom/proxy/path',
+ } as ServerConfiguration),
+ ).toBe('/');
+ });
+
+ it('honors PUBLIC_BASE_URL pathname in standalone development', () => {
+ expect(
+ getPublicUiBasePath({
+ STANDALONE: true,
+ NODE_ENV: 'development',
+ PUBLIC_BASE_URL: 'https://host.example/custom/proxy/path',
+ } as ServerConfiguration),
+ ).toBe('/custom/proxy/path/');
+ });
+});
diff --git a/packages/trueforge/tests/unit/frontend.test.ts b/packages/trueforge/tests/unit/frontend.test.ts
index 8e64417d2..5c09da2fc 100644
--- a/packages/trueforge/tests/unit/frontend.test.ts
+++ b/packages/trueforge/tests/unit/frontend.test.ts
@@ -16,7 +16,7 @@ function buildDir(): string {
function appWithFrontend(dir: string): OpenAPIHono {
const app = new OpenAPIHono();
app.get('/api/v1/health', c => c.json({ ok: true }));
- mountFrontend(app, dir);
+ mountFrontend(app, { dir, uiBasePath: '/' });
return app;
}
@@ -24,8 +24,24 @@ const HTML_ACCEPT = { accept: 'text/html,application/xhtml+xml' };
describe('mountFrontend', () => {
it('reports whether the directory holds a build', () => {
- expect(mountFrontend(new OpenAPIHono(), path.join(tmpdir(), 'trueforge-missing-build'))).toBe(false);
- expect(mountFrontend(new OpenAPIHono(), buildDir())).toBe(true);
+ expect(
+ mountFrontend(new OpenAPIHono(), { dir: path.join(tmpdir(), 'trueforge-missing-build'), uiBasePath: '/' }),
+ ).toBe(false);
+ expect(mountFrontend(new OpenAPIHono(), { dir: buildDir(), uiBasePath: '/' })).toBe(true);
+ });
+
+ it('substitutes the public UI prefix into the cached app shell', async () => {
+ const dir = mkdtempSync(path.join(tmpdir(), 'trueforge-frontend-'));
+ writeFileSync(
+ path.join(dir, 'index.html'),
+ "<html><script>window.__TRUEFORGE_BASE_PATH__='%%TRUEFORGE_BASE_PATH%%';</script></html>",
+ );
+ const app = new OpenAPIHono();
+ mountFrontend(app, { dir, uiBasePath: '/custom/proxy/path/' });
+
+ const response = await app.request('/', { headers: HTML_ACCEPT });
+ expect(response.status).toBe(200);
+ await expect(response.text()).resolves.toContain("window.__TRUEFORGE_BASE_PATH__='/custom/proxy/path/'");
});
it('serves the app shell for client-only deep links', async () => {