Skip to content

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

Go

MUL-6833 fix(web): localize auth callback and error pages (#7752)

Soda043121806176
diff --git a/apps/web/app/auth/callback/callback-error.test.ts b/apps/web/app/auth/callback/callback-error.test.ts
new file mode 100644
index 0000000000..6fe41e811e
--- /dev/null
+++ b/apps/web/app/auth/callback/callback-error.test.ts
@@ -0,0 +1,72 @@
+// @vitest-environment node
+
+import { describe, expect, it } from "vitest";
+import { ApiError } from "@multica/core/api";
+import { callbackErrorFrom } from "./callback-error";
+
+describe("callbackErrorFrom", () => {
+ it.each([
+ "account_disabled",
+ "signup_prohibited",
+ "email_not_allowed",
+ "google_account_no_email",
+ "oauth_code_invalid",
+ ] as const)("keeps the stable %s error kind for localization", (code) => {
+ const err = new ApiError("English fallback", 403, "Forbidden", { code });
+ expect(callbackErrorFrom(err)).toEqual({ kind: code });
+ });
+
+ it("keeps an actionable message from an older server that returned an uncoded 4xx", () => {
+ const err = new ApiError("registration is disabled", 403, "Forbidden");
+ expect(callbackErrorFrom(err)).toEqual({
+ kind: "raw",
+ text: "registration is disabled",
+ });
+ });
+
+ it("preserves unknown actionable codes as their server message", () => {
+ const err = new ApiError("new signup restriction", 403, "Forbidden", {
+ code: "future_restriction",
+ });
+ expect(callbackErrorFrom(err)).toEqual({
+ kind: "raw",
+ text: "new signup restriction",
+ });
+ });
+
+ it("localizes a known 4xx code even without a fallback message", () => {
+ const err = new ApiError("", 400, "Bad Request", { code: "oauth_code_invalid" });
+ expect(callbackErrorFrom(err)).toEqual({ kind: "oauth_code_invalid" });
+ });
+
+ it.each([undefined, null, {}, { code: 42 }, { code: "" }])(
+ "handles malformed error bodies: %j",
+ (body) => {
+ const err = new ApiError("actionable fallback", 400, "Bad Request", body);
+ expect(callbackErrorFrom(err)).toEqual({ kind: "raw", text: "actionable fallback" });
+ },
+ );
+
+ it.each([500, 502, 503])(
+ "hides %s details even when a known code is present",
+ (status) => {
+ const err = new ApiError("internal detail", status, "Server Error", {
+ code: "oauth_code_invalid",
+ });
+ expect(callbackErrorFrom(err)).toEqual({ kind: "login_failed" });
+ },
+ );
+
+ it.each([new Error("Failed to fetch"), null, undefined, { code: "oauth_code_invalid" }])(
+ "handles transport and non-API errors: %j",
+ (err) => {
+ expect(callbackErrorFrom(err)).toEqual({ kind: "login_failed" });
+ },
+ );
+
+ it("uses the localized generic failure for an empty, uncoded 4xx", () => {
+ expect(callbackErrorFrom(new ApiError("", 400, "Bad Request"))).toEqual({
+ kind: "login_failed",
+ });
+ });
+});
diff --git a/apps/web/app/auth/callback/callback-error.ts b/apps/web/app/auth/callback/callback-error.ts
new file mode 100644
index 0000000000..3f542cd591
--- /dev/null
+++ b/apps/web/app/auth/callback/callback-error.ts
@@ -0,0 +1,43 @@
+import { ApiError, clientErrorMessage, errorCode } from "@multica/core/api";
+
+export type CallbackError =
+ | {
+ kind:
+ | "missing_code"
+ | "access_denied"
+ | "login_failed"
+ | "account_disabled"
+ | "signup_prohibited"
+ | "email_not_allowed"
+ | "google_account_no_email"
+ | "oauth_code_invalid";
+ }
+ | { kind: "raw"; text: string };
+
+export function callbackErrorFrom(err: unknown): CallbackError {
+ // An actionable code is meaningful only on a client error. A drifting server
+ // must not turn a provider/internal failure into a specific user diagnosis.
+ if (!(err instanceof ApiError) || err.status < 400 || err.status >= 500) {
+ return { kind: "login_failed" };
+ }
+
+ switch (errorCode(err)) {
+ case "account_disabled":
+ return { kind: "account_disabled" };
+ case "signup_prohibited":
+ return { kind: "signup_prohibited" };
+ case "email_not_allowed":
+ return { kind: "email_not_allowed" };
+ case "google_account_no_email":
+ return { kind: "google_account_no_email" };
+ case "oauth_code_invalid":
+ return { kind: "oauth_code_invalid" };
+ default:
+ break;
+ }
+
+ const clientMessage = clientErrorMessage(err);
+ return clientMessage
+ ? { kind: "raw", text: clientMessage }
+ : { kind: "login_failed" };
+}
diff --git a/apps/web/app/auth/callback/page.test.tsx b/apps/web/app/auth/callback/page.test.tsx
index 8e6bf069fd..43f658dddb 100644
--- a/apps/web/app/auth/callback/page.test.tsx
+++ b/apps/web/app/auth/callback/page.test.tsx
@@ -1,22 +1,50 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
-import { render, waitFor } from "@testing-library/react";
+import { render, screen, waitFor } from "@testing-library/react";
+import type { SupportedLocale } from "@multica/core/i18n";
+import { I18nProvider } from "@multica/core/i18n/react";
import { paths } from "@multica/core/paths";
+import { RESOURCES } from "@multica/views/locales";
+import { ApiError } from "@multica/core/api";
const {
mockPush,
+ mockRouter,
mockSearchParams,
mockLoginWithGoogle,
mockListWorkspaces,
mockListMyInvitations,
mockSetQueryData,
-} = vi.hoisted(() => ({
- mockPush: vi.fn(),
- mockSearchParams: new URLSearchParams(),
- mockLoginWithGoogle: vi.fn(),
- mockListWorkspaces: vi.fn(),
- mockListMyInvitations: vi.fn(),
- mockSetQueryData: vi.fn(),
-}));
+ mockQueryClient,
+} = vi.hoisted(() => {
+ const mockPush = vi.fn();
+ const mockSetQueryData = vi.fn();
+ return {
+ mockPush,
+ mockRouter: { push: mockPush },
+ mockSearchParams: new URLSearchParams(),
+ mockLoginWithGoogle: vi.fn(),
+ mockListWorkspaces: vi.fn(),
+ mockListMyInvitations: vi.fn(),
+ mockSetQueryData,
+ mockQueryClient: { setQueryData: mockSetQueryData },
+ };
+});
+
+vi.mock("@multica/core/logger", async () => {
+ const actual =
+ await vi.importActual<typeof import("@multica/core/logger")>(
+ "@multica/core/logger",
+ );
+ return {
+ ...actual,
+ createLogger: () => ({
+ debug: vi.fn(),
+ info: vi.fn(),
+ warn: vi.fn(),
+ error: vi.fn(),
+ }),
+ };
+});
const makeUser = (
overrides: Partial<{
@@ -36,12 +64,12 @@ const makeUser = (
});
vi.mock("next/navigation", () => ({
- useRouter: () => ({ push: mockPush }),
+ useRouter: () => mockRouter,
useSearchParams: () => mockSearchParams,
}));
vi.mock("@tanstack/react-query", () => ({
- useQueryClient: () => ({ setQueryData: mockSetQueryData }),
+ useQueryClient: () => mockQueryClient,
}));
// Preserve the real sanitizeNextUrl so the "drop unsafe ?next=" behavior is
@@ -65,16 +93,30 @@ vi.mock("@multica/core/workspace/queries", () => ({
},
}));
-vi.mock("@multica/core/api", () => ({
- api: {
- listWorkspaces: mockListWorkspaces,
- listMyInvitations: mockListMyInvitations,
- googleLogin: vi.fn(),
- },
-}));
+vi.mock("@multica/core/api", async () => {
+ const actual = await vi.importActual<typeof import("@multica/core/api")>(
+ "@multica/core/api",
+ );
+ return {
+ ...actual,
+ api: {
+ listWorkspaces: mockListWorkspaces,
+ listMyInvitations: mockListMyInvitations,
+ googleLogin: vi.fn(),
+ },
+ };
+});
import CallbackPage from "./page";
+function renderCallback(locale: SupportedLocale = "en") {
+ return render(
+ <I18nProvider locale={locale} resources={RESOURCES}>
+ <CallbackPage />
+ </I18nProvider>,
+ );
+}
+
describe("CallbackPage", () => {
beforeEach(() => {
vi.clearAllMocks();
@@ -98,9 +140,125 @@ describe("CallbackPage", () => {
mockListMyInvitations.mockResolvedValue([]);
});
+ it("renders callback errors in the selected locale", async () => {
+ mockSearchParams.delete("code");
+
+ renderCallback("zh-Hans");
+
+ expect(await screen.findByText("登录失败")).toBeInTheDocument();
+ expect(screen.getByText("缺少授权码")).toBeInTheDocument();
+ expect(screen.getByText("返回登录")).toBeInTheDocument();
+ });
+
+ it("shows access denied before checking for a missing authorization code", async () => {
+ mockSearchParams.delete("code");
+ mockSearchParams.set("error", "access_denied");
+
+ renderCallback("zh-Hans");
+
+ expect(await screen.findByText("访问被拒绝")).toBeInTheDocument();
+ expect(screen.queryByText("缺少授权码")).not.toBeInTheDocument();
+ expect(mockLoginWithGoogle).not.toHaveBeenCalled();
+ });
+
+ it("renders a localized generic failure instead of a raw English error", async () => {
+ mockLoginWithGoogle.mockRejectedValue(
+ new Error("upstream authentication failed"),
+ );
+
+ renderCallback("zh-Hans");
+
+ expect(await screen.findByText("无法完成登录,请重试。")).toBeInTheDocument();
+ expect(
+ screen.queryByText("upstream authentication failed"),
+ ).not.toBeInTheDocument();
+ });
+
+ it("localizes a stable login error code", async () => {
+ mockLoginWithGoogle.mockRejectedValue(
+ new ApiError("English fallback", 403, "Forbidden", {
+ code: "signup_prohibited",
+ }),
+ );
+
+ renderCallback("zh-Hans");
+
+ expect(
+ await screen.findByText("此自托管实例已禁止用户注册。"),
+ ).toBeInTheDocument();
+ expect(screen.queryByText("English fallback")).not.toBeInTheDocument();
+ });
+
+ it("preserves an actionable uncoded 4xx message from an older server", async () => {
+ mockLoginWithGoogle.mockRejectedValue(
+ new ApiError("legacy client error", 403, "Forbidden"),
+ );
+
+ renderCallback("zh-Hans");
+
+ expect(await screen.findByText("legacy client error")).toBeInTheDocument();
+ });
+
+ it("retranslates a missing-email response without repeating the single-use code exchange", async () => {
+ mockLoginWithGoogle.mockRejectedValue(
+ new ApiError("Google did not provide an email address", 400, "Bad Request", {
+ code: "google_account_no_email",
+ }),
+ );
+
+ const view = renderCallback("zh-Hans");
+ expect(
+ await screen.findByText("Google 未提供本次登录所需的邮箱地址。"),
+ ).toBeInTheDocument();
+
+ view.rerender(
+ <I18nProvider locale="ja" resources={RESOURCES}>
+ <CallbackPage />
+ </I18nProvider>,
+ );
+
+ expect(
+ await screen.findByText("Googleから今回のログインに必要なメールアドレスが提供されませんでした。"),
+ ).toBeInTheDocument();
+ expect(mockLoginWithGoogle).toHaveBeenCalledTimes(1);
+ expect(mockPush).not.toHaveBeenCalled();
+ });
+
+ // The response matrix lives in callback-error.test.ts; this covers page wiring.
+ it("does not turn a provider failure into a user diagnosis even if it carries a known code", async () => {
+ mockLoginWithGoogle.mockRejectedValue(
+ new ApiError("internal provider detail", 502, "Bad Gateway", {
+ code: "oauth_code_invalid",
+ }),
+ );
+
+ renderCallback("zh-Hans");
+
+ expect(await screen.findByText("无法完成登录,请重试。")).toBeInTheDocument();
+ expect(screen.queryByText("internal provider detail")).not.toBeInTheDocument();
+ });
+
+ it.each([
+ ["Desktop", "platform:desktop"],
+ ["CLI", "cli_callback:http://127.0.0.1:46233/callback,cli_state:test"],
+ ])("uses the same localized error handling for the %s callback", async (_flow, state) => {
+ const { api: mockedApi } = await import("@multica/core/api");
+ vi.mocked(mockedApi.googleLogin).mockRejectedValue(
+ new ApiError("English fallback", 403, "Forbidden", { code: "signup_prohibited" }),
+ );
+ mockSearchParams.set("state", state);
+
+ renderCallback("zh-Hans");
+
+ expect(await screen.findByText("此自托管实例已禁止用户注册。")).toBeInTheDocument();
+ expect(mockedApi.googleLogin).toHaveBeenCalledTimes(1);
+ expect(mockLoginWithGoogle).not.toHaveBeenCalled();
+ expect(mockPush).not.toHaveBeenCalled();
+ });
+
it("unonboarded user honors a safe next= (e.g. /invite/{id}) so invitees aren't trapped", async () => {
mockSearchParams.set("state", "next:/invite/abc123");
- render(<CallbackPage />);
+ renderCallback();
await waitFor(() => {
expect(mockPush).toHaveBeenCalledWith("/invite/abc123");
});
@@ -110,7 +268,7 @@ describe("CallbackPage", () => {
});
it("unonboarded user with no next= and no pending invitations lands on /onboarding", async () => {
- render(<CallbackPage />);
+ renderCallback();
await waitFor(() => {
expect(mockPush).toHaveBeenCalledWith(paths.onboarding());
});
@@ -127,7 +285,7 @@ describe("CallbackPage", () => {
status: "pending",
},
]);
- render(<CallbackPage />);
+ renderCallback();
await waitFor(() => {
expect(mockPush).toHaveBeenCalledWith(paths.invitations());
});
@@ -153,7 +311,7 @@ describe("CallbackPage", () => {
updated_at: "",
},
]);
- render(<CallbackPage />);
+ renderCallback();
await waitFor(() => {
expect(mockPush).toHaveBeenCalledWith(paths.workspace("acme").issues());
});
@@ -168,7 +326,7 @@ describe("CallbackPage", () => {
);
mockSearchParams.set("state", "next:https://evil.example");
- render(<CallbackPage />);
+ renderCallback();
await waitFor(() => {
expect(mockPush).toHaveBeenCalled();
@@ -182,7 +340,7 @@ describe("CallbackPage", () => {
);
mockSearchParams.set("state", "next:/invite/abc123");
- render(<CallbackPage />);
+ renderCallback();
await waitFor(() => {
expect(mockPush).toHaveBeenCalledWith("/invite/abc123");
@@ -191,7 +349,7 @@ describe("CallbackPage", () => {
it("falls through to /onboarding when listMyInvitations errors", async () => {
mockListMyInvitations.mockRejectedValue(new Error("network"));
- render(<CallbackPage />);
+ renderCallback();
await waitFor(() => {
expect(mockPush).toHaveBeenCalledWith(paths.onboarding());
});
@@ -216,7 +374,7 @@ describe("CallbackPage", () => {
);
mockGoogleLogin.mockResolvedValue({ token: "cli-jwt-token" });
- render(<CallbackPage />);
+ renderCallback();
await waitFor(() => {
expect(mockGoogleLogin).toHaveBeenCalledWith(
@@ -244,7 +402,7 @@ describe("CallbackPage", () => {
mockListWorkspaces.mockResolvedValue([]);
mockListMyInvitations.mockResolvedValue([]);
- render(<CallbackPage />);
+ renderCallback();
await waitFor(() => {
// Normal web flow: loginWithGoogle is called (not googleLogin)
@@ -276,7 +434,7 @@ describe("CallbackPage", () => {
);
mockGoogleLogin.mockResolvedValue({ token: "mixed-jwt" });
- render(<CallbackPage />);
+ renderCallback();
await waitFor(() => {
expect(mockGoogleLogin).toHaveBeenCalled();
@@ -319,7 +477,7 @@ describe("CallbackPage", () => {
updated_at: "",
},
]);
- render(<CallbackPage />);
+ renderCallback();
await waitFor(() => {
expect(mockPush).toHaveBeenCalledWith(paths.workspace("acme").issues());
});
diff --git a/apps/web/app/auth/callback/page.tsx b/apps/web/app/auth/callback/page.tsx
index 06d51b8c5c..792d27f2c8 100644
--- a/apps/web/app/auth/callback/page.tsx
+++ b/apps/web/app/auth/callback/page.tsx
@@ -7,6 +7,7 @@ import { sanitizeNextUrl, useAuthStore } from "@multica/core/auth";
import { workspaceKeys } from "@multica/core/workspace/queries";
import { paths, resolvePostAuthDestination } from "@multica/core/paths";
import { api } from "@multica/core/api";
+import { createLogger } from "@multica/core/logger";
import { validateCliCallback, redirectToCliCallback } from "@multica/views/auth";
import {
Card,
@@ -16,26 +17,36 @@ import {
CardContent,
} from "@multica/ui/components/ui/card";
import { Button } from "@multica/ui/components/ui/button";
+import { useT } from "@multica/views/i18n";
import { Loader2 } from "lucide-react";
+import { callbackErrorFrom, type CallbackError } from "./callback-error";
+
+const authLogger = createLogger("auth.callback");
function CallbackContent() {
+ const { t } = useT("auth");
const router = useRouter();
const searchParams = useSearchParams();
const qc = useQueryClient();
const loginWithGoogle = useAuthStore((s) => s.loginWithGoogle);
- const [error, setError] = useState("");
+ const [error, setError] = useState<CallbackError | null>(null);
const [desktopToken, setDesktopToken] = useState<string | null>(null);
useEffect(() => {
const code = searchParams.get("code");
- if (!code) {
- setError("Missing authorization code");
+ const errorParam = searchParams.get("error");
+ if (errorParam) {
+ authLogger.warn("Google OAuth returned an error parameter", errorParam);
+ setError(
+ errorParam === "access_denied"
+ ? { kind: "access_denied" }
+ : { kind: "login_failed" },
+ );
return;
}
- const errorParam = searchParams.get("error");
- if (errorParam) {
- setError(errorParam === "access_denied" ? "Access denied" : errorParam);
+ if (!code) {
+ setError({ kind: "missing_code" });
return;
}
@@ -77,7 +88,8 @@ function CallbackContent() {
redirectToCliCallback(cliCallback, token, cliState);
})
.catch((err) => {
- setError(err instanceof Error ? err.message : "Login failed");
+ authLogger.error("CLI Google OAuth callback failed", err);
+ setError(callbackErrorFrom(err));
});
} else if (isDesktop) {
// Desktop flow: exchange code for token, then redirect via deep link
@@ -88,7 +100,8 @@ function CallbackContent() {
window.location.href = `multica://auth/callback?token=${encodeURIComponent(token)}`;
})
.catch((err) => {
- setError(err instanceof Error ? err.message : "Login failed");
+ authLogger.error("Desktop Google OAuth callback failed", err);
+ setError(callbackErrorFrom(err));
});
} else {
// Normal web flow
@@ -138,20 +151,46 @@ function CallbackContent() {
router.push(resolvePostAuthDestination(wsList, onboarded));
})
.catch((err) => {
- setError(err instanceof Error ? err.message : "Login failed");
+ authLogger.error("Web Google OAuth callback failed", err);
+ setError(callbackErrorFrom(err));
});
}
}, [searchParams, loginWithGoogle, router, qc]);
+ const errorDescription = (() => {
+ if (!error) return null;
+ switch (error.kind) {
+ case "raw":
+ return error.text;
+ case "missing_code":
+ return t(($) => $.web.callback.missing_code);
+ case "access_denied":
+ return t(($) => $.web.callback.access_denied);
+ case "login_failed":
+ return t(($) => $.web.callback.login_failed);
+ case "account_disabled":
+ return t(($) => $.web.callback.account_disabled);
+ case "signup_prohibited":
+ return t(($) => $.web.callback.signup_prohibited);
+ case "email_not_allowed":
+ return t(($) => $.web.callback.email_not_allowed);
+ case "google_account_no_email":
+ return t(($) => $.web.callback.google_account_no_email);
+ case "oauth_code_invalid":
+ return t(($) => $.web.callback.oauth_code_invalid);
+ }
+ })();
+
if (desktopToken) {
return (
<div className="flex min-h-screen items-center justify-center">
<Card className="w-full max-w-sm">
<CardHeader className="text-center">
- <CardTitle className="text-display-sm">Opening Multica</CardTitle>
+ <CardTitle className="text-display-sm">
+ {t(($) => $.web.desktop_handoff.opening_title)}
+ </CardTitle>
<CardDescription>
- You should see a prompt to open the Multica desktop app. If
- nothing happens, click the button below.
+ {t(($) => $.web.desktop_handoff.opening_description)}
</CardDescription>
</CardHeader>
<CardContent className="flex justify-center">
@@ -161,7 +200,7 @@ function CallbackContent() {
window.location.href = `multica://auth/callback?token=${encodeURIComponent(desktopToken)}`;
}}
>
- Open Multica Desktop
+ {t(($) => $.web.desktop_handoff.open_button)}
</Button>
</CardContent>
</Card>
@@ -174,12 +213,16 @@ function CallbackContent() {
<div className="flex min-h-screen items-center justify-center">
<Card className="w-full max-w-sm">
<CardHeader className="text-center">
- <CardTitle className="text-display-sm">Login Failed</CardTitle>
- <CardDescription>{error}</CardDescription>
+ <CardTitle className="text-display-sm">
+ {t(($) => $.web.callback.failed_title)}
+ </CardTitle>
+ <CardDescription>
+ {errorDescription}
+ </CardDescription>
</CardHeader>
<CardContent className="flex justify-center">
<a href={paths.login()} className="text-primary underline-offset-4 hover:underline">
- Back to login
+ {t(($) => $.web.callback.back_to_login)}
</a>
</CardContent>
</Card>
@@ -191,8 +234,12 @@ function CallbackContent() {
<div className="flex min-h-screen items-center justify-center">
<Card className="w-full max-w-sm">
<CardHeader className="text-center">
- <CardTitle className="text-display-sm">Signing in...</CardTitle>
- <CardDescription>Please wait while we complete your login</CardDescription>
+ <CardTitle className="text-display-sm">
+ {t(($) => $.web.callback.signing_in)}
+ </CardTitle>
+ <CardDescription>
+ {t(($) => $.web.callback.signing_in_description)}
+ </CardDescription>
</CardHeader>
<CardContent className="flex justify-center">
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
diff --git a/apps/web/app/emergency-locale.ts b/apps/web/app/emergency-locale.ts
new file mode 100644
index 0000000000..f74fc0c0b4
--- /dev/null
+++ b/apps/web/app/emergency-locale.ts
@@ -0,0 +1,24 @@
+import { matchLocale, type SupportedLocale } from "@multica/core/i18n";
+import { createBrowserCookieLocaleAdapter } from "@multica/core/i18n/browser";
+
+export function resolveEmergencyLocale(): SupportedLocale {
+ const adapter = createBrowserCookieLocaleAdapter();
+ let cookieLocale: string | null = null;
+ let browserLocales: readonly string[] = [];
+
+ try {
+ cookieLocale = adapter.getUserChoice();
+ } catch {
+ // A blocked cookie should not be able to break the last-resort UI.
+ }
+
+ try {
+ browserLocales = adapter.getSystemPreferences();
+ } catch {
+ // Browser language detection is best-effort in the emergency boundary.
+ }
+
+ return matchLocale(
+ [cookieLocale ?? "", ...browserLocales].filter(Boolean),
+ );
+}
diff --git a/apps/web/app/global-error.test.tsx b/apps/web/app/global-error.test.tsx
new file mode 100644
index 0000000000..279170d877
--- /dev/null
+++ b/apps/web/app/global-error.test.tsx
@@ -0,0 +1,93 @@
+// @vitest-environment jsdom
+
+import { act } from "react";
+import { hydrateRoot, type Root } from "react-dom/client";
+import { renderToString } from "react-dom/server";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { LOCALE_COOKIE } from "@multica/core/i18n";
+import { resolveEmergencyLocale } from "./emergency-locale";
+import GlobalError from "./global-error";
+
+vi.mock("@multica/core/analytics", () => ({
+ captureException: vi.fn(),
+}));
+
+function setBrowserLanguages(languages: string[]) {
+ Object.defineProperty(window.navigator, "languages", {
+ configurable: true,
+ value: languages,
+ });
+}
+
+function resetDocument() {
+ document.open();
+ document.write("<!doctype html><html><head></head><body></body></html>");
+ document.close();
+}
+
+let hydratedRoot: Root | undefined;
+
+async function hydrateGlobalError(documentLanguage: string) {
+ const reset = vi.fn();
+ const onRecoverableError = vi.fn();
+ const element = <GlobalError error={new Error("boom")} reset={reset} />;
+
+ document.open();
+ document.write(`<!doctype html>${renderToString(element)}`);
+ document.close();
+ document.documentElement.lang = documentLanguage;
+
+ await act(async () => {
+ hydratedRoot = hydrateRoot(document, element, { onRecoverableError });
+ });
+
+ return { reset, onRecoverableError };
+}
+
+afterEach(async () => {
+ await act(async () => {
+ hydratedRoot?.unmount();
+ });
+ hydratedRoot = undefined;
+ document.cookie = `${LOCALE_COOKIE}=;path=/;max-age=0`;
+ setBrowserLanguages(["en-US"]);
+ resetDocument();
+});
+
+describe("resolveEmergencyLocale", () => {
+ it("prefers the product locale cookie over browser languages", () => {
+ document.cookie = `${LOCALE_COOKIE}=zh-Hans;path=/`;
+ setBrowserLanguages(["ja-JP"]);
+
+ expect(resolveEmergencyLocale()).toBe("zh-Hans");
+ });
+
+ it("hydrates with the browser locale when no cookie exists", async () => {
+ setBrowserLanguages(["ja-JP", "ja"]);
+ const { reset, onRecoverableError } = await hydrateGlobalError("ja-JP");
+
+ expect(document.documentElement.lang).toBe("ja-JP");
+ expect(document.body).toHaveTextContent("問題が発生しました");
+ expect(document.body).not.toHaveTextContent("Something went wrong");
+ expect(onRecoverableError).not.toHaveBeenCalled();
+
+ await act(async () => {
+ document.querySelector("button")?.click();
+ });
+ expect(reset).toHaveBeenCalledTimes(1);
+ });
+
+ it("hydrates in the cookie locale when the browser and document use another language", async () => {
+ document.cookie = `${LOCALE_COOKIE}=zh-Hans;path=/`;
+ setBrowserLanguages(["ja-JP"]);
+
+ const { onRecoverableError } = await hydrateGlobalError("ja-JP");
+
+ expect(document.documentElement.lang).toBe("zh-CN");
+ expect(document.body).toHaveTextContent("出现了问题");
+ expect(document.querySelector("button")).toHaveTextContent("重新加载");
+ expect(document.body).not.toHaveTextContent("Something went wrong");
+ expect(document.body).not.toHaveTextContent("問題が発生しました");
+ expect(onRecoverableError).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/web/app/global-error.tsx b/apps/web/app/global-error.tsx
index da0e2f7132..24701bfdfd 100644
--- a/apps/web/app/global-error.tsx
+++ b/apps/web/app/global-error.tsx
@@ -1,7 +1,10 @@
"use client";
-import { useEffect } from "react";
+import { useEffect, useState } from "react";
import { captureException } from "@multica/core/analytics";
+import type { SupportedLocale } from "@multica/core/i18n";
+import { resolveEmergencyLocale } from "./emergency-locale";
+import { HTML_LANG } from "@/lib/html-lang";
/**
* Route-level error boundary for the web app. Next.js renders this (replacing
@@ -18,12 +21,19 @@ export default function GlobalError({
error: Error & { digest?: string };
reset: () => void;
}) {
+ const [locale, setLocale] = useState<SupportedLocale | null>(null);
+ const copy = EMERGENCY_COPY[locale ?? "en"];
+
useEffect(() => {
captureException(error, { source: "global-error", digest: error.digest });
+ setLocale(resolveEmergencyLocale());
}, [error]);
return (
- <html>
+ <html
+ lang={locale ? HTML_LANG[locale] : undefined}
+ suppressHydrationWarning
+ >
<body
style={{
display: "flex",
@@ -34,9 +44,9 @@ export default function GlobalError({
}}
>
<div style={{ maxWidth: 420, textAlign: "center" }}>
- <h1 style={{ fontSize: 18, fontWeight: 600 }}>Something went wrong</h1>
+ <h1 style={{ fontSize: 18, fontWeight: 600 }}>{copy.title}</h1>
<p style={{ marginTop: 8, color: "#666" }}>
- The page hit an unexpected error. Try reloading.
+ {copy.description}
</p>
<button
type="button"
@@ -49,10 +59,36 @@ export default function GlobalError({
cursor: "pointer",
}}
>
- Reload
+ {copy.reload}
</button>
</div>
</body>
</html>
);
}
+
+// GlobalError replaces the root layout, so it cannot use the normal i18n
+// provider. Keep this provider-less copy aligned with the corresponding error
+// language in packages/views/locales whenever those translations are revised.
+const EMERGENCY_COPY = {
+ en: {
+ title: "Something went wrong",
+ description: "The page hit an unexpected error. Try reloading.",
+ reload: "Reload",
+ },
+ "zh-Hans": {
+ title: "出现了问题",
+ description: "页面发生意外错误,请尝试重新加载。",
+ reload: "重新加载",
+ },
+ ja: {
+ title: "問題が発生しました",
+ description: "ページで予期しないエラーが発生しました。再読み込みしてください。",
+ reload: "再読み込み",
+ },
+ ko: {
+ title: "문제가 발생했습니다",
+ description: "페이지에서 예기치 않은 오류가 발생했습니다. 다시 불러오세요.",
+ reload: "다시 불러오기",
+ },
+} as const;
diff --git a/apps/web/app/layout.tsx b/apps/web/app/layout.tsx
index 1d45aa9d1b..9f512d7bbf 100644
--- a/apps/web/app/layout.tsx
+++ b/apps/web/app/layout.tsx
@@ -5,9 +5,9 @@ import { ThemeProvider } from "@/components/theme-provider";
import { Toaster } from "@multica/ui/components/ui/sonner";
import { cn } from "@multica/ui/lib/utils";
import { WebProviders } from "@/components/web-providers";
-import type { SupportedLocale } from "@multica/core/i18n";
import { RESOURCES } from "@multica/views/locales";
import { getRequestLocale } from "@/lib/request-locale";
+import { HTML_LANG } from "@/lib/html-lang";
import { SITE_TITLE, TITLE_TEMPLATE } from "@/platform/document-title";
import {
resolveBrowserApiBaseUrl,
@@ -119,17 +119,6 @@ export const metadata: Metadata = {
},
};
-// HTML lang attribute uses BCP-47 region tags that screen readers and font
-// stacks recognize widely. i18next keeps `zh-Hans` as its internal locale
-// (script subtag is what we actually translate against), but the html element
-// expects a region-flavoured tag for accessibility tooling and CJK fallback.
-const HTML_LANG: Record<SupportedLocale, string> = {
- en: "en",
- "zh-Hans": "zh-CN",
- ko: "ko-KR",
- ja: "ja-JP",
-};
-
export default async function RootLayout({
children,
}: {
diff --git a/apps/web/app/not-found.test.tsx b/apps/web/app/not-found.test.tsx
new file mode 100644
index 0000000000..8e906ad827
--- /dev/null
+++ b/apps/web/app/not-found.test.tsx
@@ -0,0 +1,26 @@
+import { render, screen } from "@testing-library/react";
+import { describe, expect, it } from "vitest";
+import { I18nProvider } from "@multica/core/i18n/react";
+import { RESOURCES } from "@multica/views/locales";
+import NotFound from "./not-found";
+
+describe("NotFound", () => {
+ it("renders the not-found page in the selected locale", () => {
+ render(
+ <I18nProvider locale="zh-Hans" resources={RESOURCES}>
+ <NotFound />
+ </I18nProvider>,
+ );
+
+ expect(
+ screen.getByRole("heading", { name: "页面未找到" }),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByText("你要查找的页面不存在或已被移动。"),
+ ).toBeInTheDocument();
+ expect(screen.getByRole("link", { name: "返回 Multica" })).toHaveAttribute(
+ "href",
+ "/",
+ );
+ });
+});
diff --git a/apps/web/app/not-found.tsx b/apps/web/app/not-found.tsx
index 71f47ce16c..96bd7c5a8f 100644
--- a/apps/web/app/not-found.tsx
+++ b/apps/web/app/not-found.tsx
@@ -2,17 +2,21 @@
import Link from "next/link";
import { buttonVariants } from "@multica/ui/components/ui/button";
+import { useT } from "@multica/views/i18n";
export default function NotFound() {
+ const { t } = useT("common");
return (
<main className="flex min-h-screen flex-col items-center justify-center gap-6 px-6 py-24 text-center">
<p className="text-body font-medium text-muted-foreground">404</p>
- <h1 className="text-display-sm font-semibold tracking-tight">Page not found</h1>
+ <h1 className="text-display-sm font-semibold tracking-tight">
+ {t(($) => $.not_found.title)}
+ </h1>
<p className="max-w-md text-body text-muted-foreground">
- The page you are looking for doesn&rsquo;t exist or has been moved.
+ {t(($) => $.not_found.description)}
</p>
<Link href="/" className={buttonVariants({ className: "mt-2" })}>
- Back to Multica
+ {t(($) => $.not_found.back_to_multica)}
</Link>
</main>
);
diff --git a/apps/web/components/web-providers.tsx b/apps/web/components/web-providers.tsx
index 69dc7ffff5..4d223a77e7 100644
--- a/apps/web/components/web-providers.tsx
+++ b/apps/web/components/web-providers.tsx
@@ -13,6 +13,7 @@ import {
clearLoggedInCookie,
} from "@/features/auth/auth-cookie";
import { detectWebOS } from "@/platform/client-os";
+import { useUserLocaleSyncEnabled } from "@/platform/user-locale-sync";
// Legacy token in localStorage → keep this session in token mode so users who
// logged in before the cookie-auth migration stay authed. They migrate to
@@ -58,6 +59,7 @@ export function WebProviders({
wsUrl?: string;
}) {
const cookieAuth = !hasLegacyToken();
+ const syncUserLocale = useUserLocaleSyncEnabled();
// Stable identity reference so downstream effects keyed on it don't see a
// new object on every parent render.
const identity = useMemo(
@@ -85,6 +87,7 @@ export function WebProviders({
locale={locale}
resources={resources}
localeAdapter={localeAdapter}
+ syncUserLocale={syncUserLocale}
>
<WebNavigationProvider>
<WebScrollRestorationProvider>{children}</WebScrollRestorationProvider>
diff --git a/apps/web/lib/html-lang.ts b/apps/web/lib/html-lang.ts
new file mode 100644
index 0000000000..11ae38e4b7
--- /dev/null
+++ b/apps/web/lib/html-lang.ts
@@ -0,0 +1,11 @@
+import type { SupportedLocale } from "@multica/core/i18n";
+
+// HTML lang uses BCP-47 region tags widely recognized by screen readers and
+// font stacks. i18next keeps zh-Hans internally because that is the resource
+// key, while the document uses zh-CN for accessibility and CJK fallback.
+export const HTML_LANG: Record<SupportedLocale, string> = {
+ en: "en",
+ "zh-Hans": "zh-CN",
+ ko: "ko-KR",
+ ja: "ja-JP",
+};
diff --git a/apps/web/platform/user-locale-sync.test.tsx b/apps/web/platform/user-locale-sync.test.tsx
new file mode 100644
index 0000000000..db1fd3967a
--- /dev/null
+++ b/apps/web/platform/user-locale-sync.test.tsx
@@ -0,0 +1,37 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { renderHook } from "@testing-library/react";
+
+const route = vi.hoisted(() => ({ pathname: null as string | null }));
+
+vi.mock("next/navigation", () => ({
+ usePathname: () => route.pathname,
+}));
+
+import { useUserLocaleSyncEnabled } from "./user-locale-sync";
+
+describe("useUserLocaleSyncEnabled", () => {
+ beforeEach(() => {
+ route.pathname = null;
+ });
+
+ it("waits for the callback to finish before resuming locale synchronization", () => {
+ const { result, rerender } = renderHook(useUserLocaleSyncEnabled);
+ expect(result.current).toBe(false);
+
+ route.pathname = "/auth/callback";
+ rerender();
+ expect(result.current).toBe(false);
+
+ route.pathname = "/onboarding";
+ rerender();
+ expect(result.current).toBe(true);
+ });
+
+ it("also pauses on a callback path with a trailing slash", () => {
+ route.pathname = "/auth/callback/";
+
+ const { result } = renderHook(useUserLocaleSyncEnabled);
+
+ expect(result.current).toBe(false);
+ });
+});
diff --git a/apps/web/platform/user-locale-sync.ts b/apps/web/platform/user-locale-sync.ts
new file mode 100644
index 0000000000..6868122ea4
--- /dev/null
+++ b/apps/web/platform/user-locale-sync.ts
@@ -0,0 +1,11 @@
+"use client";
+
+import { usePathname } from "next/navigation";
+import { paths } from "@multica/core/paths";
+
+export function useUserLocaleSyncEnabled(): boolean {
+ const pathname = usePathname();
+ // Account locale synchronization can reload the page. Finish the single-use
+ // OAuth callback before allowing that reload on its destination.
+ return !!pathname && pathname.replace(/\/+$/, "") !== paths.authCallback();
+}
diff --git a/e2e/auth-callback-locale.spec.ts b/e2e/auth-callback-locale.spec.ts
new file mode 100644
index 0000000000..bf1bab4bd1
--- /dev/null
+++ b/e2e/auth-callback-locale.spec.ts
@@ -0,0 +1,165 @@
+import { expect, test } from "@playwright/test";
+
+test.use({ locale: "zh-CN" });
+
+for (const scenario of [
+ {
+ name: "different account language",
+ language: "ja",
+ htmlLang: "ja-JP",
+ continueLabel: "ウェブで続ける",
+ },
+ {
+ name: "same account language",
+ language: "zh-Hans",
+ htmlLang: "zh-CN",
+ continueLabel: "在 web 端继续",
+ },
+]) {
+ test(`Google callback keeps its single-use code while synchronizing ${scenario.name}`, async ({
+ page,
+ context,
+ baseURL,
+ }) => {
+ if (!baseURL) {
+ throw new Error("The callback regression requires a configured baseURL");
+ }
+ const origin = new URL(baseURL).origin;
+ const code = "locale-regression-code";
+ const user = {
+ id: "66666666-6666-4666-8666-666666666666",
+ name: "Callback locale test",
+ email: "[email protected]",
+ avatar_url: null,
+ language: scenario.language,
+ onboarded_at: null,
+ onboarding_questionnaire: {},
+ created_at: "2026-01-01T00:00:00Z",
+ updated_at: "2026-01-01T00:00:00Z",
+ };
+ let authenticated = false;
+ let workspaceRequests = 0;
+ let callbackDocuments = 0;
+ const exchanges: unknown[] = [];
+ const unexpectedApiRequests: string[] = [];
+ const googleRequests: string[] = [];
+ const pageErrors: string[] = [];
+ let completeInitialAuthCheck!: () => void;
+ const initialAuthCheck = new Promise<void>((resolve) => {
+ completeInitialAuthCheck = resolve;
+ });
+ let releaseWorkspaces!: () => void;
+ const workspaceGate = new Promise<void>((resolve) => {
+ releaseWorkspaces = resolve;
+ });
+
+ await context.addCookies([
+ { name: "multica-locale", value: "zh-Hans", url: origin },
+ ]);
+ // Isolate application WebSockets without intercepting Next.js HMR.
+ await context.routeWebSocket(
+ (url) => url.pathname === "/ws",
+ (socket) => socket.close(),
+ );
+ page.on("pageerror", (error) => pageErrors.push(error.message));
+ page.on("request", (request) => {
+ if (
+ request.isNavigationRequest() &&
+ request.frame() === page.mainFrame() &&
+ new URL(request.url()).pathname === "/auth/callback"
+ ) {
+ callbackDocuments += 1;
+ }
+ });
+
+ // Keep the real Next.js page, providers, auth store, and API client. Only
+ // the HTTP boundary is controlled; no Google account or backend rows are used.
+ await context.route("**/*", async (route) => {
+ const request = route.request();
+ const url = new URL(request.url());
+ if (url.origin !== origin) {
+ if (
+ /(^|\.)(google\.com|googleapis\.com|googleusercontent\.com)$/.test(url.hostname)
+ ) {
+ googleRequests.push(request.url());
+ }
+ return route.abort();
+ }
+ const json = (status: number, body: unknown) => route.fulfill({ status, json: body });
+ if (url.pathname === "/auth/google" && request.method() === "POST") {
+ exchanges.push(request.postDataJSON());
+ // A replay must fail, otherwise an accidental callback reload can look successful.
+ if (exchanges.length > 1) {
+ return json(400, {
+ code: "oauth_code_invalid",
+ error: "The test code has already been used",
+ });
+ }
+ await initialAuthCheck;
+ authenticated = true;
+ return json(200, { token: "synthetic-callback-token", user });
+ }
+ if (url.pathname === "/api/config") {
+ return json(200, {
+ allow_signup: true,
+ google_client_id: "callback-test-only",
+ feature_flags: {},
+ });
+ }
+ if (url.pathname === "/api/me") {
+ if (authenticated) return json(200, user);
+ await json(401, { error: "Not authenticated" });
+ completeInitialAuthCheck();
+ return;
+ }
+ if (url.pathname === "/api/workspaces") {
+ workspaceRequests += 1;
+ await workspaceGate;
+ return json(200, []);
+ }
+ if (url.pathname === "/api/invitations") return json(200, []);
+ if (url.pathname === "/api/client-usage") return route.fulfill({ status: 204 });
+ if (url.pathname.startsWith("/api/") || url.pathname === "/auth/google") {
+ unexpectedApiRequests.push(`${request.method()} ${url.pathname}`);
+ return json(500, { error: "Unexpected API request in callback locale test" });
+ }
+ return route.continue();
+ });
+
+ try {
+ await page.goto(`/auth/callback?code=${code}`, { waitUntil: "domcontentloaded" });
+ await expect.poll(() => workspaceRequests).toBeGreaterThan(0);
+ // Let the login render and its passive effects finish while navigation is
+ // blocked by the workspace response, instead of racing a fixed network delay.
+ await page.evaluate(async () => {
+ await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
+ await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
+ });
+ await expect(page).toHaveURL(`${origin}/auth/callback?code=${code}`);
+ expect(exchanges).toEqual([{ code, redirect_uri: `${origin}/auth/callback` }]);
+ expect(callbackDocuments).toBe(1);
+ expect(
+ (await context.cookies(origin)).find((cookie) => cookie.name === "multica-locale")?.value,
+ ).toBe("zh-Hans");
+ releaseWorkspaces();
+
+ await expect(page).toHaveURL(`${origin}/onboarding`, { timeout: 15000 });
+ await expect(page.locator("html")).toHaveAttribute("lang", scenario.htmlLang);
+ await expect(
+ page.getByRole("button", { name: scenario.continueLabel, exact: true }),
+ ).toBeVisible();
+ expect(
+ (await context.cookies(origin)).find((cookie) => cookie.name === "multica-locale")?.value,
+ ).toBe(scenario.language);
+ expect(await page.evaluate(() => localStorage.getItem("multica_token"))).toBeNull();
+ expect(exchanges).toHaveLength(1);
+ expect(callbackDocuments).toBe(1);
+ expect(unexpectedApiRequests).toEqual([]);
+ expect(googleRequests).toEqual([]);
+ expect(pageErrors).toEqual([]);
+ } finally {
+ releaseWorkspaces();
+ await context.unrouteAll({ behavior: "wait" });
+ }
+ });
+}
diff --git a/packages/core/platform/core-provider.tsx b/packages/core/platform/core-provider.tsx
index b8ebec10ea..33cc194dc5 100644
--- a/packages/core/platform/core-provider.tsx
+++ b/packages/core/platform/core-provider.tsx
@@ -94,6 +94,7 @@ export function CoreProvider({
locale,
resources,
localeAdapter,
+ syncUserLocale = true,
}: CoreProviderProps) {
// Initialize singletons on first render only. Dependencies are read-once:
// apiBaseUrl, storage, and callbacks are set at app boot and never change at runtime.
@@ -140,7 +141,7 @@ export function CoreProvider({
// the host app provides one (web layout + desktop App both do).
const withAdapter = localeAdapter ? (
<LocaleAdapterProvider adapter={localeAdapter}>
- <UserLocaleSync />
+ {syncUserLocale && <UserLocaleSync />}
{tree}
</LocaleAdapterProvider>
) : (
diff --git a/packages/core/platform/types.ts b/packages/core/platform/types.ts
index 0ea17a7c66..1da5f079e0 100644
--- a/packages/core/platform/types.ts
+++ b/packages/core/platform/types.ts
@@ -40,4 +40,6 @@ export interface CoreProviderProps {
/** Locale adapter for persisting user choice (used by Settings switcher).
* Optional because some shells (e.g. CLI auth pages) don't need switching. */
localeAdapter?: LocaleAdapter;
+ /** Automatically sync the signed-in user's locale. Pause during one-shot handoffs. Default: true. */
+ syncUserLocale?: boolean;
}
diff --git a/packages/ui/components/common/error-boundary.tsx b/packages/ui/components/common/error-boundary.tsx
index d68e7d6cb0..41a6c79242 100644
--- a/packages/ui/components/common/error-boundary.tsx
+++ b/packages/ui/components/common/error-boundary.tsx
@@ -1,6 +1,7 @@
"use client";
import { Component, type ErrorInfo, type ReactNode } from "react";
+import { useTranslation } from "react-i18next";
import { Button } from "../ui/button";
export interface ErrorBoundaryProps {
@@ -78,6 +79,7 @@ export class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundarySt
}
function DefaultFallback({ error, reset }: { error: Error; reset: () => void }) {
+ const { t } = useTranslation("ui");
return (
<div
role="alert"
@@ -85,14 +87,14 @@ function DefaultFallback({ error, reset }: { error: Error; reset: () => void })
>
<div className="space-y-1">
<p className="font-medium text-foreground">
- Something went wrong displaying this section.
+ {t(($) => $.error_boundary.title)}
</p>
<p className="text-muted-foreground">
- {error.message || "An unexpected error occurred."}
+ {error.message || t(($) => $.error_boundary.description)}
</p>
</div>
<Button size="sm" variant="outline" onClick={reset}>
- Try again
+ {t(($) => $.error_boundary.try_again)}
</Button>
</div>
);
diff --git a/packages/ui/types/i18next.ts b/packages/ui/types/i18next.ts
index e2957eaa9f..93b8905cbd 100644
--- a/packages/ui/types/i18next.ts
+++ b/packages/ui/types/i18next.ts
@@ -21,6 +21,11 @@ declare global {
toggle_sidebar: string;
copy_code: string;
plain_text: string;
+ error_boundary: {
+ title: string;
+ description: string;
+ try_again: string;
+ };
};
}
}
diff --git a/packages/views/locales/en/auth.json b/packages/views/locales/en/auth.json
index a78de97619..fadc547118 100644
--- a/packages/views/locales/en/auth.json
+++ b/packages/views/locales/en/auth.json
@@ -42,6 +42,20 @@
"open_button": "Open Multica Desktop",
"failed_title": "Sign-in Failed",
"prepare_failed": "Failed to prepare Desktop sign-in"
+ },
+ "callback": {
+ "failed_title": "Login Failed",
+ "missing_code": "Missing authorization code",
+ "access_denied": "Access denied",
+ "login_failed": "We couldn't complete your sign-in. Please try again.",
+ "account_disabled": "This account is disabled.",
+ "signup_prohibited": "User registration is disabled on this self-hosted instance.",
+ "email_not_allowed": "This email address or domain is not allowed on this instance.",
+ "google_account_no_email": "Google did not provide an email address for this sign-in.",
+ "oauth_code_invalid": "The Google authorization code is invalid, expired, or has already been used. Sign in again.",
+ "back_to_login": "Back to login",
+ "signing_in": "Signing in...",
+ "signing_in_description": "Please wait while we complete your login"
}
},
"desktop": {
diff --git a/packages/views/locales/en/common.json b/packages/views/locales/en/common.json
index 1d09fe235d..d86d30b847 100644
--- a/packages/views/locales/en/common.json
+++ b/packages/views/locales/en/common.json
@@ -121,6 +121,11 @@
"error_not_member": "You're signed in to a Multica account that isn't a member of this workspace.",
"error_unknown": "Something went wrong. Try again, and if the problem persists, contact the workspace admin."
},
+ "not_found": {
+ "title": "Page not found",
+ "description": "The page you are looking for doesn't exist or has been moved.",
+ "back_to_multica": "Back to Multica"
+ },
"navigation": {
"open_in_new_tab": "Open in new tab"
}
diff --git a/packages/views/locales/en/ui.json b/packages/views/locales/en/ui.json
index c3a69ea8ab..f8ade86a1f 100644
--- a/packages/views/locales/en/ui.json
+++ b/packages/views/locales/en/ui.json
@@ -2,5 +2,10 @@
"attach_file": "Attach file",
"toggle_sidebar": "Toggle left sidebar",
"copy_code": "Copy code",
- "plain_text": "plain text"
+ "plain_text": "plain text",
+ "error_boundary": {
+ "title": "Something went wrong displaying this section.",
+ "description": "An unexpected error occurred.",
+ "try_again": "Try again"
+ }
}
diff --git a/packages/views/locales/ja/auth.json b/packages/views/locales/ja/auth.json
index 9bb381c428..34ebed3610 100644
--- a/packages/views/locales/ja/auth.json
+++ b/packages/views/locales/ja/auth.json
@@ -42,6 +42,20 @@
"open_button": "Multica Desktopを開く",
"failed_title": "ログインに失敗しました",
"prepare_failed": "デスクトップのログインを準備できませんでした"
+ },
+ "callback": {
+ "failed_title": "ログインに失敗しました",
+ "missing_code": "認証コードがありません",
+ "access_denied": "アクセスが拒否されました",
+ "login_failed": "ログインを完了できませんでした。もう一度お試しください。",
+ "account_disabled": "このアカウントは無効になっています。",
+ "signup_prohibited": "このセルフホストインスタンスではユーザー登録が無効になっています。",
+ "email_not_allowed": "このメールアドレスまたはドメインは、このインスタンスでは許可されていません。",
+ "google_account_no_email": "Googleから今回のログインに必要なメールアドレスが提供されませんでした。",
+ "oauth_code_invalid": "Googleの認証コードが無効、期限切れ、または使用済みです。もう一度ログインしてください。",
+ "back_to_login": "ログインに戻る",
+ "signing_in": "ログイン中…",
+ "signing_in_description": "ログインが完了するまでお待ちください"
}
},
"desktop": {
diff --git a/packages/views/locales/ja/common.json b/packages/views/locales/ja/common.json
index 93affc6eb8..539a4aa790 100644
--- a/packages/views/locales/ja/common.json
+++ b/packages/views/locales/ja/common.json
@@ -121,6 +121,11 @@
"error_not_member": "サインインしている Multica アカウントはこのワークスペースのメンバーではありません。",
"error_unknown": "問題が発生しました。もう一度試し、それでも解決しない場合はワークスペース管理者にお問い合わせください。"
},
+ "not_found": {
+ "title": "ページが見つかりません",
+ "description": "お探しのページは存在しないか、移動しました。",
+ "back_to_multica": "Multicaに戻る"
+ },
"navigation": {
"open_in_new_tab": "新しいタブで開く"
}
diff --git a/packages/views/locales/ja/ui.json b/packages/views/locales/ja/ui.json
index dbfd027c14..5f89d5ee1c 100644
--- a/packages/views/locales/ja/ui.json
+++ b/packages/views/locales/ja/ui.json
@@ -2,5 +2,10 @@
"attach_file": "ファイルを添付",
"toggle_sidebar": "左サイドバーの開閉",
"copy_code": "コードをコピー",
- "plain_text": "プレーンテキスト"
+ "plain_text": "プレーンテキスト",
+ "error_boundary": {
+ "title": "このセクションを表示できませんでした。",
+ "description": "予期しないエラーが発生しました。",
+ "try_again": "もう一度試す"
+ }
}
diff --git a/packages/views/locales/ko/auth.json b/packages/views/locales/ko/auth.json
index 021e2041c0..aa59932371 100644
--- a/packages/views/locales/ko/auth.json
+++ b/packages/views/locales/ko/auth.json
@@ -42,6 +42,20 @@
"open_button": "Multica Desktop 열기",
"failed_title": "로그인 실패",
"prepare_failed": "데스크톱 로그인을 준비하지 못했습니다"
+ },
+ "callback": {
+ "failed_title": "로그인하지 못했습니다",
+ "missing_code": "인증 코드가 없습니다",
+ "access_denied": "접근이 거부되었습니다",
+ "login_failed": "로그인을 완료하지 못했습니다. 다시 시도하세요.",
+ "account_disabled": "이 계정은 비활성화되었습니다.",
+ "signup_prohibited": "이 자체 호스팅 인스턴스에서는 사용자 등록이 비활성화되어 있습니다.",
+ "email_not_allowed": "이 이메일 주소 또는 도메인은 이 인스턴스에서 허용되지 않습니다.",
+ "google_account_no_email": "Google에서 이번 로그인에 필요한 이메일 주소를 제공하지 않았습니다.",
+ "oauth_code_invalid": "Google 인증 코드가 유효하지 않거나 만료되었거나 이미 사용되었습니다. 다시 로그인하세요.",
+ "back_to_login": "로그인으로 돌아가기",
+ "signing_in": "로그인 중…",
+ "signing_in_description": "로그인을 완료하는 동안 잠시 기다려 주세요"
}
},
"desktop": {
diff --git a/packages/views/locales/ko/common.json b/packages/views/locales/ko/common.json
index 9ed448be07..d06b923ee4 100644
--- a/packages/views/locales/ko/common.json
+++ b/packages/views/locales/ko/common.json
@@ -121,6 +121,11 @@
"error_not_member": "로그인한 Multica 계정이 이 워크스페이스의 멤버가 아니에요.",
"error_unknown": "문제가 발생했어요. 다시 시도해 보고, 계속되면 워크스페이스 관리자에게 문의하세요."
},
+ "not_found": {
+ "title": "페이지를 찾을 수 없습니다",
+ "description": "찾으시는 페이지가 없거나 이동되었습니다.",
+ "back_to_multica": "Multica로 돌아가기"
+ },
"navigation": {
"open_in_new_tab": "새 탭에서 열기"
}
diff --git a/packages/views/locales/ko/ui.json b/packages/views/locales/ko/ui.json
index 5ee0375bf7..32ddec6346 100644
--- a/packages/views/locales/ko/ui.json
+++ b/packages/views/locales/ko/ui.json
@@ -2,5 +2,10 @@
"attach_file": "파일 첨부",
"toggle_sidebar": "왼쪽 사이드바 열기/닫기",
"copy_code": "코드 복사",
- "plain_text": "일반 텍스트"
+ "plain_text": "일반 텍스트",
+ "error_boundary": {
+ "title": "이 섹션을 표시하는 중 문제가 발생했습니다.",
+ "description": "예기치 않은 오류가 발생했습니다.",
+ "try_again": "다시 시도"
+ }
}
diff --git a/packages/views/locales/zh-Hans/auth.json b/packages/views/locales/zh-Hans/auth.json
index 065013ad44..54d324814c 100644
--- a/packages/views/locales/zh-Hans/auth.json
+++ b/packages/views/locales/zh-Hans/auth.json
@@ -42,6 +42,20 @@
"open_button": "打开 Multica 桌面应用",
"failed_title": "登录失败",
"prepare_failed": "桌面登录准备失败"
+ },
+ "callback": {
+ "failed_title": "登录失败",
+ "missing_code": "缺少授权码",
+ "access_denied": "访问被拒绝",
+ "login_failed": "无法完成登录,请重试。",
+ "account_disabled": "此账号已被停用。",
+ "signup_prohibited": "此自托管实例已禁止用户注册。",
+ "email_not_allowed": "此实例不允许使用该邮箱地址或域名。",
+ "google_account_no_email": "Google 未提供本次登录所需的邮箱地址。",
+ "oauth_code_invalid": "Google 授权码无效、已过期或已被使用,请重新登录。",
+ "back_to_login": "返回登录",
+ "signing_in": "正在登录...",
+ "signing_in_description": "正在完成登录,请稍候"
}
},
"desktop": {
diff --git a/packages/views/locales/zh-Hans/common.json b/packages/views/locales/zh-Hans/common.json
index 68f33ca01b..eb6782a93a 100644
--- a/packages/views/locales/zh-Hans/common.json
+++ b/packages/views/locales/zh-Hans/common.json
@@ -121,6 +121,11 @@
"error_not_member": "你登录的 Multica 账号不是当前工作区成员。",
"error_unknown": "出现未知错误。请稍后再试,如反复失败请联系工作区管理员。"
},
+ "not_found": {
+ "title": "页面未找到",
+ "description": "你要查找的页面不存在或已被移动。",
+ "back_to_multica": "返回 Multica"
+ },
"navigation": {
"open_in_new_tab": "在新标签页打开"
}
diff --git a/packages/views/locales/zh-Hans/ui.json b/packages/views/locales/zh-Hans/ui.json
index 83744b43b2..92646debca 100644
--- a/packages/views/locales/zh-Hans/ui.json
+++ b/packages/views/locales/zh-Hans/ui.json
@@ -2,5 +2,10 @@
"attach_file": "添加附件",
"toggle_sidebar": "切换左侧边栏",
"copy_code": "复制代码",
- "plain_text": "纯文本"
+ "plain_text": "纯文本",
+ "error_boundary": {
+ "title": "此区域显示时出现问题。",
+ "description": "发生了意外错误。",
+ "try_again": "重试"
+ }
}
diff --git a/server/internal/handler/auth.go b/server/internal/handler/auth.go
index 3832fdb17f..89e88192b3 100644
--- a/server/internal/handler/auth.go
+++ b/server/internal/handler/auth.go
@@ -38,6 +38,14 @@ func (e SignupError) Error() string {
var ErrSignupProhibited = SignupError{Message: "user registration is disabled on this self-hosted instance"}
var ErrEmailNotAllowed = SignupError{Message: "email address or domain not allowed on this instance"}
+const (
+ googleLoginCodeAccountDisabled = "account_disabled"
+ googleLoginCodeSignupProhibited = "signup_prohibited"
+ googleLoginCodeEmailNotAllowed = "email_not_allowed"
+ googleLoginCodeAccountWithoutEmail = "google_account_no_email"
+ googleLoginCodeInvalidOAuthCode = "oauth_code_invalid"
+)
+
const devVerificationCodeEnv = "MULTICA_DEV_VERIFICATION_CODE"
// supportedLanguages mirrors `SUPPORTED_LOCALES` in packages/core/i18n/types.ts.
@@ -260,7 +268,7 @@ func (h *Handler) checkSignupAllowed(email string, isNewUser bool) error {
// 4. if allowlists are set but didn't match, block
if len(h.cfg.AllowedEmailDomains) > 0 || len(h.cfg.AllowedEmails) > 0 {
- return ErrSignupProhibited
+ return ErrEmailNotAllowed
}
return nil
@@ -491,6 +499,32 @@ type googleUserInfo struct {
Picture string `json:"picture"`
}
+func writeGoogleLoginActionableError(w http.ResponseWriter, err error) bool {
+ switch {
+ case errors.Is(err, auth.ErrTemporarilyDisabledUser):
+ writeErrorCode(w, http.StatusForbidden, googleLoginCodeAccountDisabled, auth.TemporarilyDisabledUserError)
+ case errors.Is(err, ErrSignupProhibited):
+ writeErrorCode(w, http.StatusForbidden, googleLoginCodeSignupProhibited, ErrSignupProhibited.Error())
+ case errors.Is(err, ErrEmailNotAllowed):
+ writeErrorCode(w, http.StatusForbidden, googleLoginCodeEmailNotAllowed, ErrEmailNotAllowed.Error())
+ default:
+ var signupErr SignupError
+ if !errors.As(err, &signupErr) {
+ return false
+ }
+ // Preserve the actionable fallback for signup restrictions without a code.
+ writeError(w, http.StatusForbidden, signupErr.Error())
+ }
+ return true
+}
+
+func (h *Handler) googleHTTPClient() *http.Client {
+ if h.googleOAuthHTTPClient != nil {
+ return h.googleOAuthHTTPClient
+ }
+ return http.DefaultClient
+}
+
func (h *Handler) GoogleLogin(w http.ResponseWriter, r *http.Request) {
var req GoogleLoginRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
@@ -516,7 +550,7 @@ func (h *Handler) GoogleLogin(w http.ResponseWriter, r *http.Request) {
}
// Exchange authorization code for tokens.
- tokenResp, err := http.PostForm("https://oauth2.googleapis.com/token", url.Values{
+ tokenResp, err := h.googleHTTPClient().PostForm("https://oauth2.googleapis.com/token", url.Values{
"code": {req.Code},
"client_id": {clientID},
"client_secret": {clientSecret},
@@ -538,7 +572,17 @@ func (h *Handler) GoogleLogin(w http.ResponseWriter, r *http.Request) {
if tokenResp.StatusCode != http.StatusOK {
slog.Error("google oauth token exchange returned error", "status", tokenResp.StatusCode, "body", string(tokenBody))
- writeError(w, http.StatusBadRequest, "failed to exchange code with Google")
+ var tokenErr struct {
+ Error string `json:"error"`
+ }
+ // Only a valid invalid_grant response identifies a rejected authorization
+ // code. Configuration, provider and malformed responses are server failures.
+ if err := json.Unmarshal(tokenBody, &tokenErr); err == nil &&
+ tokenResp.StatusCode == http.StatusBadRequest && tokenErr.Error == "invalid_grant" {
+ writeErrorCode(w, http.StatusBadRequest, googleLoginCodeInvalidOAuthCode, "failed to exchange code with Google")
+ return
+ }
+ writeError(w, http.StatusBadGateway, "failed to exchange code with Google")
return
}
@@ -547,6 +591,11 @@ func (h *Handler) GoogleLogin(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusBadGateway, "failed to parse Google token response")
return
}
+ if strings.TrimSpace(gToken.AccessToken) == "" {
+ slog.Error("google oauth token response has no access token")
+ writeError(w, http.StatusBadGateway, "invalid Google token response")
+ return
+ }
// Fetch user info from Google.
userInfoReq, err := http.NewRequestWithContext(r.Context(), http.MethodGet, "https://www.googleapis.com/oauth2/v2/userinfo", nil)
@@ -557,7 +606,7 @@ func (h *Handler) GoogleLogin(w http.ResponseWriter, r *http.Request) {
}
userInfoReq.Header.Set("Authorization", "Bearer "+gToken.AccessToken)
- userInfoResp, err := http.DefaultClient.Do(userInfoReq)
+ userInfoResp, err := h.googleHTTPClient().Do(userInfoReq)
if err != nil {
slog.Error("google userinfo fetch failed", "error", err)
writeError(w, http.StatusBadGateway, "failed to fetch user info from Google")
@@ -565,32 +614,41 @@ func (h *Handler) GoogleLogin(w http.ResponseWriter, r *http.Request) {
}
defer userInfoResp.Body.Close()
- var gUser googleUserInfo
+ if userInfoResp.StatusCode != http.StatusOK {
+ body, readErr := io.ReadAll(io.LimitReader(userInfoResp.Body, 4096))
+ if readErr != nil {
+ slog.Error("google userinfo error response could not be read", "status", userInfoResp.StatusCode, "error", readErr)
+ } else {
+ slog.Error("google userinfo returned error", "status", userInfoResp.StatusCode, "body", string(body))
+ }
+ writeError(w, http.StatusBadGateway, "failed to fetch user info from Google")
+ return
+ }
+
+ var gUser *googleUserInfo
if err := json.NewDecoder(userInfoResp.Body).Decode(&gUser); err != nil {
writeError(w, http.StatusBadGateway, "failed to parse Google user info")
return
}
-
- if gUser.Email == "" {
- writeError(w, http.StatusBadRequest, "Google account has no email")
+ if gUser == nil {
+ writeError(w, http.StatusBadGateway, "invalid Google user info")
return
}
email := strings.ToLower(strings.TrimSpace(gUser.Email))
+ if email == "" {
+ writeErrorCode(w, http.StatusBadRequest, googleLoginCodeAccountWithoutEmail, "Google did not provide an email address for this sign-in")
+ return
+ }
+
if auth.IsTemporarilyDisabledUserEmail(email) {
- writeError(w, http.StatusForbidden, auth.TemporarilyDisabledUserError)
+ writeErrorCode(w, http.StatusForbidden, googleLoginCodeAccountDisabled, auth.TemporarilyDisabledUserError)
return
}
user, isNew, err := h.findOrCreateUser(r.Context(), email)
if err != nil {
- if errors.Is(err, auth.ErrTemporarilyDisabledUser) {
- writeError(w, http.StatusForbidden, auth.TemporarilyDisabledUserError)
- return
- }
- var signupErr SignupError
- if errors.As(err, &signupErr) {
- writeError(w, http.StatusForbidden, signupErr.Error())
+ if writeGoogleLoginActionableError(w, err) {
return
}
writeError(w, http.StatusInternalServerError, "failed to create user")
@@ -630,8 +688,7 @@ func (h *Handler) GoogleLogin(w http.ResponseWriter, r *http.Request) {
tokenString, err := h.issueJWT(user)
if err != nil {
- if errors.Is(err, auth.ErrTemporarilyDisabledUser) {
- writeError(w, http.StatusForbidden, auth.TemporarilyDisabledUserError)
+ if writeGoogleLoginActionableError(w, err) {
return
}
slog.Warn("google login failed", append(logger.RequestAttrs(r), "error", err, "email", email)...)
diff --git a/server/internal/handler/auth_google_error_code_test.go b/server/internal/handler/auth_google_error_code_test.go
new file mode 100644
index 0000000000..f0c85a50c4
--- /dev/null
+++ b/server/internal/handler/auth_google_error_code_test.go
@@ -0,0 +1,322 @@
+package handler
+
+import (
+ "bytes"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "testing/iotest"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/multica-ai/multica/server/internal/auth"
+ "github.com/multica-ai/multica/server/internal/middleware"
+ "github.com/multica-ai/multica/server/internal/testutil"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+type googleRoundTripper func(*http.Request) (*http.Response, error)
+
+func (fn googleRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
+ return fn(req)
+}
+
+func googleResponse(req *http.Request, status int, body string) *http.Response {
+ return &http.Response{
+ StatusCode: status,
+ Header: make(http.Header),
+ Body: io.NopCloser(strings.NewReader(body)),
+ Request: req,
+ }
+}
+
+func TestGoogleLoginTokenFailures(t *testing.T) {
+ t.Setenv("GOOGLE_CLIENT_ID", "test-client")
+ t.Setenv("GOOGLE_CLIENT_SECRET", "test-secret")
+ tests := []struct {
+ name string
+ status int
+ body string
+ readErr error
+ requestErr error
+ wantStatus int
+ wantCode string
+ }{
+ {name: "invalid grant", status: 400, body: `{"error":"invalid_grant"}`, wantStatus: 400, wantCode: "oauth_code_invalid"},
+ {name: "invalid client", status: 401, body: `{"error":"invalid_client"}`, wantStatus: 502},
+ {name: "redirect mismatch", status: 400, body: `{"error":"redirect_uri_mismatch"}`, wantStatus: 502},
+ {name: "unauthorized client", status: 400, body: `{"error":"unauthorized_client"}`, wantStatus: 502},
+ {name: "deleted client", status: 401, body: `{"error":"deleted_client"}`, wantStatus: 502},
+ {name: "unknown provider error", status: 400, body: `{"error":"future_error"}`, wantStatus: 502},
+ {name: "rate limited", status: 429, body: `{"error":"rate_limit_exceeded"}`, wantStatus: 502},
+ {name: "provider unavailable", status: 503, body: `{"error":"temporarily_unavailable"}`, wantStatus: 502},
+ {name: "5xx takes precedence over invalid grant", status: 500, body: `{"error":"invalid_grant"}`, wantStatus: 502},
+ {name: "malformed provider error", status: 400, body: `<html>bad gateway</html>`, wantStatus: 502},
+ {name: "partially decoded provider error", status: 400, body: `{"error":"invalid_grant","error":42}`, wantStatus: 502},
+ {name: "empty provider error", status: 400, wantStatus: 502},
+ {name: "malformed token", status: 200, body: `{`, wantStatus: 502},
+ {name: "missing access token", status: 200, body: `{}`, wantStatus: 502},
+ {name: "null token", status: 200, body: `null`, wantStatus: 502},
+ {name: "empty access token", status: 200, body: `{"access_token":""}`, wantStatus: 502},
+ {name: "wrong access token type", status: 200, body: `{"access_token":42}`, wantStatus: 502},
+ {name: "read failure", status: 200, readErr: io.ErrUnexpectedEOF, wantStatus: 502},
+ {name: "transport failure", requestErr: errors.New("provider unavailable"), wantStatus: 502},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ h := newTestHandler(Config{})
+ h.googleOAuthHTTPClient = &http.Client{Transport: googleRoundTripper(func(req *http.Request) (*http.Response, error) {
+ if req.URL.Host != "oauth2.googleapis.com" {
+ t.Fatalf("token failure must not fetch userinfo: %s", req.URL)
+ }
+ if tt.requestErr != nil {
+ return nil, tt.requestErr
+ }
+ resp := googleResponse(req, tt.status, tt.body)
+ if tt.readErr != nil {
+ resp.Body = io.NopCloser(iotest.ErrReader(tt.readErr))
+ }
+ return resp, nil
+ })}
+ req := httptest.NewRequest(http.MethodPost, "/auth/google", strings.NewReader(`{"code":"test-code"}`))
+ var got struct {
+ Error string `json:"error"`
+ Code string `json:"code"`
+ }
+ testutil.Call(t, h.GoogleLogin, req).Want(tt.wantStatus).JSON(&got)
+ if got.Code != tt.wantCode || got.Error == "" {
+ t.Fatalf("got code=%q error=%q, want code=%q and a fallback message", got.Code, got.Error, tt.wantCode)
+ }
+ })
+ }
+}
+
+func TestGoogleLoginUserInfoFailures(t *testing.T) {
+ t.Setenv("GOOGLE_CLIENT_ID", "test-client")
+ t.Setenv("GOOGLE_CLIENT_SECRET", "test-secret")
+ tests := []struct {
+ name string
+ status int
+ body string
+ readErr error
+ requestErr error
+ wantStatus int
+ wantCode string
+ }{
+ {name: "unauthorized", status: 401, body: `{"error":{"code":401,"status":"UNAUTHENTICATED"}}`, wantStatus: 502},
+ {name: "forbidden", status: 403, body: `{"error":{"code":403}}`, wantStatus: 502},
+ {name: "rate limited", status: 429, body: `{"error":{"code":429}}`, wantStatus: 502},
+ {name: "provider unavailable", status: 503, body: `{"error":{"code":503}}`, wantStatus: 502},
+ {name: "error status with profile fields", status: 500, body: `{"email":"[email protected]"}`, wantStatus: 502},
+ {name: "non-JSON provider failure", status: 502, body: `<html>bad gateway</html>`, wantStatus: 502},
+ {name: "missing email on a successful response", status: 200, body: `{"name":"No Email"}`, wantStatus: 400, wantCode: "google_account_no_email"},
+ {name: "blank email on a successful response", status: 200, body: `{"email":" "}`, wantStatus: 400, wantCode: "google_account_no_email"},
+ {name: "null profile", status: 200, body: `null`, wantStatus: 502},
+ {name: "malformed profile", status: 200, body: `{`, wantStatus: 502},
+ {name: "wrong email type", status: 200, body: `{"email":42}`, wantStatus: 502},
+ {name: "empty profile response", status: 200, wantStatus: 502},
+ {name: "read failure", status: 200, readErr: io.ErrUnexpectedEOF, wantStatus: 502},
+ {name: "unreadable provider failure", status: 503, readErr: io.ErrUnexpectedEOF, wantStatus: 502},
+ {name: "transport failure", requestErr: errors.New("provider unavailable"), wantStatus: 502},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ h := newTestHandler(Config{})
+ h.googleOAuthHTTPClient = &http.Client{Transport: googleRoundTripper(func(req *http.Request) (*http.Response, error) {
+ switch req.URL.Host {
+ case "oauth2.googleapis.com":
+ return googleResponse(req, http.StatusOK, `{"access_token":"test-token"}`), nil
+ case "www.googleapis.com":
+ if tt.requestErr != nil {
+ return nil, tt.requestErr
+ }
+ resp := googleResponse(req, tt.status, tt.body)
+ if tt.readErr != nil {
+ resp.Body = io.NopCloser(iotest.ErrReader(tt.readErr))
+ }
+ return resp, nil
+ default:
+ t.Fatalf("unexpected Google OAuth request: %s", req.URL)
+ return nil, nil
+ }
+ })}
+ req := httptest.NewRequest(http.MethodPost, "/auth/google", strings.NewReader(`{"code":"test-code"}`))
+ var got struct {
+ Error string `json:"error"`
+ Code string `json:"code"`
+ }
+ testutil.Call(t, h.GoogleLogin, req).Want(tt.wantStatus).JSON(&got)
+ if got.Code != tt.wantCode || got.Error == "" {
+ t.Fatalf("got code=%q error=%q, want code=%q and a fallback message", got.Code, got.Error, tt.wantCode)
+ }
+ })
+ }
+}
+
+func TestGoogleLoginActionableErrorCodes(t *testing.T) {
+ t.Setenv("GOOGLE_CLIENT_ID", "test-client")
+ t.Setenv("GOOGLE_CLIENT_SECRET", "test-secret")
+
+ tests := []struct {
+ name string
+ cfg Config
+ userBody string
+ wantStatus int
+ wantCode string
+ wantError string
+ }{
+ {
+ name: "signup prohibited",
+ cfg: Config{AllowSignup: false},
+ userBody: `{"email":"[email protected]"}`,
+ wantStatus: http.StatusForbidden,
+ wantCode: "signup_prohibited",
+ wantError: "user registration is disabled on this self-hosted instance",
+ },
+ {
+ name: "email not allowed",
+ cfg: Config{AllowSignup: true, AllowedEmailDomains: []string{"company.com"}},
+ userBody: `{"email":"[email protected]"}`,
+ wantStatus: http.StatusForbidden,
+ wantCode: "email_not_allowed",
+ wantError: "email address or domain not allowed on this instance",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ h := newTestHandler(tt.cfg)
+ h.Queries = db.New(&mockDB{getUserErr: pgx.ErrNoRows})
+
+ h.googleOAuthHTTPClient = &http.Client{Transport: googleRoundTripper(func(req *http.Request) (*http.Response, error) {
+ switch req.URL.Host {
+ case "oauth2.googleapis.com":
+ return googleResponse(req, http.StatusOK, `{"access_token":"test-token"}`), nil
+ case "www.googleapis.com":
+ return googleResponse(req, http.StatusOK, tt.userBody), nil
+ default:
+ t.Fatalf("unexpected Google OAuth request: %s", req.URL)
+ return nil, nil
+ }
+ })}
+
+ req := httptest.NewRequest(
+ http.MethodPost,
+ "/auth/google",
+ bytes.NewBufferString(`{"code":"test-code","redirect_uri":"http://localhost/auth/callback"}`),
+ )
+ var got struct {
+ Error string `json:"error"`
+ Code string `json:"code"`
+ }
+ testutil.Call(t, h.GoogleLogin, req).Want(tt.wantStatus).JSON(&got)
+ if got.Code != tt.wantCode || got.Error != tt.wantError {
+ t.Fatalf("got code=%q error=%q, want code=%q error=%q", got.Code, got.Error, tt.wantCode, tt.wantError)
+ }
+ })
+ }
+}
+
+func TestGoogleLoginActionableErrorMapping(t *testing.T) {
+ tests := []struct {
+ name string
+ err error
+ wantCode string
+ wantError string
+ }{
+ {"account disabled", auth.ErrTemporarilyDisabledUser, "account_disabled", "account disabled"},
+ {"signup prohibited", ErrSignupProhibited, "signup_prohibited", ErrSignupProhibited.Error()},
+ {"email not allowed", ErrEmailNotAllowed, "email_not_allowed", ErrEmailNotAllowed.Error()},
+ {"wrapped signup restriction", fmt.Errorf("signup: %w", ErrEmailNotAllowed), "email_not_allowed", ErrEmailNotAllowed.Error()},
+ {"future signup restriction", SignupError{Message: "another signup restriction"}, "", "another signup restriction"},
+ {"wrapped future signup restriction", fmt.Errorf("signup: %w", SignupError{Message: "another signup restriction"}), "", "another signup restriction"},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ var got struct {
+ Error string `json:"error"`
+ Code string `json:"code"`
+ }
+ req := httptest.NewRequest(http.MethodGet, "/auth/google", nil)
+ testutil.Call(t, func(w http.ResponseWriter, _ *http.Request) {
+ if !writeGoogleLoginActionableError(w, tt.err) {
+ t.Fatalf("actionable error was not handled: %v", tt.err)
+ }
+ }, req).Want(http.StatusForbidden).JSON(&got)
+ if got.Code != tt.wantCode || got.Error != tt.wantError {
+ t.Fatalf("got code=%q error=%q, want code=%q error=%q", got.Code, got.Error, tt.wantCode, tt.wantError)
+ }
+ })
+ }
+}
+
+func TestGoogleLoginSuccessfulExistingUser(t *testing.T) {
+ t.Setenv("GOOGLE_CLIENT_ID", "test-client")
+ t.Setenv("GOOGLE_CLIENT_SECRET", "test-secret")
+ email := "[email protected]"
+ userID := dbfx.User(t, "Google OAuth User", email)
+ // Existing users can still sign in when new registrations are restricted.
+ h := newTestHandler(Config{AllowSignup: false, AllowedEmailDomains: []string{"company.com"}})
+ h.Queries = testHandler.Queries
+ requests := 0
+ h.googleOAuthHTTPClient = &http.Client{Transport: googleRoundTripper(func(req *http.Request) (*http.Response, error) {
+ requests++
+ switch req.URL.Host {
+ case "oauth2.googleapis.com":
+ if err := req.ParseForm(); err != nil {
+ t.Fatal(err)
+ }
+ if req.Form.Get("code") != "test-code" || req.Form.Get("redirect_uri") != "http://localhost/auth/callback" {
+ t.Fatalf("unexpected token exchange form: %v", req.Form)
+ }
+ return googleResponse(req, http.StatusOK, `{"access_token":"test-token"}`), nil
+ case "www.googleapis.com":
+ if req.Header.Get("Authorization") != "Bearer test-token" {
+ t.Fatal("userinfo request did not use the exchanged token")
+ }
+ return googleResponse(req, http.StatusOK, `{"email":" [email protected] "}`), nil
+ default:
+ t.Fatalf("unexpected Google OAuth request: %s", req.URL)
+ return nil, nil
+ }
+ })}
+ req := httptest.NewRequest(http.MethodPost, "/auth/google", strings.NewReader(`{"code":"test-code","redirect_uri":"http://localhost/auth/callback"}`))
+ var got LoginResponse
+ resp := testutil.Call(t, h.GoogleLogin, req).Want(http.StatusOK).JSON(&got)
+ if requests != 2 || got.Token == "" || got.User.ID != userID || got.User.Email != email {
+ t.Fatalf("unexpected successful login: requests=%d, token present=%t, user=%+v", requests, got.Token != "", got.User)
+ }
+ var authCookie, csrfCookie *http.Cookie
+ for _, cookie := range resp.Result().Cookies() {
+ switch cookie.Name {
+ case auth.AuthCookieName:
+ authCookie = cookie
+ case auth.CSRFCookieName:
+ csrfCookie = cookie
+ }
+ }
+ if authCookie == nil || authCookie.Value != got.Token || csrfCookie == nil || csrfCookie.Value == "" {
+ t.Fatal("successful Google login must return matching auth and CSRF cookies")
+ }
+
+ // Exercise the issued JWT through the same middleware that accepts browser sessions.
+ meReq := httptest.NewRequest(http.MethodGet, "/users/me", nil)
+ meReq.AddCookie(authCookie)
+ protected := middleware.Auth(h.Queries, nil, nil)(http.HandlerFunc(h.GetMe))
+ var me UserResponse
+ testutil.Call(t, protected.ServeHTTP, meReq).Want(http.StatusOK).JSON(&me)
+ if me.ID != userID || me.Email != email {
+ t.Fatalf("Google session resolved to the wrong user: %+v", me)
+ }
+
+ csrfReq := httptest.NewRequest(http.MethodPost, "/users/me", nil)
+ csrfReq.AddCookie(authCookie)
+ csrfReq.Header.Set("X-CSRF-Token", csrfCookie.Value)
+ if !auth.ValidateCSRF(csrfReq) {
+ t.Fatal("Google login cookies must allow authenticated browser writes")
+ }
+}
diff --git a/server/internal/handler/auth_signup_test.go b/server/internal/handler/auth_signup_test.go
index 227dcaf6d5..587445caf1 100644
--- a/server/internal/handler/auth_signup_test.go
+++ b/server/internal/handler/auth_signup_test.go
@@ -2,11 +2,14 @@ package handler
import (
"context"
+ "errors"
+ "net/http"
"strings"
"testing"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
+ "github.com/multica-ai/multica/server/internal/testutil"
db "github.com/multica-ai/multica/server/pkg/db/generated"
)
@@ -18,26 +21,66 @@ func newTestHandler(cfg Config) *Handler {
func TestSignupGating(t *testing.T) {
tests := []struct {
- name string
- cfg Config
- email string
- isNew bool
- wantErr bool
+ name string
+ cfg Config
+ email string
+ isNew bool
+ want error
}{
- {"allow_signup_true_new", Config{AllowSignup: true}, "[email protected]", true, false},
- {"allow_signup_false_new", Config{AllowSignup: false}, "[email protected]", true, true},
- {"allow_signup_false_existing", Config{AllowSignup: false}, "[email protected]", false, false},
- {"domain_allowlist_match", Config{AllowSignup: false, AllowedEmailDomains: []string{"company.com"}}, "[email protected]", true, false},
- {"domain_allowlist_mismatch", Config{AllowSignup: false, AllowedEmailDomains: []string{"company.com"}}, "[email protected]", true, true},
- {"email_allowlist_match", Config{AllowSignup: false, AllowedEmails: []string{"[email protected]"}}, "[email protected]", true, false},
+ {"allow_signup_true_new", Config{AllowSignup: true}, "[email protected]", true, nil},
+ {"allow_signup_false_new", Config{AllowSignup: false}, "[email protected]", true, ErrSignupProhibited},
+ {"allow_signup_false_existing", Config{AllowSignup: false}, "[email protected]", false, nil},
+ {"domain_allowlist_match", Config{AllowSignup: false, AllowedEmailDomains: []string{"company.com"}}, "[email protected]", true, nil},
+ {"domain_allowlist_mismatch_signup_disabled", Config{AllowSignup: false, AllowedEmailDomains: []string{"company.com"}}, "[email protected]", true, ErrSignupProhibited},
+ {"domain_allowlist_mismatch_signup_enabled", Config{AllowSignup: true, AllowedEmailDomains: []string{"company.com"}}, "[email protected]", true, ErrEmailNotAllowed},
+ {"email_allowlist_match", Config{AllowSignup: false, AllowedEmails: []string{"[email protected]"}}, "[email protected]", true, nil},
+ {"email_allowlist_mismatch_signup_enabled", Config{AllowSignup: true, AllowedEmails: []string{"[email protected]"}}, "[email protected]", true, ErrEmailNotAllowed},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
h := newTestHandler(tt.cfg)
err := h.checkSignupAllowed(tt.email, tt.isNew)
- if (err != nil) != tt.wantErr {
- t.Fatalf("got err=%v wantErr=%v", err, tt.wantErr)
+ if !errors.Is(err, tt.want) {
+ t.Fatalf("got err=%v want=%v", err, tt.want)
+ }
+ })
+ }
+}
+
+func TestEmailCodeAllowlistErrors(t *testing.T) {
+ for _, path := range []string{"send-code", "verify-code"} {
+ t.Run(path, func(t *testing.T) {
+ email := path + "[email protected]"
+ h := newTestHandler(Config{AllowSignup: true, AllowedEmailDomains: []string{"company.com"}})
+ h.Queries = testHandler.Queries
+ dbfx.Cleanup(t, `DELETE FROM "user" WHERE email = $1`, email)
+ body := map[string]string{"email": email}
+ handler := h.SendCode
+ if path == "verify-code" {
+ // A code can remain valid after the instance's signup policy changes.
+ body["code"] = "123456"
+ dbfx.Insert(t, "verification_code", testutil.Cols{
+ "email": email,
+ "code": body["code"],
+ "expires_at": testutil.Raw("now() + interval '10 minutes'"),
+ })
+ handler = h.VerifyCode
+ }
+ req := testutil.JSONRequest(http.MethodPost, "/auth/"+path, body)
+ resp := testutil.Call(t, handler, req).Want(http.StatusForbidden)
+ got := resp.Map()
+ if got["error"] != ErrEmailNotAllowed.Error() {
+ t.Fatalf("expected an actionable allowlist error, got %v", got)
+ }
+ if _, hasCode := got["code"]; hasCode {
+ t.Fatal("email-code errors must retain their existing response shape")
+ }
+ if len(resp.Result().Cookies()) != 0 {
+ t.Fatal("rejected signup must not establish an authenticated session")
+ }
+ if count := dbfx.Count(t, `SELECT count(*) FROM "user" WHERE email = $1`, email); count != 0 {
+ t.Fatalf("rejected signup created %d users", count)
}
})
}
diff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.go
index 72b547bce5..726a270814 100644
--- a/server/internal/handler/handler.go
+++ b/server/internal/handler/handler.go
@@ -235,6 +235,8 @@ type Handler struct {
InvitationRateLimiters InvitationRateLimiters
WebhookDeliveryWorker *WebhookDeliveryWorker
CloudRuntime cloudRuntimeProxy
+ // Test-only HTTP override; nil uses the default client in production.
+ googleOAuthHTTPClient *http.Client
// Lark integration. All three are nil when the Lark master key
// (MULTICA_LARK_SECRET_KEY) is unset; the corresponding HTTP
// handlers return 503 in that case so a misconfigured self-host