Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

fix(web): validate the browser API base URL (MUL-5922) (#6627)

Naiyuan Qing2b35f8017ab3
diff --git a/.env.example b/.env.example
index e59d9f0486..ff2cb0458b 100644
--- a/.env.example
+++ b/.env.example
@@ -358,6 +358,12 @@ MULTICA_DINGTALK_SECRET_KEY=
# Frontend
# Leave empty — auto-derived from page origin in browser, set by Makefile for local dev.
# NEXT_PUBLIC_API_URL also feeds the Next.js SSR proxy when explicitly set.
+#
+# When you do set it, give the backend's ORIGIN only — scheme + host (+ port),
+# with NO path: https://api.example.com, not https://api.example.com/api.
+# The client appends its own /api, /uploads and /ws prefixes, so a path here is
+# doubled: /api/api/... for every request and 404s for every avatar/attachment.
+# A trailing /api is stripped defensively, but anything else is kept as-is.
NEXT_PUBLIC_API_URL=
NEXT_PUBLIC_WS_URL=
diff --git a/SELF_HOSTING_ADVANCED.md b/SELF_HOSTING_ADVANCED.md
index ea5b5fe6bc..d2553619fa 100644
--- a/SELF_HOSTING_ADVANCED.md
+++ b/SELF_HOSTING_ADVANCED.md
@@ -425,6 +425,10 @@ NEXT_PUBLIC_API_URL=https://api.example.com
NEXT_PUBLIC_WS_URL=wss://api.example.com/ws
```
+> **`NEXT_PUBLIC_API_URL` and `REMOTE_API_URL` take the backend's origin — scheme + host (+ port) — and no path.** Write `https://api.example.com`, never `https://api.example.com/api`. The browser client appends its own prefixes, so a path is doubled: requests go to `/api/api/...` and every avatar, image and attachment resolves under `<your-path>/uploads/...`, which the backend does not serve — the app loads but data calls and images 404. A trailing `/api` is now stripped defensively, but any other path is kept, because a reverse proxy may legitimately mount the whole backend under a prefix.
+>
+> This bites on upgrade: before v0.4.10 `NEXT_PUBLIC_API_URL` was inert in the published images, so a wrong value sat in `.env` doing nothing. v0.4.10 wired it through, and the stale value took effect. If you upgraded and the UI loads but nothing else does, check this variable first, then recreate the frontend container (`docker compose ... up -d --force-recreate frontend`) so the new value is picked up.
+
> **`COOKIE_DOMAIN` is required in this setup — omitting it breaks every write.** The web app authenticates with an HttpOnly `multica_auth` cookie plus a JS-readable `multica_csrf` cookie, and sends the CSRF value as an `X-CSRF-Token` header on every non-GET request. Both cookies are host-only unless `COOKIE_DOMAIN` is set, so a frontend on `app.example.com` cannot read a cookie issued by `api.example.com`. The header is then never sent and the backend rejects the request with `403 {"error":"CSRF validation failed"}` — while GET requests keep working, so the app renders but nothing can be created or edited.
>
> After changing `COOKIE_DOMAIN`, delete the existing `multica_auth` / `multica_csrf` cookies on **both** hosts and log in again. Stale host-only cookies otherwise sit alongside the new domain-scoped ones and the browser sends both.
diff --git a/apps/web/config/runtime-urls.test.ts b/apps/web/config/runtime-urls.test.ts
index f1be2809b2..b69036cb14 100644
--- a/apps/web/config/runtime-urls.test.ts
+++ b/apps/web/config/runtime-urls.test.ts
@@ -50,6 +50,25 @@ describe("resolveRemoteApiUrl", () => {
).toBeUndefined();
});
+ // Same defect as the browser base, same fix: the rewrite target already
+ // appends the full incoming pathname (`/api/**`, `/uploads/**`, `/ws`), so a
+ // configured `/api` suffix would double it (MUL-5922).
+ it("strips a trailing /api from server-side rewrite targets", () => {
+ expect(
+ resolveRemoteApiUrl({ REMOTE_API_URL: "http://backend:8080/api" }),
+ ).toBe("http://backend:8080");
+ expect(
+ runtimeRewriteDestination("/api/config", {
+ NEXT_PUBLIC_API_URL: "https://app.example.com/api",
+ }),
+ ).toBe("https://app.example.com/api/config");
+ expect(
+ runtimeRewriteDestination("/uploads/workspaces/a.png", {
+ NEXT_PUBLIC_API_URL: "https://app.example.com/api",
+ }),
+ ).toBe("https://app.example.com/uploads/workspaces/a.png");
+ });
+
it("ignores whitespace-only or invalid backend URL values", () => {
expect(
resolveRemoteApiUrl({
@@ -91,6 +110,71 @@ describe("browser runtime URLs", () => {
).toBe("https://api.example.com");
});
+ // #6619: these two values used to reach the browser untouched and became the
+ // XHR base, so every request went to `/api/api/**` and every avatar to
+ // `<base>/uploads/**` — which the backend serves at the root, hence 404.
+ it("rejects a relative public API URL so the browser stays same-origin", () => {
+ expect(
+ resolveBrowserApiBaseUrl({ NEXT_PUBLIC_API_URL: "/api" }),
+ ).toBeUndefined();
+ expect(
+ resolveBrowserApiBaseUrl({ NEXT_PUBLIC_API_URL: "ftp://api.example.com" }),
+ ).toBeUndefined();
+ });
+
+ it("strips a trailing /api from an absolute public API URL", () => {
+ expect(
+ resolveBrowserApiBaseUrl({
+ NEXT_PUBLIC_API_URL: " https://app.example.com/api/ ",
+ }),
+ ).toBe("https://app.example.com");
+ });
+
+ it("keeps a non-/api path prefix so prefix-mounted backends still work", () => {
+ expect(
+ resolveBrowserApiBaseUrl({
+ NEXT_PUBLIC_API_URL: "https://app.example.com/multica",
+ }),
+ ).toBe("https://app.example.com/multica");
+ });
+
+ it("does not mistake an `api` host for an /api path suffix", () => {
+ expect(
+ resolveBrowserApiBaseUrl({ NEXT_PUBLIC_API_URL: "http://api:8080" }),
+ ).toBe("http://api:8080");
+ });
+
+ // The XHR base doubles as the base for `/uploads/**` (avatars, attachment
+ // previews) via resolvePublicFileUrlWithBase in packages/core. Assert the
+ // joined result, not just the base, because that join is what users saw fail.
+ it("produces working /api and /uploads targets for every supported value", () => {
+ const cases: Array<[string | undefined, string, string]> = [
+ [undefined, "/api/issues", "/uploads/avatars/a.png"],
+ ["/api", "/api/issues", "/uploads/avatars/a.png"],
+ [
+ "https://app.example.com/api",
+ "https://app.example.com/api/issues",
+ "https://app.example.com/uploads/avatars/a.png",
+ ],
+ [
+ "https://api.example.com",
+ "https://api.example.com/api/issues",
+ "https://api.example.com/uploads/avatars/a.png",
+ ],
+ ];
+
+ for (const [configured, expectedApi, expectedUpload] of cases) {
+ // Mirrors the browser: CoreProvider defaults an absent base to "" and the
+ // api client concatenates `${baseUrl}${path}`.
+ const base =
+ resolveBrowserApiBaseUrl({ NEXT_PUBLIC_API_URL: configured }) ?? "";
+ expect(`${base}/api/issues`).toBe(expectedApi);
+ expect(`${base}/uploads/avatars/a.png`).toBe(expectedUpload);
+ }
+ });
+
+ // Sub-path semantics are intentional, not incidental: the base is the mount
+ // prefix, so HTTP and websocket traffic must share it (see tryDeriveWsUrl).
it("derives browser websocket URL from the public API URL", () => {
expect(
resolveBrowserWsUrl({
@@ -99,6 +183,14 @@ describe("browser runtime URLs", () => {
).toBe("wss://api.example.com/base/ws");
});
+ it("derives a root websocket URL once the /api suffix is stripped", () => {
+ expect(
+ resolveBrowserWsUrl({
+ NEXT_PUBLIC_API_URL: "https://app.example.com/api",
+ }),
+ ).toBe("wss://app.example.com/ws");
+ });
+
it("prefers an explicit browser websocket URL", () => {
expect(
resolveBrowserWsUrl({
diff --git a/apps/web/config/runtime-urls.ts b/apps/web/config/runtime-urls.ts
index 24c7d97b27..ba37c0b62b 100644
--- a/apps/web/config/runtime-urls.ts
+++ b/apps/web/config/runtime-urls.ts
@@ -20,15 +20,45 @@ function cleanHttpUrl(raw: string | undefined): string | undefined {
return undefined;
}
+// The API base names the backend ORIGIN, never its `/api` endpoint: every
+// caller already carries its own prefix (`packages/core/api/client.ts` sends
+// `/api/**`, avatars resolve `/uploads/**`, realtime connects `/ws`), and the
+// backend serves all three at the root (server/cmd/server/router.go). A base
+// ending in `/api` therefore yields `/api/api/**` requests and 404s every
+// upload — the most common self-hosting mistake (#6619, MUL-5922). Strip that
+// one suffix instead of honouring it. Any other path is preserved: a reverse
+// proxy may legitimately mount the whole backend under a prefix such as
+// `https://host/multica`.
+function stripApiPathSuffix(value: string): string {
+ let url: URL;
+ try {
+ url = new URL(value);
+ } catch {
+ return value;
+ }
+ const pathname = url.pathname.replace(/\/+$/, "");
+ if (!pathname.endsWith("/api")) return value;
+ url.pathname = pathname.slice(0, -"/api".length);
+ url.search = "";
+ url.hash = "";
+ return url.toString().replace(/\/+$/, "");
+}
+
+function cleanApiBaseUrl(raw: string | undefined): string | undefined {
+ const value = cleanHttpUrl(raw);
+ if (!value) return undefined;
+ return stripApiPathSuffix(value);
+}
+
function appendPath(baseUrl: string, path: string): string {
return `${baseUrl}${path.startsWith("/") ? path : `/${path}`}`;
}
export function resolveRemoteApiUrl(env: RuntimeEnv): string | undefined {
- const explicitRemote = cleanHttpUrl(env.REMOTE_API_URL);
+ const explicitRemote = cleanApiBaseUrl(env.REMOTE_API_URL);
if (explicitRemote) return explicitRemote;
- const publicApi = cleanHttpUrl(env.NEXT_PUBLIC_API_URL);
+ const publicApi = cleanApiBaseUrl(env.NEXT_PUBLIC_API_URL);
if (publicApi) return publicApi;
return undefined;
}
@@ -60,8 +90,13 @@ export function resolveDevDocsUrl(env: RuntimeEnv): string {
return resolveDocsUrl(env) ?? "http://localhost:4000";
}
+// Same strictness as the server-side resolver above. A relative or otherwise
+// non-http value used to pass through untouched and became the XHR base, so
+// `NEXT_PUBLIC_API_URL=/api` produced `/api/api/**` and `/api/uploads/**`
+// (#6619). Returning undefined instead makes the browser fall back to
+// same-origin relative paths, which is what an unset value already does.
export function resolveBrowserApiBaseUrl(env: RuntimeEnv): string | undefined {
- return cleanUrl(env.NEXT_PUBLIC_API_URL);
+ return cleanApiBaseUrl(env.NEXT_PUBLIC_API_URL);
}
export function resolveBrowserWsUrl(env: RuntimeEnv): string | undefined {
@@ -111,6 +146,15 @@ function isBackendAuthPath(pathname: string): boolean {
return pathname === "/auth" || pathname.startsWith("/auth/");
}
+// `/ws` is appended to the api base's PATH, not to its origin, and that is
+// deliberate: the base is whatever prefix the backend is mounted under, so
+// HTTP (`<base>/api/**`) and realtime (`<base>/ws`) must share it or a
+// prefix-mounted deployment would break in one direction while working in the
+// other. `apps/desktop/src/shared/runtime-config.ts` derives it the same way,
+// so both clients read one configured value identically. The regression that
+// motivated MUL-5922 — `NEXT_PUBLIC_API_URL=https://host/api` deriving
+// `wss://host/api/ws` while the backend serves `/ws` at the root — is fixed
+// upstream in the base itself (see stripApiPathSuffix), not here.
function tryDeriveWsUrl(apiUrl: string): string | undefined {
let url: URL;
try {