Memos is an open-source, self-hosted note-taking app that brings your everyday thoughts together in a personal timeline. Your data stays yours, and you choose what to keep private or share.
Go dockerfossgomarkdownmemomicroblognote-takingnotesopen-sourceown-your-datareactself-hostedsqlitetimeline
feat(auth): automatically start SSO when it is the only option (#6450)
Johnnyd5df8915f70a
diff --git a/web/src/components/IdentityProviderButtons.tsx b/web/src/components/IdentityProviderButtons.tsxindex 997337c40..d03c25406 100644--- a/web/src/components/IdentityProviderButtons.tsx+++ b/web/src/components/IdentityProviderButtons.tsx@@ -1,62 +1,98 @@+import { LoaderIcon } from "lucide-react";+import { useCallback, useEffect, useRef, useState } from "react";import { toast } from "react-hot-toast";+import { useSearchParams } from "react-router-dom";import { Button } from "@/components/ui/button";-import { absolutifyLink } from "@/lib/browser";import { handleError } from "@/lib/error";-import { ROUTES } from "@/router/routes";-import { IdentityProvider, IdentityProvider_Type } from "@/types/proto/api/idp_service_pb";+import { IdentityProvider } from "@/types/proto/api/idp_service_pb";+import { AUTH_AUTO_SIGN_IN_PARAM } from "@/utils/auth-redirect";import { useTranslate } from "@/utils/i18n";-import { storeOAuthState } from "@/utils/oauth";+import { getSSOConfig, signInWithSSO } from "@/utils/sso";interface Props {identityProviderList: IdentityProvider[];redirectTarget?: string;+ autoSignIn?: boolean;}-const IdentityProviderButtons = ({ identityProviderList, redirectTarget }: Props) => {+const IdentityProviderButtons = ({ identityProviderList, redirectTarget, autoSignIn = false }: Props) => {const t = useTranslate();+ const [searchParams, setSearchParams] = useSearchParams();+ const [pendingProvider, setPendingProvider] = useState<IdentityProvider>();+ const pendingRef = useRef(false);+ const automaticAttemptedRef = useRef(false);- const handleSignInWithIdentityProvider = async (identityProvider: IdentityProvider) => {- if (identityProvider.type === IdentityProvider_Type.OAUTH2) {- const redirectUri = absolutifyLink(ROUTES.AUTH_CALLBACK);- const oauth2Config = identityProvider.config?.config?.case === "oauth2Config" ? identityProvider.config.config.value : undefined;- if (!oauth2Config) {- toast.error("Identity provider configuration is invalid.");- return;- }-+ const handleSignInWithIdentityProvider = useCallback(+ async (identityProvider: IdentityProvider) => {+ if (pendingRef.current) return;+ pendingRef.current = true;+ setPendingProvider(identityProvider);try {- // Generate and store secure state parameter with CSRF protection- // Also generate PKCE parameters (code_challenge) for enhanced security if available- const { state, codeChallenge } = await storeOAuthState(identityProvider.name, "signin", redirectTarget);-- // Build OAuth authorization URL with secure state- // Include PKCE if available (requires HTTPS/localhost for crypto.subtle)- // Using S256 (SHA-256) as the code_challenge_method per RFC 7636- let authUrl = `${oauth2Config.authUrl}?client_id=${- oauth2Config.clientId- }&redirect_uri=${encodeURIComponent(redirectUri)}&state=${state}&response_type=code&scope=${encodeURIComponent(- oauth2Config.scopes.join(" "),- )}`;-- // Add PKCE parameters if available- if (codeChallenge) {- authUrl += `&code_challenge=${codeChallenge}&code_challenge_method=S256`;- }-- window.location.href = authUrl;+ // Mark this history entry before leaving, so Back/reload offers manual sign-in.+ setSearchParams(+ (previous) => {+ const next = new URLSearchParams(previous);+ next.set(AUTH_AUTO_SIGN_IN_PARAM, "false");+ return next;+ },+ { replace: true },+ );+ await signInWithSSO(identityProvider, redirectTarget);} catch (error) {+ pendingRef.current = false;+ setPendingProvider(undefined);handleError(error, toast.error, {context: "Failed to initiate OAuth flow",fallbackMessage: "Failed to initiate sign-in. Please try again.",});}+ },+ [redirectTarget, setSearchParams],+ );++ useEffect(() => {+ const provider = identityProviderList[0];+ if (+ !autoSignIn ||+ identityProviderList.length !== 1 ||+ !provider ||+ !getSSOConfig(provider) ||+ searchParams.get(AUTH_AUTO_SIGN_IN_PARAM) === "false" ||+ automaticAttemptedRef.current+ ) {+ return;}- };+ automaticAttemptedRef.current = true;+ void handleSignInWithIdentityProvider(provider);+ }, [autoSignIn, identityProviderList, searchParams, handleSignInWithIdentityProvider]);++ useEffect(() => {+ // Back may restore the page from bfcache with React's pending state intact.+ const onPageShow = (event: PageTransitionEvent) => {+ if (event.persisted) {+ pendingRef.current = false;+ setPendingProvider(undefined);+ }+ };+ window.addEventListener("pageshow", onPageShow);+ return () => window.removeEventListener("pageshow", onPageShow);+ }, []);return (<div className="flex w-full flex-col gap-2">+ {pendingProvider && (+ <p className="flex items-center justify-center gap-2 text-sm text-muted-foreground">+ <LoaderIcon className="h-4 w-4 animate-spin motion-reduce:animate-none" aria-hidden="true" />+ {t("auth.redirecting-to-provider", { provider: pendingProvider.title })}+ </p>+ )}{identityProviderList.map((identityProvider) => (- <Button key={identityProvider.name} variant="outline" onClick={() => handleSignInWithIdentityProvider(identityProvider)}>+ <Button+ key={identityProvider.name}+ variant="outline"+ disabled={Boolean(pendingProvider)}+ onClick={() => void handleSignInWithIdentityProvider(identityProvider)}+ >{t("auth.continue-with", { provider: identityProvider.title })}</Button>))}diff --git a/web/src/components/UserMenu.tsx b/web/src/components/UserMenu.tsxindex 6b48ec940..aa58230ed 100644--- a/web/src/components/UserMenu.tsx+++ b/web/src/components/UserMenu.tsx@@ -30,6 +30,7 @@ import { locales } from "@/i18n";import { cn } from "@/lib/utils";import { Routes } from "@/router";import { UserNotification_Status } from "@/types/proto/api/user_service_pb";+import { buildAuthRoute } from "@/utils/auth-redirect";import { getLocaleDisplayName, getLocaleWithFallback, loadLocale, useTranslate } from "@/utils/i18n";import { getThemeWithFallback, loadTheme, THEME_OPTIONS } from "@/utils/theme";@@ -166,7 +167,7 @@ const UserMenu = ({ onClose }: { onClose: () => void }) => {} catch {// Ignore errors from localStorage operations.}- window.location.replace(Routes.AUTH);+ window.location.replace(buildAuthRoute({ autoSignIn: false }));};return (diff --git a/web/src/hooks/useIdentityProviderQueries.ts b/web/src/hooks/useIdentityProviderQueries.tsindex cabd48eeb..af57baeb4 100644--- a/web/src/hooks/useIdentityProviderQueries.ts+++ b/web/src/hooks/useIdentityProviderQueries.ts@@ -13,7 +13,7 @@ const EMPTY_LIST: IdentityProvider[] = [];// Hook to fetch the configured identity providers. Pass `enabled: false` on// pages/branches that never render provider buttons to skip the request.export function useIdentityProviderList(enabled = true) {- const { data, isLoading } = useQuery({+ const { data, isLoading, isSuccess } = useQuery({queryKey: identityProviderKeys.list(),queryFn: async () => (await identityProviderServiceClient.listIdentityProviders({})).identityProviders,staleTime: 60_000,@@ -22,5 +22,6 @@ export function useIdentityProviderList(enabled = true) {return {identityProviderList: data ?? EMPTY_LIST,isLoading,+ isSuccess,};}diff --git a/web/src/locales/ar.json b/web/src/locales/ar.jsonindex eb9231484..e24d4cc2f 100644--- a/web/src/locales/ar.json+++ b/web/src/locales/ar.json@@ -24,6 +24,7 @@"auth": {"create-your-account": "أنشئ حسابك","new-password": "كلمة المرور الجديدة",+ "redirecting-to-provider": "جارٍ إعادة التوجيه إلى {{provider}}…","repeat-new-password": "أعد كلمة المرور الجديدة","sign-in-tip": "هل لديك حساب بالفعل؟","sign-up-tip": "ليس لديك حساب بعد؟",diff --git a/web/src/locales/az.json b/web/src/locales/az.jsonindex b8b4dd6d2..1bcbd54fe 100644--- a/web/src/locales/az.json+++ b/web/src/locales/az.json@@ -49,6 +49,7 @@"explore-public-memos": "Bu instansdakı ictimai qeydləri kəşf edin","first-run": "İlk işə salma","new-password": "Yeni parol",+ "redirecting-to-provider": "{{provider}} xidmətinə yönləndirilir…","repeat-new-password": "Yeni parolu təkrarlayın","setup-description": "Bu instans üçün administrator hesabı yaradın.","setup-note": "Bu hesab instans parametrlərinə, üzvlərə və kimlik provayderlərinə sahib olur.",diff --git a/web/src/locales/bg.json b/web/src/locales/bg.jsonindex 4f1f01f5e..18b2e8ee4 100644--- a/web/src/locales/bg.json+++ b/web/src/locales/bg.json@@ -24,6 +24,7 @@"auth": {"create-your-account": "Създайте своя акаунт","new-password": "Нова парола",+ "redirecting-to-provider": "Пренасочване към {{provider}}…","repeat-new-password": "Повторете новата парола","sign-in-tip": "Вече имате акаунт?","sign-up-tip": "Все още нямате акаунт?",diff --git a/web/src/locales/ca.json b/web/src/locales/ca.jsonindex 9ed48c61d..f5bcf9b12 100644--- a/web/src/locales/ca.json+++ b/web/src/locales/ca.json@@ -24,6 +24,7 @@"auth": {"create-your-account": "Crea el teu compte","new-password": "Nova contrasenya",+ "redirecting-to-provider": "S’està redirigint a {{provider}}…","repeat-new-password": "Repeteix la contrasenya","sign-in-tip": "Ja tens un compte?","sign-up-tip": "Encara no tens un compte?",diff --git a/web/src/locales/cs.json b/web/src/locales/cs.jsonindex add9d55c8..1182552f6 100644--- a/web/src/locales/cs.json+++ b/web/src/locales/cs.json@@ -24,6 +24,7 @@"auth": {"create-your-account": "Založit nový účet","new-password": "Nové heslo",+ "redirecting-to-provider": "Přesměrování na {{provider}}…","repeat-new-password": "Zopakujte nové heslo","sign-in-tip": "Už máte účet?","sign-up-tip": "Ještě nemáte účet?",diff --git a/web/src/locales/da.json b/web/src/locales/da.jsonindex 5b612dd93..cf02f2549 100644--- a/web/src/locales/da.json+++ b/web/src/locales/da.json@@ -24,6 +24,7 @@"auth": {"create-your-account": "Opret din konto","new-password": "Ny adgangskode",+ "redirecting-to-provider": "Omdirigerer til {{provider}}…","repeat-new-password": "Gentag den nye adgangskode","sign-in-tip": "Har du allerede en konto?","sign-up-tip": "Har du ikke en konto endnu?",diff --git a/web/src/locales/de.json b/web/src/locales/de.jsonindex c27fd7be4..37460a4a3 100644--- a/web/src/locales/de.json+++ b/web/src/locales/de.json@@ -24,6 +24,7 @@"auth": {"create-your-account": "Benutzerkonto anlegen","new-password": "Neues Passwort",+ "redirecting-to-provider": "Weiterleitung zu {{provider}}…","repeat-new-password": "Neues Passwort wiederholen","sign-in-tip": "Bereits ein Benutzerkonto?","sign-up-tip": "Noch kein Benutzerkonto?",diff --git a/web/src/locales/el.json b/web/src/locales/el.jsonindex 6980a94df..157941b4c 100644--- a/web/src/locales/el.json+++ b/web/src/locales/el.json@@ -24,6 +24,7 @@"auth": {"create-your-account": "Δημιουργήστε τον λογαριασμό σας","new-password": "Νέος κωδικός πρόσβασης",+ "redirecting-to-provider": "Ανακατεύθυνση στο {{provider}}…","repeat-new-password": "Επαναλάβετε τον νέο κωδικό πρόσβασης","sign-in-tip": "Έχετε ήδη λογαριασμό;","sign-up-tip": "Δεν έχετε λογαριασμό ακόμα;",diff --git a/web/src/locales/en-GB.json b/web/src/locales/en-GB.jsonindex f10a377ee..628fc8ffc 100644--- a/web/src/locales/en-GB.json+++ b/web/src/locales/en-GB.json@@ -24,6 +24,7 @@"auth": {"create-your-account": "Create your account","new-password": "New password",+ "redirecting-to-provider": "Redirecting to {{provider}}…","repeat-new-password": "Repeat the new password","sign-in-tip": "Already have an account?","sign-up-tip": "Don't have an account yet?",diff --git a/web/src/locales/en.json b/web/src/locales/en.jsonindex 97d9f0a56..85af9e0a4 100644--- a/web/src/locales/en.json+++ b/web/src/locales/en.json@@ -49,6 +49,7 @@"explore-public-memos": "Explore public memos on this instance","first-run": "First run","new-password": "New password",+ "redirecting-to-provider": "Redirecting to {{provider}}…","repeat-new-password": "Repeat the new password","setup-description": "Create the administrator account for this instance.","setup-note": "This account owns instance settings, members, and identity providers.",diff --git a/web/src/locales/es.json b/web/src/locales/es.jsonindex fe6c313c8..a002aba74 100644--- a/web/src/locales/es.json+++ b/web/src/locales/es.json@@ -24,6 +24,7 @@"auth": {"create-your-account": "Crea tu cuenta","new-password": "Nueva contraseña",+ "redirecting-to-provider": "Redirigiendo a {{provider}}…","repeat-new-password": "Repite la nueva contraseña","sign-in-tip": "¿Ya tienes una cuenta?","sign-up-tip": "¿Aún no tienes una cuenta?",diff --git a/web/src/locales/et.json b/web/src/locales/et.jsonindex 9c7ef9a85..8e56861f4 100644--- a/web/src/locales/et.json+++ b/web/src/locales/et.json@@ -24,6 +24,7 @@"auth": {"create-your-account": "Looge oma konto","new-password": "Uus parool",+ "redirecting-to-provider": "Suunamine teenusesse {{provider}}…","repeat-new-password": "Korrake uut parooli","sign-in-tip": "Kas teil on juba konto?","sign-up-tip": "Kas teil pole veel kontot?",diff --git a/web/src/locales/fa.json b/web/src/locales/fa.jsonindex 70737f8bb..155bf070d 100644--- a/web/src/locales/fa.json+++ b/web/src/locales/fa.json@@ -24,6 +24,7 @@"auth": {"create-your-account": "حساب کاربری خود را ایجاد کنید.","new-password": "گذرواژه جدید",+ "redirecting-to-provider": "در حال هدایت به {{provider}}…","repeat-new-password": "گذرواژه جدید را تکرار کنید","sign-in-tip": "آیا حساب کاربری تعریف شده دارید؟","sign-up-tip": "آیا حساب کاربری تعریف شده ندارید؟",diff --git a/web/src/locales/fi.json b/web/src/locales/fi.jsonindex 915308cc3..25e0dd503 100644--- a/web/src/locales/fi.json+++ b/web/src/locales/fi.json@@ -24,6 +24,7 @@"auth": {"create-your-account": "Luo tili","new-password": "Uusi salasana",+ "redirecting-to-provider": "Ohjataan palveluun {{provider}}…","repeat-new-password": "Toista uusi salasana","sign-in-tip": "Onko sinulla jo tili?","sign-up-tip": "Eikö sinulla ole vielä tiliä?",diff --git a/web/src/locales/fr.json b/web/src/locales/fr.jsonindex 2687bf582..fdde2cea9 100644--- a/web/src/locales/fr.json+++ b/web/src/locales/fr.json@@ -24,6 +24,7 @@"auth": {"create-your-account": "Créez votre compte","new-password": "Nouveau mot de passe",+ "redirecting-to-provider": "Redirection vers {{provider}}…","repeat-new-password": "Répétez le nouveau mot de passe","sign-in-tip": "Vous avez déjà un compte ?","sign-up-tip": "Vous n'avez pas encore de compte ?",diff --git a/web/src/locales/gl.json b/web/src/locales/gl.jsonindex 8fe823765..a5f3486d4 100644--- a/web/src/locales/gl.json+++ b/web/src/locales/gl.json@@ -24,6 +24,7 @@"auth": {"create-your-account": "Crea a túa conta","new-password": "Novo contrasinal",+ "redirecting-to-provider": "Redirixindo a {{provider}}…","repeat-new-password": "Repite o novo contrasinal","sign-in-tip": "Xa tes unha conta?","sign-up-tip": "Aínda non tes unha conta?",diff --git a/web/src/locales/he.json b/web/src/locales/he.jsonindex be88433fc..2cff12d35 100644--- a/web/src/locales/he.json+++ b/web/src/locales/he.json@@ -31,6 +31,7 @@"explore-public-memos": "עיינו בפתקים הציבוריים במופע הזה","first-run": "הפעלה ראשונה","new-password": "סיסמה חדשה",+ "redirecting-to-provider": "מעבר אל {{provider}}…","repeat-new-password": "הקלידו שוב את הסיסמה החדשה","setup-description": "צרו את חשבון המנהל עבור המופע הזה.","setup-note": "חשבון זה מנהל את הגדרות המופע, החברים וספקי הזהות.",diff --git a/web/src/locales/hi.json b/web/src/locales/hi.jsonindex f4d3c9290..913ce544a 100644--- a/web/src/locales/hi.json+++ b/web/src/locales/hi.json@@ -24,6 +24,7 @@"auth": {"create-your-account": "अपना खाता बनाएं","new-password": "नया पासवर्ड",+ "redirecting-to-provider": "{{provider}} पर भेजा जा रहा है…","repeat-new-password": "नया पासवर्ड दोहराएं","sign-in-tip": "क्या आपके पास पहले से खाता है?","sign-up-tip": "अभी तक खाता नहीं है?",diff --git a/web/src/locales/hr.json b/web/src/locales/hr.jsonindex 6f4bc9b27..9db823d36 100644--- a/web/src/locales/hr.json+++ b/web/src/locales/hr.json@@ -24,6 +24,7 @@"auth": {"create-your-account": "Stvori svoj račun","new-password": "Nova lozinka",+ "redirecting-to-provider": "Preusmjeravanje na {{provider}}…","repeat-new-password": "Ponovi novu lozinku","sign-in-tip": "Račun već postoji?","sign-up-tip": "Još nemaš račun?",diff --git a/web/src/locales/hu.json b/web/src/locales/hu.jsonindex 7de970a1f..aeb69c76f 100644--- a/web/src/locales/hu.json+++ b/web/src/locales/hu.json@@ -24,6 +24,7 @@"auth": {"create-your-account": "Fiók létrehozása","new-password": "Új jelszó",+ "redirecting-to-provider": "Átirányítás ide: {{provider}}…","repeat-new-password": "Jelszó ismét","sign-in-tip": "Már van fiókod?","sign-up-tip": "Még nincs fiókod?",diff --git a/web/src/locales/id.json b/web/src/locales/id.jsonindex c84fb9409..fd91e5b97 100644--- a/web/src/locales/id.json+++ b/web/src/locales/id.json@@ -24,6 +24,7 @@"auth": {"create-your-account": "Buat akun Anda","new-password": "Kata sandi baru",+ "redirecting-to-provider": "Mengalihkan ke {{provider}}…","repeat-new-password": "Ulangi kata sandi baru","sign-in-tip": "Sudah memiliki akun?","sign-up-tip": "Belum memiliki akun?",diff --git a/web/src/locales/it.json b/web/src/locales/it.jsonindex 2c71d5cf2..5e2973174 100644--- a/web/src/locales/it.json+++ b/web/src/locales/it.json@@ -24,6 +24,7 @@"auth": {"create-your-account": "Crea il tuo account","new-password": "Nuova password",+ "redirecting-to-provider": "Reindirizzamento a {{provider}}…","repeat-new-password": "Ripeti la nuova password","sign-in-tip": "Hai già un account?","sign-up-tip": "Non hai ancora un account?",diff --git a/web/src/locales/ja.json b/web/src/locales/ja.jsonindex ce7a54831..fc0867569 100644--- a/web/src/locales/ja.json+++ b/web/src/locales/ja.json@@ -31,6 +31,7 @@"explore-public-memos": "このインスタンスの公開メモを見る","first-run": "初回起動","new-password": "新しいパスワード",+ "redirecting-to-provider": "{{provider}} にリダイレクトしています…","repeat-new-password": "新しいパスワードを再入力","setup-description": "このインスタンスの管理者アカウントを作成します。","setup-note": "このアカウントはインスタンスの設定、メンバー、IDプロバイダーを管理します。",diff --git a/web/src/locales/ka-GE.json b/web/src/locales/ka-GE.jsonindex 0d2619a15..2f8ac0aca 100644--- a/web/src/locales/ka-GE.json+++ b/web/src/locales/ka-GE.json@@ -24,6 +24,7 @@"auth": {"create-your-account": "შექმენით თქვენი ანგარიში","new-password": "ახალი პაროლი",+ "redirecting-to-provider": "გადამისამართება {{provider}}-ზე…","repeat-new-password": "გაიმეორეთ ახალი პაროლი","sign-in-tip": "დაქვემდებარებული გაქვთ ანგარიში?","sign-up-tip": "ჯერ არ გაქვთ ანგარიში?",diff --git a/web/src/locales/ko.json b/web/src/locales/ko.jsonindex 9ebdede33..fb510e9b2 100644--- a/web/src/locales/ko.json+++ b/web/src/locales/ko.json@@ -24,6 +24,7 @@"auth": {"create-your-account": "계정 만들기","new-password": "새 비밀번호",+ "redirecting-to-provider": "{{provider}}(으)로 이동 중…","repeat-new-password": "새 비밀번호 재확인","sign-in-tip": "이미 계정이 있으신가요?","sign-up-tip": "아직 계정이 없으신가요?",diff --git a/web/src/locales/lt.json b/web/src/locales/lt.jsonindex 0b9dfdbd2..d78dbc61c 100644--- a/web/src/locales/lt.json+++ b/web/src/locales/lt.json@@ -24,6 +24,7 @@"auth": {"create-your-account": "Susikurkite paskyrą","new-password": "Naujas slaptažodis",+ "redirecting-to-provider": "Nukreipiama į {{provider}}…","repeat-new-password": "Pakartokite naują slaptažodį","sign-in-tip": "Jau turite paskyrą?","sign-up-tip": "Dar neturite paskyros?",diff --git a/web/src/locales/lv.json b/web/src/locales/lv.jsonindex 391380a3d..5ba230cb4 100644--- a/web/src/locales/lv.json+++ b/web/src/locales/lv.json@@ -24,6 +24,7 @@"auth": {"create-your-account": "Izveidojiet savu kontu","new-password": "Jauna parole",+ "redirecting-to-provider": "Pāradresēšana uz {{provider}}…","repeat-new-password": "Atkārtojiet jauno paroli","sign-in-tip": "Vai jums jau ir konts?","sign-up-tip": "Vai jums vēl nav konta?",diff --git a/web/src/locales/mr.json b/web/src/locales/mr.jsonindex 563065014..fcca833ba 100644--- a/web/src/locales/mr.json+++ b/web/src/locales/mr.json@@ -24,6 +24,7 @@"auth": {"create-your-account": "तुमचे खाते तयार करा","new-password": "नवीन पासवर्ड",+ "redirecting-to-provider": "{{provider}} कडे पुनर्निर्देशित करत आहे…","repeat-new-password": "नवीन पासवर्डची पुनरावृत्ती करा","sign-in-tip": "आधीपासूनच एक खाते आहे?","sign-up-tip": "अजून खाते नाही?",diff --git a/web/src/locales/nb.json b/web/src/locales/nb.jsonindex 87b7a6559..7e1a9bb3f 100644--- a/web/src/locales/nb.json+++ b/web/src/locales/nb.json@@ -24,6 +24,7 @@"auth": {"create-your-account": "Opprett konto","new-password": "Nytt passord",+ "redirecting-to-provider": "Videresender til {{provider}}…","repeat-new-password": "Gjenta det nye passordet","sign-in-tip": "Har du allerede en konto?","sign-up-tip": "Har du ikke en konto enda?",diff --git a/web/src/locales/nl.json b/web/src/locales/nl.jsonindex 17a8c5dd1..43ee8ad5e 100644--- a/web/src/locales/nl.json+++ b/web/src/locales/nl.json@@ -24,6 +24,7 @@"auth": {"create-your-account": "Maak je account","new-password": "Nieuw wachtwoord",+ "redirecting-to-provider": "Doorsturen naar {{provider}}…","repeat-new-password": "Nieuw wachtwoord herhalen","sign-in-tip": "Al een account?","sign-up-tip": "Nog geen account?",diff --git a/web/src/locales/nn.json b/web/src/locales/nn.jsonindex 71516196e..61f1caf5b 100644--- a/web/src/locales/nn.json+++ b/web/src/locales/nn.json@@ -97,6 +97,7 @@"explore-public-memos": "Utforsk offentlege notat på denne instansen","first-run": "Fyrste oppstart","new-password": "Nytt passord",+ "redirecting-to-provider": "Vidaresender til {{provider}}…","repeat-new-password": "Skriv det nye passordet ein gong til","setup-description": "Opprett administratorkontoen for denne instansen.","setup-note": "Denne kontoen rår over instansinnstillingar, medlemer og identitetstilbydarar.",diff --git a/web/src/locales/pl.json b/web/src/locales/pl.jsonindex 7b10b2ee4..83dc7f1e3 100644--- a/web/src/locales/pl.json+++ b/web/src/locales/pl.json@@ -24,6 +24,7 @@"auth": {"create-your-account": "Utwórz konto","new-password": "Nowe hasło",+ "redirecting-to-provider": "Przekierowywanie do {{provider}}…","repeat-new-password": "Powtórz nowe hasło","sign-in-tip": "Masz już konto?","sign-up-tip": "Nie masz jeszcze konta?",diff --git a/web/src/locales/pt-BR.json b/web/src/locales/pt-BR.jsonindex 2d1997959..9cb700995 100644--- a/web/src/locales/pt-BR.json+++ b/web/src/locales/pt-BR.json@@ -24,6 +24,7 @@"auth": {"create-your-account": "Crie sua conta","new-password": "Nova senha",+ "redirecting-to-provider": "Redirecionando para {{provider}}…","repeat-new-password": "Repita a nova senha","sign-in-tip": "Já tem uma conta?","sign-up-tip": "Ainda não tem uma conta?",diff --git a/web/src/locales/pt-PT.json b/web/src/locales/pt-PT.jsonindex 18493425d..a5c60e5e2 100644--- a/web/src/locales/pt-PT.json+++ b/web/src/locales/pt-PT.json@@ -24,6 +24,7 @@"auth": {"create-your-account": "Crie a sua conta","new-password": "Nova palavra-passe",+ "redirecting-to-provider": "A redirecionar para {{provider}}…","repeat-new-password": "Repita a nova palavra-passe","sign-in-tip": "Já tem uma conta?","sign-up-tip": "Ainda não tem uma conta?",diff --git a/web/src/locales/ro.json b/web/src/locales/ro.jsonindex 033be16cf..72d54893b 100644--- a/web/src/locales/ro.json+++ b/web/src/locales/ro.json@@ -24,6 +24,7 @@"auth": {"create-your-account": "Creați-vă contul","new-password": "Parolă Nouă",+ "redirecting-to-provider": "Se redirecționează către {{provider}}…","repeat-new-password": "Repetați noua parolă","sign-in-tip": "Aveți deja un cont?","sign-up-tip": "Nu aveți încă un cont?",diff --git a/web/src/locales/ru.json b/web/src/locales/ru.jsonindex 7ee66987f..260fe51b0 100644--- a/web/src/locales/ru.json+++ b/web/src/locales/ru.json@@ -24,6 +24,7 @@"auth": {"create-your-account": "Создание учетной записи","new-password": "Новый пароль",+ "redirecting-to-provider": "Перенаправление в {{provider}}…","repeat-new-password": "Повторить новый пароль","sign-in-tip": "У вас уже есть учетная запись?","sign-up-tip": "У вас еще нет учетной записи?",diff --git a/web/src/locales/sk.json b/web/src/locales/sk.jsonindex 595c19098..39624ceaa 100644--- a/web/src/locales/sk.json+++ b/web/src/locales/sk.json@@ -24,6 +24,7 @@"auth": {"create-your-account": "Vytvorte si účet","new-password": "Nové heslo",+ "redirecting-to-provider": "Presmerovanie na {{provider}}…","repeat-new-password": "Zopakujte nové heslo","sign-in-tip": "Už máte účet?","sign-up-tip": "Ešte nemáte účet?",diff --git a/web/src/locales/sl.json b/web/src/locales/sl.jsonindex ff793037e..e352be992 100644--- a/web/src/locales/sl.json+++ b/web/src/locales/sl.json@@ -24,6 +24,7 @@"auth": {"create-your-account": "Ustvari nov račun","new-password": "Novo geslo",+ "redirecting-to-provider": "Preusmerjanje na {{provider}}…","repeat-new-password": "Ponovi novo geslo","sign-in-tip": "Že imaš račun?","sign-up-tip": "Še nimaš računa?",diff --git a/web/src/locales/sr.json b/web/src/locales/sr.jsonindex 2460be242..506fdefae 100644--- a/web/src/locales/sr.json+++ b/web/src/locales/sr.json@@ -24,6 +24,7 @@"auth": {"create-your-account": "Креирајте свој налог","new-password": "Нова лозинка",+ "redirecting-to-provider": "Преусмеравање на {{provider}}…","repeat-new-password": "Поновите нову лозинку","sign-in-tip": "Већ имате налог?","sign-up-tip": "Још увек немате налог?",diff --git a/web/src/locales/sv.json b/web/src/locales/sv.jsonindex a68f72ba8..b9fb11f0e 100644--- a/web/src/locales/sv.json+++ b/web/src/locales/sv.json@@ -24,6 +24,7 @@"auth": {"create-your-account": "Skapa ditt konto","new-password": "Nytt lösenord",+ "redirecting-to-provider": "Omdirigerar till {{provider}}…","repeat-new-password": "Upprepa det nya lösenordet","sign-in-tip": "Har du redan ett konto?","sign-up-tip": "Har du inget konto än?",diff --git a/web/src/locales/th.json b/web/src/locales/th.jsonindex 9544123c0..cabef847f 100644--- a/web/src/locales/th.json+++ b/web/src/locales/th.json@@ -24,6 +24,7 @@"auth": {"create-your-account": "สร้างบัญชีใหม่","new-password": "รหัสผ่านใหม่",+ "redirecting-to-provider": "กำลังเปลี่ยนเส้นทางไปยัง {{provider}}…","repeat-new-password": "รหัสผ่านใหม่อีกครั้ง","sign-in-tip": "มีบัญชีอยู่แล้ว?","sign-up-tip": "ยังไม่มีบัญชี?",diff --git a/web/src/locales/tr.json b/web/src/locales/tr.jsonindex 90692a804..28a95cfbd 100644--- a/web/src/locales/tr.json+++ b/web/src/locales/tr.json@@ -49,6 +49,7 @@"explore-public-memos": "Bu sunucudaki herkese açık notları keşfedin","first-run": "İlk çalıştırma","new-password": "Yeni şifre",+ "redirecting-to-provider": "{{provider}} hizmetine yönlendiriliyor…","repeat-new-password": "Yeni şifreyi tekrar girin","setup-description": "Bu sunucu için yönetici hesabını oluşturun.","setup-note": "Bu hesap sunucu ayarlarının, üyelerin ve kimlik sağlayıcıların sahibidir.",diff --git a/web/src/locales/uk.json b/web/src/locales/uk.jsonindex 592791a80..c1dacb0bf 100644--- a/web/src/locales/uk.json+++ b/web/src/locales/uk.json@@ -24,6 +24,7 @@"auth": {"create-your-account": "Створіть обліковий запис","new-password": "Новий пароль",+ "redirecting-to-provider": "Перенаправлення до {{provider}}…","repeat-new-password": "Повторіть новий пароль","sign-in-tip": "Вже маєте обліковий запис?","sign-up-tip": "Ще не маєте облікового запису?",diff --git a/web/src/locales/vi.json b/web/src/locales/vi.jsonindex c0482a9d5..2e3b1ae59 100644--- a/web/src/locales/vi.json+++ b/web/src/locales/vi.json@@ -24,6 +24,7 @@"auth": {"create-your-account": "Tạo tài khoản của bạn","new-password": "Mật khẩu mới",+ "redirecting-to-provider": "Đang chuyển hướng đến {{provider}}…","repeat-new-password": "Nhập lại mật khẩu mới","sign-in-tip": "Đã có tài khoản?","sign-up-tip": "Chưa có tài khoản?",diff --git a/web/src/locales/zh-Hans.json b/web/src/locales/zh-Hans.jsonindex e9d1aa26e..bf465c1e5 100644--- a/web/src/locales/zh-Hans.json+++ b/web/src/locales/zh-Hans.json@@ -49,6 +49,7 @@"explore-public-memos": "浏览此实例上的公开 Memo","first-run": "首次运行","new-password": "新密码",+ "redirecting-to-provider": "正在跳转至 {{provider}}…","repeat-new-password": "重复新密码","setup-description": "为此实例创建管理员账号。","setup-note": "该账号拥有实例设置、成员与身份提供商的管理权限。",diff --git a/web/src/locales/zh-Hant.json b/web/src/locales/zh-Hant.jsonindex fab9ca3c8..fcba2bf8c 100644--- a/web/src/locales/zh-Hant.json+++ b/web/src/locales/zh-Hant.json@@ -31,6 +31,7 @@"explore-public-memos": "瀏覽此實例的公開備忘錄","first-run": "初次啟動","new-password": "新密碼",+ "redirecting-to-provider": "正在跳轉至 {{provider}}…","repeat-new-password": "再次輸入新密碼","setup-description": "為此實例建立管理員帳號。","setup-note": "此帳號擁有實例設定、成員與身分識別提供者的管理權限。",diff --git a/web/src/pages/AuthCallback.tsx b/web/src/pages/AuthCallback.tsxindex c4351cb83..a56780425 100644--- a/web/src/pages/AuthCallback.tsx+++ b/web/src/pages/AuthCallback.tsx@@ -1,6 +1,6 @@import { timestampDate } from "@bufbuild/protobuf/wkt";import { useEffect, useRef, useState } from "react";-import { useSearchParams } from "react-router-dom";+import { Link, useSearchParams } from "react-router-dom";import { setAccessToken } from "@/auth-state";import { authServiceClient, userServiceClient } from "@/connect";import { useAuth } from "@/contexts/AuthContext";@@ -8,15 +8,18 @@ import useNavigateTo from "@/hooks/useNavigateTo";import { absolutifyLink } from "@/lib/browser";import { handleError } from "@/lib/error";import { ROUTES } from "@/router/routes";-import { getSafeRedirectPath } from "@/utils/auth-redirect";+import { buildAuthRoute, getSafeRedirectPath } from "@/utils/auth-redirect";+import { useTranslate } from "@/utils/i18n";import { validateOAuthState } from "@/utils/oauth";interface State {loading: boolean;errorMessage: string;+ returnUrl?: string;}const AuthCallback = () => {+ const t = useTranslate();const navigateTo = useNavigateTo();const { currentUser, initialize, isInitialized } = useAuth();const [searchParams] = useSearchParams();@@ -33,12 +36,15 @@ const AuthCallback = () => {if (handledRef.current) {return;}+ handledRef.current = true;// Check for OAuth error response first (e.g., user denied access)const error = searchParams.get("error");const errorDescription = searchParams.get("error_description");const errorUri = searchParams.get("error_uri");if (error) {+ const oauthState = searchParams.get("state");+ const validatedState = oauthState ? validateOAuthState(oauthState) : null;// OAuth provider returned an errorlet errorMessage = `OAuth error: ${error}`;if (errorDescription) {@@ -51,6 +57,7 @@ const AuthCallback = () => {setState({loading: false,errorMessage,+ returnUrl: validatedState?.returnUrl,});return;}@@ -78,8 +85,6 @@ const AuthCallback = () => {const { flowMode, identityProviderName, returnUrl, linkingUserName, codeVerifier } = validatedState;const redirectUri = absolutifyLink("/auth/callback");- handledRef.current = true;-(async () => {try {if (flowMode === "link") {@@ -133,6 +138,7 @@ const AuthCallback = () => {setState({loading: false,errorMessage: message,+ returnUrl,});},});@@ -143,8 +149,15 @@ const AuthCallback = () => {if (state.loading) return null;return (- <div className="p-4 py-24 w-full h-full flex justify-center items-center">- <div className="max-w-lg font-mono whitespace-pre-wrap opacity-80">{state.errorMessage}</div>+ <div className="p-4 py-24 w-full h-full flex flex-col justify-center items-center gap-4">+ <div className="max-w-lg font-mono whitespace-pre-wrap break-words opacity-80" role="alert">+ {state.errorMessage}+ </div>+ {state.errorMessage && (+ <Link to={buildAuthRoute({ autoSignIn: false, redirect: state.returnUrl })} className="text-sm text-primary hover:underline">+ {t("auth.back-to-sign-in")}+ </Link>+ )}</div>);};diff --git a/web/src/pages/SignIn.tsx b/web/src/pages/SignIn.tsxindex 678cdf5b8..2ce659cdb 100644--- a/web/src/pages/SignIn.tsx+++ b/web/src/pages/SignIn.tsx@@ -12,9 +12,9 @@ import { useTranslate } from "@/utils/i18n";const SignIn = () => {const t = useTranslate();- const { generalSetting: instanceGeneralSetting } = useInstance();+ const { generalSetting: instanceGeneralSetting, profile, profileLoaded, isInitialized } = useInstance();const [searchParams] = useSearchParams();- const { identityProviderList, isLoading: identityProvidersLoading } = useIdentityProviderList();+ const { identityProviderList, isLoading: identityProvidersLoading, isSuccess: identityProvidersLoaded } = useIdentityProviderList();const redirectTarget = getSafeRedirectPath(searchParams.get(AUTH_REDIRECT_PARAM));const signUpPath = appendSearchParams(ROUTES.AUTH_SIGNUP, searchParams);@@ -30,7 +30,13 @@ const SignIn = () => {<AuthOptionsLoading />) : showAuthOptions ? (<>- {hasIdentityProviders && <IdentityProviderButtons identityProviderList={identityProviderList} redirectTarget={redirectTarget} />}+ {hasIdentityProviders && (+ <IdentityProviderButtons+ identityProviderList={identityProviderList}+ redirectTarget={redirectTarget}+ autoSignIn={isInitialized && profileLoaded && !profile.needsSetup && !passwordAuthAllowed && identityProvidersLoaded}+ />+ )}{hasIdentityProviders && passwordAuthAllowed && (<div className="my-4 flex items-center gap-3 text-xs uppercase tracking-wider text-muted-foreground"><div className="flex-1">diff --git a/web/src/pages/SignUp.tsx b/web/src/pages/SignUp.tsxindex 8c97cb05e..9e801beda 100644--- a/web/src/pages/SignUp.tsx+++ b/web/src/pages/SignUp.tsx@@ -31,7 +31,7 @@ const SignUp = () => {const [challengeToken, setChallengeToken] = useState<string | null>(null);const [challengeResetKey, setChallengeResetKey] = useState(0);const { initialize: initAuth } = useAuth();- const { generalSetting: instanceGeneralSetting, profile, initialize: initInstance } = useInstance();+ const { generalSetting: instanceGeneralSetting, profile, profileLoaded, isInitialized, initialize: initInstance } = useInstance();const [searchParams] = useSearchParams();const redirectTarget = getSafeRedirectPath(searchParams.get(AUTH_REDIRECT_PARAM));const signInPath = appendSearchParams(ROUTES.AUTH, searchParams);@@ -40,9 +40,11 @@ const SignUp = () => {const registrationOpen = !instanceGeneralSetting.disallowUserRegistration;const needsSetup = profile.needsSetup;// Provider buttons only render on the SSO-provisioned branch below; skip the request elsewhere.- const { identityProviderList, isLoading: identityProvidersLoading } = useIdentityProviderList(- !needsSetup && registrationOpen && !passwordAuthAllowed,- );+ const {+ identityProviderList,+ isLoading: identityProvidersLoading,+ isSuccess: identityProvidersLoaded,+ } = useIdentityProviderList(!needsSetup && registrationOpen && !passwordAuthAllowed);const hasIdentityProviders = identityProviderList.length > 0;const handleFormSubmit = async (e: React.FormEvent<HTMLFormElement>) => {@@ -163,7 +165,11 @@ const SignUp = () => {{identityProvidersLoading ? (<AuthOptionsLoading />) : showSsoOptions ? (- <IdentityProviderButtons identityProviderList={identityProviderList} redirectTarget={redirectTarget} />+ <IdentityProviderButtons+ identityProviderList={identityProviderList}+ redirectTarget={redirectTarget}+ autoSignIn={isInitialized && profileLoaded && identityProvidersLoaded}+ />) : (<AuthEmptyStateicon={<LockIcon className="h-5 w-5" />}diff --git a/web/src/utils/auth-redirect.ts b/web/src/utils/auth-redirect.tsindex 4c70e37a8..c6dbd96e6 100644--- a/web/src/utils/auth-redirect.ts+++ b/web/src/utils/auth-redirect.ts@@ -6,6 +6,7 @@ import { buildAuthRoute, isPublicRoute } from "./redirect-safety";// keep working without every caller switching to the new module. The side-effectful// `redirectOnAuthFailure` lives here; pure logic lives in `./redirect-safety`.export {+ AUTH_AUTO_SIGN_IN_PARAM,AUTH_REASON_PARAM,AUTH_REASON_PROTECTED_MEMO,AUTH_REDIRECT_PARAM,diff --git a/web/src/utils/redirect-safety.ts b/web/src/utils/redirect-safety.tsindex 9acc27e72..66ad11f68 100644--- a/web/src/utils/redirect-safety.ts+++ b/web/src/utils/redirect-safety.ts@@ -3,6 +3,9 @@ import { ROUTES } from "@/router/routes";/** Query parameter used to preserve the intended destination across the auth flow. */export const AUTH_REDIRECT_PARAM = "redirect";+/** Set to false to show manual SSO controls instead of automatically redirecting. */+export const AUTH_AUTO_SIGN_IN_PARAM = "auto_sign_in";+/** Query parameter used to surface why the user was sent to the auth page. */export const AUTH_REASON_PARAM = "reason";@@ -39,7 +42,7 @@ export function getSafeRedirectPath(path: string | null | undefined): string | u* Builds a URL pointing at the auth entry page, optionally embedding a validated* `redirect` target and a machine-readable `reason` code.*/-export function buildAuthRoute(options?: { redirect?: string | null; reason?: string | null }): string {+export function buildAuthRoute(options?: { redirect?: string | null; reason?: string | null; autoSignIn?: boolean }): string {const searchParams = new URLSearchParams();const redirectPath = getSafeRedirectPath(options?.redirect);@@ -51,6 +54,10 @@ export function buildAuthRoute(options?: { redirect?: string | null; reason?: stsearchParams.set(AUTH_REASON_PARAM, options.reason);}+ if (options?.autoSignIn === false) {+ searchParams.set(AUTH_AUTO_SIGN_IN_PARAM, "false");+ }+const search = searchParams.toString();return search ? `${ROUTES.AUTH}?${search}` : ROUTES.AUTH;}diff --git a/web/src/utils/sso.ts b/web/src/utils/sso.tsnew file mode 100644index 000000000..39a1c44d6--- /dev/null+++ b/web/src/utils/sso.ts@@ -0,0 +1,40 @@+import { absolutifyLink } from "@/lib/browser";+import { ROUTES } from "@/router/routes";+import { IdentityProvider, IdentityProvider_Type } from "@/types/proto/api/idp_service_pb";+import { getSafeRedirectPath } from "@/utils/auth-redirect";+import { storeOAuthState } from "@/utils/oauth";++export function getSSOConfig(identityProvider: IdentityProvider) {+ if (identityProvider.type !== IdentityProvider_Type.OAUTH2 || identityProvider.config?.config.case !== "oauth2Config") {+ return undefined;+ }+ const config = identityProvider.config.config.value;+ return config.authUrl && config.clientId ? config : undefined;+}++/** Prepares the same OAuth state and PKCE parameters for automatic and manual sign-in. */+export async function prepareSSOSignIn(identityProvider: IdentityProvider, redirectTarget?: string): Promise<string> {+ const config = getSSOConfig(identityProvider);+ if (!config) {+ throw new Error("Identity provider configuration is invalid.");+ }+ const authUrl = new URL(config.authUrl);+ if (authUrl.protocol !== "https:" && authUrl.protocol !== "http:") {+ throw new Error("Identity provider configuration is invalid.");+ }+ const { state, codeChallenge } = await storeOAuthState(identityProvider.name, "signin", getSafeRedirectPath(redirectTarget));+ authUrl.searchParams.set("client_id", config.clientId);+ authUrl.searchParams.set("redirect_uri", absolutifyLink(ROUTES.AUTH_CALLBACK));+ authUrl.searchParams.set("state", state);+ authUrl.searchParams.set("response_type", "code");+ authUrl.searchParams.set("scope", config.scopes.join(" "));+ if (codeChallenge) {+ authUrl.searchParams.set("code_challenge", codeChallenge);+ authUrl.searchParams.set("code_challenge_method", "S256");+ }+ return authUrl.toString();+}++export async function signInWithSSO(identityProvider: IdentityProvider, redirectTarget?: string): Promise<void> {+ window.location.assign(await prepareSSOSignIn(identityProvider, redirectTarget));+}diff --git a/web/tests/sso-auth-pages.test.tsx b/web/tests/sso-auth-pages.test.tsxnew file mode 100644index 000000000..62b703f5b--- /dev/null+++ b/web/tests/sso-auth-pages.test.tsx@@ -0,0 +1,174 @@+import { create } from "@bufbuild/protobuf";+import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { StrictMode } from "react";+import { createMemoryRouter, RouterProvider } from "react-router-dom";+import { beforeEach, describe, expect, it, vi } from "vitest";+import IdentityProviderButtons from "@/components/IdentityProviderButtons";+import AdminSignIn from "@/pages/AdminSignIn";+import SignIn from "@/pages/SignIn";+import SignUp from "@/pages/SignUp";+import { IdentityProvider_Type, IdentityProviderSchema } from "@/types/proto/api/idp_service_pb";+import { signInWithSSO } from "@/utils/sso";++const mocks = vi.hoisted(() => ({+ instance: {+ generalSetting: { disallowPasswordAuth: true, disallowUserRegistration: false },+ profile: { needsSetup: false },+ profileLoaded: true,+ isInitialized: true,+ },+ providers: { isLoading: false, isSuccess: true, identityProviderList: [] as unknown[] },+}));+vi.mock("@/contexts/InstanceContext", () => ({ useInstance: () => mocks.instance }));+vi.mock("@/hooks/useIdentityProviderQueries", () => ({ useIdentityProviderList: () => mocks.providers }));+vi.mock("@/contexts/AuthContext", () => ({ useAuth: () => ({ initialize: vi.fn() }) }));+vi.mock("@/connect", () => ({ authServiceClient: {}, userServiceClient: {} }));+vi.mock("@/utils/sso", async (importOriginal) => ({ ...(await importOriginal<typeof import("@/utils/sso")>()), signInWithSSO: vi.fn() }));+vi.mock("@/utils/i18n", () => ({+ useTranslate: () => (key: string, params?: { provider: string }) => (params ? `${key}: ${params.provider}` : key),+}));+vi.mock("@/components/AuthFooter", () => ({ default: () => null }));+vi.mock("@/components/PasswordSignInForm", () => ({ default: () => <div>Password form</div> }));+vi.mock("@/components/CredentialFields", () => ({ default: () => null }));+vi.mock("@/components/ChallengeWidget", () => ({ default: () => null }));+const provider = create(IdentityProviderSchema, {+ name: "identityProviders/company",+ title: "Company SSO",+ type: IdentityProvider_Type.OAUTH2,+ config: { config: { case: "oauth2Config", value: { authUrl: "https://sso.example.com/authorize", clientId: "memos" } } },+});+const renderPage = (path = "/auth", element = <SignIn />) => {+ const router = createMemoryRouter([{ path: "*", element }], { initialEntries: [path] });+ render(+ <StrictMode>+ <RouterProvider router={router} />+ </StrictMode>,+ );+ return router;+};+describe("automatic SSO auth pages", () => {+ beforeEach(() => {+ mocks.instance.generalSetting = { disallowPasswordAuth: true, disallowUserRegistration: false };+ mocks.instance.profile.needsSetup = false;+ mocks.instance.profileLoaded = true;+ mocks.instance.isInitialized = true;+ mocks.providers.isLoading = false;+ mocks.providers.isSuccess = true;+ mocks.providers.identityProviderList = [provider];+ vi.mocked(signInWithSSO).mockResolvedValue();+ });+ it.each([+ { path: "/auth", element: <SignIn /> },+ { path: "/auth/signup", element: <SignUp /> },+ ])("starts once on $path and replaces the entry with a bypass preserving the destination", async ({ path, element }) => {+ const router = renderPage(`${path}?redirect=%2Fmemos%2Fexample&reason=protected-memo`, element);+ await waitFor(() => expect(signInWithSSO).toHaveBeenCalledOnce());+ expect(signInWithSSO).toHaveBeenCalledWith(provider, "/memos/example");+ expect(router.state.historyAction).toBe("REPLACE");+ expect(new URLSearchParams(router.state.location.search).get("auto_sign_in")).toBe("false");+ expect(new URLSearchParams(router.state.location.search).get("reason")).toBe("protected-memo");+ expect(screen.getByText("auth.redirecting-to-provider: Company SSO")).toBeInTheDocument();+ });+ it.each([+ {+ scenario: "password auth enabled",+ configure: () => {+ mocks.instance.generalSetting.disallowPasswordAuth = false;+ },+ },+ {+ scenario: "multiple providers",+ configure: () => {+ mocks.providers.identityProviderList = [provider, create(IdentityProviderSchema, { ...provider, name: "identityProviders/other" })];+ },+ },+ {+ scenario: "no provider",+ configure: () => {+ mocks.providers.identityProviderList = [];+ },+ },+ {+ scenario: "providers loading",+ configure: () => {+ mocks.providers.isLoading = true;+ mocks.providers.isSuccess = false;+ },+ },+ {+ scenario: "provider refetch failed",+ configure: () => {+ mocks.providers.isSuccess = false;+ },+ },+ {+ scenario: "instance profile failed",+ configure: () => {+ mocks.instance.profileLoaded = false;+ },+ },+ {+ scenario: "instance still initializing",+ configure: () => {+ mocks.instance.isInitialized = false;+ },+ },+ {+ scenario: "setup required",+ configure: () => {+ mocks.instance.profile.needsSetup = true;+ },+ },+ {+ scenario: "invalid provider",+ configure: () => {+ mocks.providers.identityProviderList = [create(IdentityProviderSchema, { type: IdentityProvider_Type.OAUTH2 })];+ },+ },+ ])("does not automatically redirect when $scenario", async ({ configure }) => {+ configure();+ renderPage();+ await act(async () => {});+ expect(signInWithSSO).not.toHaveBeenCalled();+ });+ it("allows existing users to sign in when registration is closed", async () => {+ mocks.instance.generalSetting.disallowUserRegistration = true;+ renderPage();+ await waitFor(() => expect(signInWithSSO).toHaveBeenCalledOnce());+ });+ it("keeps closed sign-up out of automatic SSO", () => {+ mocks.instance.generalSetting.disallowUserRegistration = true;+ renderPage("/auth/signup", <SignUp />);+ expect(screen.getByText("auth.signups-closed-title")).toBeInTheDocument();+ expect(signInWithSSO).not.toHaveBeenCalled();+ });+ it("keeps administrator sign-in out of automatic SSO", () => {+ renderPage("/auth/admin", <AdminSignIn />);+ expect(screen.getByText("Password form")).toBeInTheDocument();+ expect(signInWithSSO).not.toHaveBeenCalled();+ });+ it("honors the bypass while allowing an explicit manual attempt", () => {+ renderPage("/auth?auto_sign_in=false&redirect=%2Fmemos%2Fexample");+ expect(signInWithSSO).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole("button", { name: "auth.continue-with: Company SSO" }));+ expect(signInWithSSO).toHaveBeenCalledWith(provider, "/memos/example");+ });+ it("returns to manual controls after initiation fails without automatically retrying", async () => {+ vi.mocked(signInWithSSO).mockRejectedValueOnce(new Error("Storage unavailable"));+ renderPage();+ const button = await screen.findByRole("button", { name: "auth.continue-with: Company SSO" });+ await waitFor(() => expect(button).toBeEnabled());+ expect(signInWithSSO).toHaveBeenCalledOnce();+ fireEvent.click(button);+ expect(signInWithSSO).toHaveBeenCalledTimes(2);+ });+ it("restores manual controls on bfcache Back without another attempt", async () => {+ renderPage("/auth", <IdentityProviderButtons identityProviderList={[provider]} autoSignIn />);+ await waitFor(() => expect(signInWithSSO).toHaveBeenCalledOnce());+ await act(async () => {+ window.dispatchEvent(new PageTransitionEvent("pageshow", { persisted: true }));+ });+ expect(screen.getByRole("button", { name: "auth.continue-with: Company SSO" })).toBeEnabled();+ expect(signInWithSSO).toHaveBeenCalledOnce();+ });+});diff --git a/web/tests/sso-callback.test.tsx b/web/tests/sso-callback.test.tsxnew file mode 100644index 000000000..c3dc332d3--- /dev/null+++ b/web/tests/sso-callback.test.tsx@@ -0,0 +1,85 @@+import { render, screen, waitFor } from "@testing-library/react";+import { StrictMode } from "react";+import { MemoryRouter } from "react-router-dom";+import { beforeEach, describe, expect, it, vi } from "vitest";+import AuthCallback from "@/pages/AuthCallback";+import { storeOAuthState } from "@/utils/oauth";++const mocks = vi.hoisted(() => ({ initialize: vi.fn(), signIn: vi.fn(), navigateTo: vi.fn() }));+vi.mock("@/contexts/AuthContext", () => ({ useAuth: () => ({ initialize: mocks.initialize, isInitialized: true }) }));+vi.mock("@/connect", () => ({ authServiceClient: { signIn: mocks.signIn }, userServiceClient: {} }));+vi.mock("@/auth-state", () => ({ clearAccessToken: vi.fn(), setAccessToken: vi.fn() }));+vi.mock("@/hooks/useNavigateTo", () => ({ default: () => mocks.navigateTo }));+vi.mock("@/utils/i18n", () => ({ useTranslate: () => (key: string) => key }));++const renderCallback = (search: string) =>+ render(+ <StrictMode>+ <MemoryRouter initialEntries={[`/auth/callback?${search}`]}>+ <AuthCallback />+ </MemoryRouter>+ </StrictMode>,+ );+const expectRecovery = async (redirect?: string) => {+ const link = await screen.findByRole("link", { name: "auth.back-to-sign-in" });+ const url = new URL(link.getAttribute("href")!, "http://localhost");+ expect(url.pathname).toBe("/auth");+ expect(url.searchParams.get("auto_sign_in")).toBe("false");+ expect(url.searchParams.get("redirect")).toBe(redirect ?? null);+};++describe("SSO callback recovery", () => {+ beforeEach(() => {+ sessionStorage.clear();+ });++ it("offers manual recovery after cancellation while retaining the validated destination", async () => {+ const { state } = await storeOAuthState("identityProviders/company", "signin", "/memos/example#comment");+ renderCallback(`error=access_denied&state=${state}`);+ await expectRecovery("/memos/example#comment");+ expect(screen.getByRole("alert")).toHaveTextContent("access_denied");+ expect(mocks.signIn).not.toHaveBeenCalled();+ expect(sessionStorage.getItem("oauth_state")).toBeNull();+ });++ it("does not trust the return path when cancellation state does not match", async () => {+ await storeOAuthState("identityProviders/company", "signin", "/memos/example");+ renderCallback("error=access_denied&state=wrong");+ await expectRecovery();+ expect(mocks.signIn).not.toHaveBeenCalled();+ });++ it("offers manual recovery when authorization code or state is missing", async () => {+ renderCallback("code=example");+ await expectRecovery();+ expect(mocks.signIn).not.toHaveBeenCalled();+ });++ it("retains the destination after the sign-in RPC fails without retrying", async () => {+ const { state } = await storeOAuthState("identityProviders/company", "signin", "/memos/example");+ mocks.signIn.mockRejectedValueOnce(new Error("Provider unavailable"));+ renderCallback(`code=example&state=${state}`);+ await expectRecovery("/memos/example");+ expect(mocks.signIn).toHaveBeenCalledOnce();+ expect(screen.getByRole("alert")).toHaveTextContent("Provider unavailable");+ });++ it("completes a successful callback once and returns to the requested destination", async () => {+ const { state } = await storeOAuthState("identityProviders/company", "signin", "/memos/example");+ mocks.signIn.mockResolvedValueOnce({});+ renderCallback(`code=example&state=${state}`);+ await waitFor(() => expect(mocks.navigateTo).toHaveBeenCalledWith("/memos/example"));+ expect(mocks.signIn).toHaveBeenCalledOnce();+ expect(mocks.signIn).toHaveBeenCalledWith({+ credentials: {+ case: "ssoCredentials",+ value: {+ identityProvider: "identityProviders/company",+ code: "example",+ redirectUri: `${window.location.origin}/auth/callback`,+ codeVerifier: expect.any(String),+ },+ },+ });+ });+});diff --git a/web/tests/sso.test.ts b/web/tests/sso.test.tsnew file mode 100644index 000000000..7e04a568b--- /dev/null+++ b/web/tests/sso.test.ts@@ -0,0 +1,54 @@+import { create } from "@bufbuild/protobuf";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { IdentityProvider_Type, IdentityProviderSchema } from "@/types/proto/api/idp_service_pb";+import { validateOAuthState } from "@/utils/oauth";+import { prepareSSOSignIn } from "@/utils/sso";++vi.mock("@/auth-state", () => ({ clearAccessToken: vi.fn() }));+const provider = create(IdentityProviderSchema, {+ name: "identityProviders/company",+ type: IdentityProvider_Type.OAUTH2,+ config: {+ config: {+ case: "oauth2Config",+ value: { authUrl: "https://sso.example.com/authorize?tenant=team", clientId: "client&one", scopes: ["openid", "profile"] },+ },+ },+});++describe("SSO initiation", () => {+ beforeEach(() => sessionStorage.clear());+ it("preserves URL parameters and destination with state and PKCE", async () => {+ const url = new URL(await prepareSSOSignIn(provider, "/memos/example?view=full#comment"));+ expect(url.origin).toBe("https://sso.example.com");+ expect(url.searchParams.get("tenant")).toBe("team");+ expect(url.searchParams.get("client_id")).toBe("client&one");+ expect(url.searchParams.get("redirect_uri")).toBe(`${window.location.origin}/auth/callback`);+ expect(url.searchParams.get("scope")).toBe("openid profile");+ expect(url.searchParams.get("response_type")).toBe("code");+ expect(url.searchParams.get("code_challenge_method")).toBe("S256");+ const state = validateOAuthState(url.searchParams.get("state")!);+ expect(state).toMatchObject({+ identityProviderName: provider.name,+ flowMode: "signin",+ returnUrl: "/memos/example?view=full#comment",+ codeVerifier: expect.any(String),+ });+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(state!.codeVerifier));+ const challenge = btoa(String.fromCharCode(...new Uint8Array(digest)))+ .replace(/\+/g, "-")+ .replace(/\//g, "_")+ .replace(/=+$/, "");+ expect(url.searchParams.get("code_challenge")).toBe(challenge);+ });+ it("does not preserve an external return path", async () => {+ const url = new URL(await prepareSSOSignIn(provider, "https://other.example.com"));+ expect(validateOAuthState(url.searchParams.get("state")!)?.returnUrl).toBeUndefined();+ });+ it("rejects incomplete configuration before creating OAuth state", async () => {+ await expect(prepareSSOSignIn(create(IdentityProviderSchema, { type: IdentityProvider_Type.OAUTH2 }))).rejects.toThrow(+ "Identity provider configuration is invalid.",+ );+ expect(sessionStorage.getItem("oauth_state")).toBeNull();+ });+});diff --git a/web/tests/user-menu.test.tsx b/web/tests/user-menu.test.tsxindex fb10e7473..3006f8155 100644--- a/web/tests/user-menu.test.tsx+++ b/web/tests/user-menu.test.tsx@@ -1,4 +1,4 @@-import { fireEvent, render, screen, within } from "@testing-library/react";+import { fireEvent, render, screen, waitFor, within } from "@testing-library/react";import { MemoryRouter } from "react-router-dom";import { beforeEach, describe, expect, it, vi } from "vitest";import UserMenu from "@/components/UserMenu";@@ -65,6 +65,20 @@ describe("User menu panel", () => {mocks.notifications = [];});+ it("signs out to manual sign-in so an active SSO session cannot immediately sign back in", async () => {+ const originalLocation = window.location;+ const replace = vi.fn();+ Object.defineProperty(window, "location", { configurable: true, value: { ...originalLocation, replace } });+ try {+ renderMenu();+ fireEvent.click(screen.getByRole("button", { name: "common.sign-out" }));+ await waitFor(() => expect(replace).toHaveBeenCalledWith("/auth?auto_sign_in=false"));+ expect(mocks.logout).toHaveBeenCalledOnce();+ } finally {+ Object.defineProperty(window, "location", { configurable: true, value: originalLocation });+ }+ });+it("places Inbox beside the account and Archived directly above Settings", () => {renderMenu("/archived");const accountHeader = screen.getByText("Steven").parentElement!;