mirror of
https://github.com/usememos/memos.git
synced 2026-11-19 10:29:11 +01:00
feat(auth): automatically start SSO when it is the only option (#6450)
This commit is contained in:
@@ -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>
|
||||
))}
|
||||
|
||||
@@ -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 (
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -24,6 +24,7 @@
|
||||
"auth": {
|
||||
"create-your-account": "أنشئ حسابك",
|
||||
"new-password": "كلمة المرور الجديدة",
|
||||
"redirecting-to-provider": "جارٍ إعادة التوجيه إلى {{provider}}…",
|
||||
"repeat-new-password": "أعد كلمة المرور الجديدة",
|
||||
"sign-in-tip": "هل لديك حساب بالفعل؟",
|
||||
"sign-up-tip": "ليس لديك حساب بعد؟",
|
||||
|
||||
@@ -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.",
|
||||
|
||||
@@ -24,6 +24,7 @@
|
||||
"auth": {
|
||||
"create-your-account": "Създайте своя акаунт",
|
||||
"new-password": "Нова парола",
|
||||
"redirecting-to-provider": "Пренасочване към {{provider}}…",
|
||||
"repeat-new-password": "Повторете новата парола",
|
||||
"sign-in-tip": "Вече имате акаунт?",
|
||||
"sign-up-tip": "Все още нямате акаунт?",
|
||||
|
||||
@@ -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?",
|
||||
|
||||
@@ -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?",
|
||||
|
||||
@@ -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?",
|
||||
|
||||
@@ -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?",
|
||||
|
||||
@@ -24,6 +24,7 @@
|
||||
"auth": {
|
||||
"create-your-account": "Δημιουργήστε τον λογαριασμό σας",
|
||||
"new-password": "Νέος κωδικός πρόσβασης",
|
||||
"redirecting-to-provider": "Ανακατεύθυνση στο {{provider}}…",
|
||||
"repeat-new-password": "Επαναλάβετε τον νέο κωδικό πρόσβασης",
|
||||
"sign-in-tip": "Έχετε ήδη λογαριασμό;",
|
||||
"sign-up-tip": "Δεν έχετε λογαριασμό ακόμα;",
|
||||
|
||||
@@ -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?",
|
||||
|
||||
@@ -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.",
|
||||
|
||||
@@ -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?",
|
||||
|
||||
@@ -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?",
|
||||
|
||||
@@ -24,6 +24,7 @@
|
||||
"auth": {
|
||||
"create-your-account": "حساب کاربری خود را ایجاد کنید.",
|
||||
"new-password": "گذرواژه جدید",
|
||||
"redirecting-to-provider": "در حال هدایت به {{provider}}…",
|
||||
"repeat-new-password": "گذرواژه جدید را تکرار کنید",
|
||||
"sign-in-tip": "آیا حساب کاربری تعریف شده دارید؟",
|
||||
"sign-up-tip": "آیا حساب کاربری تعریف شده ندارید؟",
|
||||
|
||||
@@ -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ä?",
|
||||
|
||||
@@ -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 ?",
|
||||
|
||||
@@ -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?",
|
||||
|
||||
@@ -31,6 +31,7 @@
|
||||
"explore-public-memos": "עיינו בפתקים הציבוריים במופע הזה",
|
||||
"first-run": "הפעלה ראשונה",
|
||||
"new-password": "סיסמה חדשה",
|
||||
"redirecting-to-provider": "מעבר אל {{provider}}…",
|
||||
"repeat-new-password": "הקלידו שוב את הסיסמה החדשה",
|
||||
"setup-description": "צרו את חשבון המנהל עבור המופע הזה.",
|
||||
"setup-note": "חשבון זה מנהל את הגדרות המופע, החברים וספקי הזהות.",
|
||||
|
||||
@@ -24,6 +24,7 @@
|
||||
"auth": {
|
||||
"create-your-account": "अपना खाता बनाएं",
|
||||
"new-password": "नया पासवर्ड",
|
||||
"redirecting-to-provider": "{{provider}} पर भेजा जा रहा है…",
|
||||
"repeat-new-password": "नया पासवर्ड दोहराएं",
|
||||
"sign-in-tip": "क्या आपके पास पहले से खाता है?",
|
||||
"sign-up-tip": "अभी तक खाता नहीं है?",
|
||||
|
||||
@@ -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?",
|
||||
|
||||
@@ -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?",
|
||||
|
||||
@@ -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?",
|
||||
|
||||
@@ -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?",
|
||||
|
||||
@@ -31,6 +31,7 @@
|
||||
"explore-public-memos": "このインスタンスの公開メモを見る",
|
||||
"first-run": "初回起動",
|
||||
"new-password": "新しいパスワード",
|
||||
"redirecting-to-provider": "{{provider}} にリダイレクトしています…",
|
||||
"repeat-new-password": "新しいパスワードを再入力",
|
||||
"setup-description": "このインスタンスの管理者アカウントを作成します。",
|
||||
"setup-note": "このアカウントはインスタンスの設定、メンバー、IDプロバイダーを管理します。",
|
||||
|
||||
@@ -24,6 +24,7 @@
|
||||
"auth": {
|
||||
"create-your-account": "შექმენით თქვენი ანგარიში",
|
||||
"new-password": "ახალი პაროლი",
|
||||
"redirecting-to-provider": "გადამისამართება {{provider}}-ზე…",
|
||||
"repeat-new-password": "გაიმეორეთ ახალი პაროლი",
|
||||
"sign-in-tip": "დაქვემდებარებული გაქვთ ანგარიში?",
|
||||
"sign-up-tip": "ჯერ არ გაქვთ ანგარიში?",
|
||||
|
||||
@@ -24,6 +24,7 @@
|
||||
"auth": {
|
||||
"create-your-account": "계정 만들기",
|
||||
"new-password": "새 비밀번호",
|
||||
"redirecting-to-provider": "{{provider}}(으)로 이동 중…",
|
||||
"repeat-new-password": "새 비밀번호 재확인",
|
||||
"sign-in-tip": "이미 계정이 있으신가요?",
|
||||
"sign-up-tip": "아직 계정이 없으신가요?",
|
||||
|
||||
@@ -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?",
|
||||
|
||||
@@ -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?",
|
||||
|
||||
@@ -24,6 +24,7 @@
|
||||
"auth": {
|
||||
"create-your-account": "तुमचे खाते तयार करा",
|
||||
"new-password": "नवीन पासवर्ड",
|
||||
"redirecting-to-provider": "{{provider}} कडे पुनर्निर्देशित करत आहे…",
|
||||
"repeat-new-password": "नवीन पासवर्डची पुनरावृत्ती करा",
|
||||
"sign-in-tip": "आधीपासूनच एक खाते आहे?",
|
||||
"sign-up-tip": "अजून खाते नाही?",
|
||||
|
||||
@@ -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?",
|
||||
|
||||
@@ -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?",
|
||||
|
||||
@@ -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.",
|
||||
|
||||
@@ -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?",
|
||||
|
||||
@@ -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?",
|
||||
|
||||
@@ -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?",
|
||||
|
||||
@@ -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?",
|
||||
|
||||
@@ -24,6 +24,7 @@
|
||||
"auth": {
|
||||
"create-your-account": "Создание учетной записи",
|
||||
"new-password": "Новый пароль",
|
||||
"redirecting-to-provider": "Перенаправление в {{provider}}…",
|
||||
"repeat-new-password": "Повторить новый пароль",
|
||||
"sign-in-tip": "У вас уже есть учетная запись?",
|
||||
"sign-up-tip": "У вас еще нет учетной записи?",
|
||||
|
||||
@@ -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?",
|
||||
|
||||
@@ -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?",
|
||||
|
||||
@@ -24,6 +24,7 @@
|
||||
"auth": {
|
||||
"create-your-account": "Креирајте свој налог",
|
||||
"new-password": "Нова лозинка",
|
||||
"redirecting-to-provider": "Преусмеравање на {{provider}}…",
|
||||
"repeat-new-password": "Поновите нову лозинку",
|
||||
"sign-in-tip": "Већ имате налог?",
|
||||
"sign-up-tip": "Још увек немате налог?",
|
||||
|
||||
@@ -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?",
|
||||
|
||||
@@ -24,6 +24,7 @@
|
||||
"auth": {
|
||||
"create-your-account": "สร้างบัญชีใหม่",
|
||||
"new-password": "รหัสผ่านใหม่",
|
||||
"redirecting-to-provider": "กำลังเปลี่ยนเส้นทางไปยัง {{provider}}…",
|
||||
"repeat-new-password": "รหัสผ่านใหม่อีกครั้ง",
|
||||
"sign-in-tip": "มีบัญชีอยู่แล้ว?",
|
||||
"sign-up-tip": "ยังไม่มีบัญชี?",
|
||||
|
||||
@@ -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.",
|
||||
|
||||
@@ -24,6 +24,7 @@
|
||||
"auth": {
|
||||
"create-your-account": "Створіть обліковий запис",
|
||||
"new-password": "Новий пароль",
|
||||
"redirecting-to-provider": "Перенаправлення до {{provider}}…",
|
||||
"repeat-new-password": "Повторіть новий пароль",
|
||||
"sign-in-tip": "Вже маєте обліковий запис?",
|
||||
"sign-up-tip": "Ще не маєте облікового запису?",
|
||||
|
||||
@@ -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?",
|
||||
|
||||
@@ -49,6 +49,7 @@
|
||||
"explore-public-memos": "浏览此实例上的公开 Memo",
|
||||
"first-run": "首次运行",
|
||||
"new-password": "新密码",
|
||||
"redirecting-to-provider": "正在跳转至 {{provider}}…",
|
||||
"repeat-new-password": "重复新密码",
|
||||
"setup-description": "为此实例创建管理员账号。",
|
||||
"setup-note": "该账号拥有实例设置、成员与身份提供商的管理权限。",
|
||||
|
||||
@@ -31,6 +31,7 @@
|
||||
"explore-public-memos": "瀏覽此實例的公開備忘錄",
|
||||
"first-run": "初次啟動",
|
||||
"new-password": "新密碼",
|
||||
"redirecting-to-provider": "正在跳轉至 {{provider}}…",
|
||||
"repeat-new-password": "再次輸入新密碼",
|
||||
"setup-description": "為此實例建立管理員帳號。",
|
||||
"setup-note": "此帳號擁有實例設定、成員與身分識別提供者的管理權限。",
|
||||
|
||||
@@ -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 error
|
||||
let 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>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -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">
|
||||
|
||||
@@ -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}
|
||||
/>
|
||||
) : (
|
||||
<AuthEmptyState
|
||||
icon={<LockIcon className="h-5 w-5" />}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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?: st
|
||||
searchParams.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;
|
||||
}
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -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),
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -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!;
|
||||
|
||||
Reference in New Issue
Block a user