⭐️⭐️⭐️ Open-source, self-hosted alternative to Linear and Plane. Project management and issue tracking where teams and AI agents work side by side to plan and ship products.
TypeScript agenticagileai-agentsbug-reportingbug-trackerganttissue-trackerjirajira-alternativekanbanlinearlinear-alternativeopen-sourceproduct-managementproject-managementroadmapself-hostedsprint-planningteam-collaborationtrello-alternative
fix(web): auth forms show the server's English message for most refusals (#637)
Pasqual Troncone88e0c059ad60
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.mdindex a58f0cf4..756268e6 100644--- a/apps/web/AGENTS.md+++ b/apps/web/AGENTS.md@@ -43,8 +43,9 @@ Next.js App Router, SSR (not SPA). Tailwind v4 + shadcn/ui. See root `AGENTS.md`invited address as `email`; here it adds nothing, while the hosted build offers a sign-inthrough providers of its own. `SignInPage` is what `/login/<name>` shows, a sign-in page under aname of its own; here every name answers 404, while the hosted build can show the sign-in- form there under a title of its own (`AuthLoginForm`'s `title`). A sign-in that comes back with a code the core does not- know shows the text the build's messages give it under `auth.errors.codes.<code>`.+ form there under a title of its own (`AuthLoginForm`'s `title`). A sign-in that comes back, or an auth form the server refuses, with+ a code the core does not know shows the text the build's messages give it under+ `auth.errors.codes.<code>`.`GodSectionExtras` renders at the end of every god section page, by its slug, for settings the hosted build adds to an existing section; `WorkspaceSectionExtras`does the same on a workspace's own settings pages (`general`, `managers`), with theworkspace, and its controls save themselves. `ScheduleDialog` is the dialog that createsdiff --git a/apps/web/messages/ar/auth.json b/apps/web/messages/ar/auth.jsonindex f3b53c8d..2a91b236 100644--- a/apps/web/messages/ar/auth.json+++ b/apps/web/messages/ar/auth.json@@ -100,6 +100,13 @@"emailDomainNotAllowed": "هذه النسخة لا تقبل إلا عناوين من نطاقات معيّنة. استخدم عنوانًا آخر أو تواصل مع المسؤول.","oauthClientUnknown": "التطبيق الذي يطلب الوصول غير مسجّل هنا. أزل هذا الخادم من التطبيق ثم أضفه من جديد ليُسجَّل مرة أخرى.","oauthRedirectUnknown": "طلب التطبيق العودة إلى عنوان لم يسجّله، لذلك أُوقف التفويض. أزل هذا الخادم من التطبيق ثم أضفه من جديد.",- "oauthClientRefused": "لا يُسمح لهذا التطبيق بالاتصال بحسابك."+ "oauthClientRefused": "لا يُسمح لهذا التطبيق بالاتصال بحسابك.",+ "invalidCredentials": "البريد الإلكتروني أو اسم المستخدم أو كلمة المرور غير صحيحة.",+ "invalidEmail": "أدخل عنوان بريد إلكتروني صالحًا.",+ "passwordTooShort": "يجب أن تتكوّن كلمة المرور من 8 أحرف على الأقل.",+ "passwordTooLong": "يجب ألا تتجاوز كلمة المرور 128 حرفًا.",+ "emailTaken": "لهذا البريد الإلكتروني حساب بالفعل. سجّل الدخول بدلًا من ذلك.",+ "tooManyRequests": "محاولات كثيرة جدًا. انتظر بضع ثوانٍ ثم حاول مرة أخرى.",+ "emailNotVerified": "أكّد عنوان بريدك الإلكتروني قبل تسجيل الدخول."}}diff --git a/apps/web/messages/ar/invite.json b/apps/web/messages/ar/invite.jsonindex 91520ac6..7dbbb4b1 100644--- a/apps/web/messages/ar/invite.json+++ b/apps/web/messages/ar/invite.json@@ -36,7 +36,6 @@"switchToRegister": "أنشئ واحدًا","existingAccountNotice": "البريد ده له حساب بالفعل. سجّل الدخول بكلمة مرورك.","passwordsDoNotMatch": "كلمتا المرور غير متطابقتين.",- "genericError": "حدث خطأ ما. حاول مرة أخرى.","registerFailed": "تعذّر إنشاء حسابك.","signInFailed": "تعذّر تسجيل دخولك."}diff --git a/apps/web/messages/en/auth.json b/apps/web/messages/en/auth.jsonindex 588b7603..cade1594 100644--- a/apps/web/messages/en/auth.json+++ b/apps/web/messages/en/auth.json@@ -100,6 +100,13 @@"emailDomainNotAllowed": "This instance only admits addresses at certain domains. Use another address or ask your administrator.","oauthClientUnknown": "The app asking for access is not registered here. Remove this server from the app and add it again, so that it registers anew.","oauthRedirectUnknown": "The app asked to come back to an address it has not registered, so the authorization was stopped. Remove this server from the app and add it again.",- "oauthClientRefused": "This app is not allowed to connect to your account."+ "oauthClientRefused": "This app is not allowed to connect to your account.",+ "invalidCredentials": "Wrong email, username or password.",+ "invalidEmail": "Enter a valid email address.",+ "passwordTooShort": "The password must be at least 8 characters long.",+ "passwordTooLong": "The password must be at most 128 characters long.",+ "emailTaken": "This email address already has an account. Sign in instead.",+ "tooManyRequests": "Too many attempts. Wait a few seconds and try again.",+ "emailNotVerified": "Confirm your email address before signing in."}}diff --git a/apps/web/messages/en/invite.json b/apps/web/messages/en/invite.jsonindex e1df3b6b..8306f995 100644--- a/apps/web/messages/en/invite.json+++ b/apps/web/messages/en/invite.json@@ -36,7 +36,6 @@"switchToRegister": "Create one","existingAccountNotice": "This email already has an account. Sign in with your password.","passwordsDoNotMatch": "Passwords do not match.",- "genericError": "Something went wrong. Please try again.","registerFailed": "Could not create your account.","signInFailed": "Could not sign you in."}diff --git a/apps/web/messages/es-ES/auth.json b/apps/web/messages/es-ES/auth.jsonindex 9301a0ff..d531080d 100644--- a/apps/web/messages/es-ES/auth.json+++ b/apps/web/messages/es-ES/auth.json@@ -100,6 +100,13 @@"emailDomainNotAllowed": "Esta instancia solo admite direcciones de ciertos dominios. Usa otra dirección o pide ayuda a tu administrador.","oauthClientUnknown": "La aplicación que pide acceso no está registrada aquí. Quita este servidor en la aplicación y vuelve a añadirlo para que se registre de nuevo.","oauthRedirectUnknown": "La aplicación pidió volver a una dirección que no tiene registrada, así que se ha detenido la autorización. Quita este servidor en la aplicación y vuelve a añadirlo.",- "oauthClientRefused": "Esta aplicación no puede conectarse a tu cuenta."+ "oauthClientRefused": "Esta aplicación no puede conectarse a tu cuenta.",+ "invalidCredentials": "El correo, el nombre de usuario o la contraseña no son correctos.",+ "invalidEmail": "Escribe una dirección de correo válida.",+ "passwordTooShort": "La contraseña debe tener al menos 8 caracteres.",+ "passwordTooLong": "La contraseña puede tener como máximo 128 caracteres.",+ "emailTaken": "Este correo ya tiene una cuenta. Inicia sesión.",+ "tooManyRequests": "Demasiados intentos. Espera unos segundos e inténtalo otra vez.",+ "emailNotVerified": "Confirma tu dirección de correo antes de iniciar sesión."}}diff --git a/apps/web/messages/es-ES/invite.json b/apps/web/messages/es-ES/invite.jsonindex b9e716b0..1ab001d5 100644--- a/apps/web/messages/es-ES/invite.json+++ b/apps/web/messages/es-ES/invite.json@@ -36,7 +36,6 @@"switchToRegister": "Crear una","existingAccountNotice": "Este correo ya tiene una cuenta. Inicia sesión con tu contraseña.","passwordsDoNotMatch": "Las contraseñas no coinciden.",- "genericError": "Algo ha salido mal. Por favor, inténtalo otra vez.","registerFailed": "No se ha podido crear tu cuenta.","signInFailed": "No se ha podido iniciar tu sesión."}diff --git a/apps/web/messages/fa/auth.json b/apps/web/messages/fa/auth.jsonindex a01b31b1..92a3d792 100644--- a/apps/web/messages/fa/auth.json+++ b/apps/web/messages/fa/auth.json@@ -100,6 +100,13 @@"emailDomainNotAllowed": "این سامانه فقط نشانیهایی با دامنههای مشخص را میپذیرد. از نشانی دیگری استفاده کنید یا از مدیر خود بپرسید.","oauthClientUnknown": "برنامهای که درخواست دسترسی دارد اینجا ثبت نشده است. این سرور را از برنامه حذف کنید و دوباره اضافه کنید تا از نو ثبت شود.","oauthRedirectUnknown": "برنامه خواست به نشانیای برگردد که ثبت نکرده است، بنابراین مجوزدهی متوقف شد. این سرور را از برنامه حذف کنید و دوباره اضافه کنید.",- "oauthClientRefused": "این برنامه اجازه ندارد به حساب شما متصل شود."+ "oauthClientRefused": "این برنامه اجازه ندارد به حساب شما متصل شود.",+ "invalidCredentials": "ایمیل، نام کاربری یا رمز عبور نادرست است.",+ "invalidEmail": "یک نشانی ایمیل معتبر وارد کنید.",+ "passwordTooShort": "رمز عبور باید دستکم ۸ نویسه باشد.",+ "passwordTooLong": "رمز عبور حداکثر میتواند ۱۲۸ نویسه باشد.",+ "emailTaken": "این نشانی ایمیل از قبل حساب دارد. بهجای آن وارد شوید.",+ "tooManyRequests": "تلاشهای زیادی انجام شد. چند ثانیه صبر کنید و دوباره تلاش کنید.",+ "emailNotVerified": "پیش از ورود، نشانی ایمیل خود را تأیید کنید."}}diff --git a/apps/web/messages/fa/invite.json b/apps/web/messages/fa/invite.jsonindex c3069c6f..d366ab09 100644--- a/apps/web/messages/fa/invite.json+++ b/apps/web/messages/fa/invite.json@@ -36,7 +36,6 @@"switchToRegister": "ایجاد کنید","existingAccountNotice": "این ایمیل قبلاً حساب دارد. با رمز عبور خود وارد شوید.","passwordsDoNotMatch": "رمزهای عبور مطابقت ندارند.",- "genericError": "مشکلی پیش آمد. لطفاً دوباره تلاش کنید.","registerFailed": "نمیتوان حساب شما را ایجاد کرد.","signInFailed": "نمیتوان شما را وارد کرد."}diff --git a/apps/web/messages/fr/auth.json b/apps/web/messages/fr/auth.jsonindex 1afa8847..309af843 100644--- a/apps/web/messages/fr/auth.json+++ b/apps/web/messages/fr/auth.json@@ -100,6 +100,13 @@"emailDomainNotAllowed": "Cette instance n'accepte que les adresses de certains domaines. Utilisez une autre adresse ou contactez votre administrateur.","oauthClientUnknown": "L’application qui demande l’accès n’est pas enregistrée ici. Retirez ce serveur de l’application puis ajoutez-le de nouveau pour qu’elle s’enregistre à nouveau.","oauthRedirectUnknown": "L’application a demandé à revenir à une adresse qu’elle n’a pas enregistrée ; l’autorisation a donc été arrêtée. Retirez ce serveur de l’application puis ajoutez-le de nouveau.",- "oauthClientRefused": "Cette application n’est pas autorisée à se connecter à votre compte."+ "oauthClientRefused": "Cette application n’est pas autorisée à se connecter à votre compte.",+ "invalidCredentials": "E-mail, nom d'utilisateur ou mot de passe incorrect.",+ "invalidEmail": "Saisissez une adresse e-mail valide.",+ "passwordTooShort": "Le mot de passe doit contenir au moins 8 caractères.",+ "passwordTooLong": "Le mot de passe doit contenir au plus 128 caractères.",+ "emailTaken": "Cette adresse e-mail a déjà un compte. Connectez-vous plutôt.",+ "tooManyRequests": "Trop de tentatives. Attendez quelques secondes et réessayez.",+ "emailNotVerified": "Confirmez votre adresse e-mail avant de vous connecter."}}diff --git a/apps/web/messages/fr/invite.json b/apps/web/messages/fr/invite.jsonindex 655f54c4..f8503fb4 100644--- a/apps/web/messages/fr/invite.json+++ b/apps/web/messages/fr/invite.json@@ -36,7 +36,6 @@"switchToRegister": "En créer un","existingAccountNotice": "Un compte existe déjà pour cette adresse. Connectez-vous avec votre mot de passe.","passwordsDoNotMatch": "Les mots de passe ne correspondent pas.",- "genericError": "Une erreur est survenue. Veuillez réessayer.","registerFailed": "Impossible de créer votre compte.","signInFailed": "Impossible de vous connecter."}diff --git a/apps/web/messages/id/auth.json b/apps/web/messages/id/auth.jsonindex 0a575252..d28a8ea8 100644--- a/apps/web/messages/id/auth.json+++ b/apps/web/messages/id/auth.json@@ -100,6 +100,13 @@"emailDomainNotAllowed": "Instance ini hanya menerima alamat dari domain tertentu. Gunakan alamat lain atau hubungi administrator Anda.","oauthClientUnknown": "Aplikasi yang meminta akses tidak terdaftar di sini. Hapus server ini dari aplikasi lalu tambahkan lagi agar aplikasi mendaftar ulang.","oauthRedirectUnknown": "Aplikasi meminta kembali ke alamat yang tidak didaftarkannya, sehingga otorisasi dihentikan. Hapus server ini dari aplikasi lalu tambahkan lagi.",- "oauthClientRefused": "Aplikasi ini tidak diizinkan terhubung ke akun Anda."+ "oauthClientRefused": "Aplikasi ini tidak diizinkan terhubung ke akun Anda.",+ "invalidCredentials": "Email, nama pengguna, atau kata sandi salah.",+ "invalidEmail": "Masukkan alamat email yang valid.",+ "passwordTooShort": "Kata sandi minimal 8 karakter.",+ "passwordTooLong": "Kata sandi maksimal 128 karakter.",+ "emailTaken": "Alamat email ini sudah memiliki akun. Silakan masuk.",+ "tooManyRequests": "Terlalu banyak percobaan. Tunggu beberapa detik lalu coba lagi.",+ "emailNotVerified": "Konfirmasi alamat email Anda sebelum masuk."}}diff --git a/apps/web/messages/id/invite.json b/apps/web/messages/id/invite.jsonindex 98cbe70b..81710b56 100644--- a/apps/web/messages/id/invite.json+++ b/apps/web/messages/id/invite.json@@ -36,7 +36,6 @@"switchToRegister": "Buat akun","existingAccountNotice": "Email ini sudah memiliki akun. Masuk dengan kata sandi Anda.","passwordsDoNotMatch": "Kata sandi tidak cocok.",- "genericError": "Terjadi kesalahan. Silakan coba lagi.","registerFailed": "Tidak dapat membuat akun Anda.","signInFailed": "Gagal masuk."}diff --git a/apps/web/messages/ko/auth.json b/apps/web/messages/ko/auth.jsonindex 2c206c77..8f91ff15 100644--- a/apps/web/messages/ko/auth.json+++ b/apps/web/messages/ko/auth.json@@ -100,6 +100,13 @@"emailDomainNotAllowed": "이 서버는 특정 도메인의 주소만 받습니다. 다른 주소를 사용하거나 관리자에게 문의하세요.","oauthClientUnknown": "접근을 요청한 앱이 여기에 등록되어 있지 않습니다. 앱에서 이 서버를 제거한 뒤 다시 추가해 새로 등록되게 하세요.","oauthRedirectUnknown": "앱이 등록하지 않은 주소로 돌아가려고 해서 인증이 중단되었습니다. 앱에서 이 서버를 제거한 뒤 다시 추가하세요.",- "oauthClientRefused": "이 앱은 계정에 연결할 수 없습니다."+ "oauthClientRefused": "이 앱은 계정에 연결할 수 없습니다.",+ "invalidCredentials": "이메일, 사용자 이름 또는 비밀번호가 올바르지 않습니다.",+ "invalidEmail": "올바른 이메일 주소를 입력하세요.",+ "passwordTooShort": "비밀번호는 8자 이상이어야 합니다.",+ "passwordTooLong": "비밀번호는 128자 이하여야 합니다.",+ "emailTaken": "이 이메일 주소에는 이미 계정이 있습니다. 대신 로그인하세요.",+ "tooManyRequests": "시도 횟수가 너무 많습니다. 잠시 후 다시 시도하세요.",+ "emailNotVerified": "로그인하기 전에 이메일 주소를 확인하세요."}}diff --git a/apps/web/messages/ko/invite.json b/apps/web/messages/ko/invite.jsonindex 3b8e1722..beee0b9c 100644--- a/apps/web/messages/ko/invite.json+++ b/apps/web/messages/ko/invite.json@@ -36,7 +36,6 @@"switchToRegister": "계정 생성","existingAccountNotice": "이 이메일로 등록된 계정이 이미 있습니다. 비밀번호로 로그인해 주세요.","passwordsDoNotMatch": "비밀번호가 일치하지 않습니다.",- "genericError": "문제가 발생했습니다. 다시 시도해 주세요.","registerFailed": "계정을 생성할 수 없습니다.","signInFailed": "로그인할 수 없습니다."}diff --git a/apps/web/messages/pt-BR/auth.json b/apps/web/messages/pt-BR/auth.jsonindex d78e3153..3faf7a8c 100644--- a/apps/web/messages/pt-BR/auth.json+++ b/apps/web/messages/pt-BR/auth.json@@ -100,6 +100,13 @@"emailDomainNotAllowed": "Esta instância só aceita endereços de determinados domínios. Use outro endereço ou fale com o seu administrador.","oauthClientUnknown": "O aplicativo que pede acesso não está registrado aqui. Remova este servidor do aplicativo e adicione-o de novo para que ele se registre novamente.","oauthRedirectUnknown": "O aplicativo pediu para voltar a um endereço que não registrou, então a autorização foi interrompida. Remova este servidor do aplicativo e adicione-o de novo.",- "oauthClientRefused": "Este aplicativo não tem permissão para se conectar à sua conta."+ "oauthClientRefused": "Este aplicativo não tem permissão para se conectar à sua conta.",+ "invalidCredentials": "E-mail, nome de usuário ou senha incorretos.",+ "invalidEmail": "Informe um endereço de e-mail válido.",+ "passwordTooShort": "A senha deve ter pelo menos 8 caracteres.",+ "passwordTooLong": "A senha deve ter no máximo 128 caracteres.",+ "emailTaken": "Este e-mail já tem uma conta. Entre com ela.",+ "tooManyRequests": "Muitas tentativas. Aguarde alguns segundos e tente novamente.",+ "emailNotVerified": "Confirme seu endereço de e-mail antes de entrar."}}diff --git a/apps/web/messages/pt-BR/invite.json b/apps/web/messages/pt-BR/invite.jsonindex b3778532..4ca2ee5b 100644--- a/apps/web/messages/pt-BR/invite.json+++ b/apps/web/messages/pt-BR/invite.json@@ -36,7 +36,6 @@"switchToRegister": "Criar uma","existingAccountNotice": "Este e-mail já tem uma conta. Entre com sua senha.","passwordsDoNotMatch": "As senhas não coincidem.",- "genericError": "Algo deu errado. Tente novamente.","registerFailed": "Não foi possível criar sua conta.","signInFailed": "Não foi possível conectar você."}diff --git a/apps/web/messages/ru/auth.json b/apps/web/messages/ru/auth.jsonindex 82d67678..237dd6d8 100644--- a/apps/web/messages/ru/auth.json+++ b/apps/web/messages/ru/auth.json@@ -100,6 +100,13 @@"emailDomainNotAllowed": "Этот инстанс принимает только адреса на определённых доменах. Используйте другой адрес или обратитесь к администратору.","oauthClientUnknown": "Приложение, запрашивающее доступ, здесь не зарегистрировано. Удалите этот сервер в приложении и добавьте его снова, чтобы оно зарегистрировалось заново.","oauthRedirectUnknown": "Приложение запросило возврат на адрес, который оно не регистрировало, поэтому авторизация остановлена. Удалите этот сервер в приложении и добавьте его снова.",- "oauthClientRefused": "Этому приложению запрещено подключаться к вашему аккаунту."+ "oauthClientRefused": "Этому приложению запрещено подключаться к вашему аккаунту.",+ "invalidCredentials": "Неверный адрес электронной почты, имя пользователя или пароль.",+ "invalidEmail": "Введите корректный адрес электронной почты.",+ "passwordTooShort": "Пароль должен содержать не менее 8 символов.",+ "passwordTooLong": "Пароль должен содержать не более 128 символов.",+ "emailTaken": "Для этого адреса уже есть учётная запись. Войдите в неё.",+ "tooManyRequests": "Слишком много попыток. Подождите несколько секунд и попробуйте ещё раз.",+ "emailNotVerified": "Подтвердите адрес электронной почты, прежде чем войти."}}diff --git a/apps/web/messages/ru/invite.json b/apps/web/messages/ru/invite.jsonindex 135b7cd0..195361bc 100644--- a/apps/web/messages/ru/invite.json+++ b/apps/web/messages/ru/invite.json@@ -36,7 +36,6 @@"switchToRegister": "Создать","existingAccountNotice": "Для этой почты уже есть аккаунт. Войдите со своим паролем.","passwordsDoNotMatch": "Пароли не совпадают.",- "genericError": "Что-то пошло не так. Попробуйте ещё раз.","registerFailed": "Не удалось создать аккаунт.","signInFailed": "Не удалось выполнить вход."}diff --git a/apps/web/messages/tr/auth.json b/apps/web/messages/tr/auth.jsonindex 0ef115a5..378ca944 100644--- a/apps/web/messages/tr/auth.json+++ b/apps/web/messages/tr/auth.json@@ -100,6 +100,13 @@"emailDomainNotAllowed": "Bu örneklem yalnızca belirli alan adlarındaki e-posta adreslerini kabul eder. Başka bir adres kullanın veya yöneticinize danışın.","oauthClientUnknown": "Erişim talep eden uygulama burada kayıtlı değil. Bu sunucuyu uygulamadan kaldırıp yeniden kaydedilmesi için tekrar ekleyin.","oauthRedirectUnknown": "Uygulama kayıtlı olmayan bir adrese yönlendirme talep ettiği için yetkilendirme durduruldu. Bu sunucuyu uygulamadan kaldırıp tekrar ekleyin.",- "oauthClientRefused": "Bu uygulamanın hesabınıza bağlanma izni yok."+ "oauthClientRefused": "Bu uygulamanın hesabınıza bağlanma izni yok.",+ "invalidCredentials": "E-posta, kullanıcı adı veya şifre hatalı.",+ "invalidEmail": "Geçerli bir e-posta adresi girin.",+ "passwordTooShort": "Şifre en az 8 karakter uzunluğunda olmalıdır.",+ "passwordTooLong": "Şifre en fazla 128 karakter uzunluğunda olabilir.",+ "emailTaken": "Bu e-posta adresinin zaten bir hesabı var. Bunun yerine giriş yapın.",+ "tooManyRequests": "Çok fazla deneme yapıldı. Birkaç saniye bekleyip tekrar deneyin.",+ "emailNotVerified": "Giriş yapmadan önce e-posta adresinizi onaylayın."}}diff --git a/apps/web/messages/tr/invite.json b/apps/web/messages/tr/invite.jsonindex fe4e1f48..eae79ec0 100644--- a/apps/web/messages/tr/invite.json+++ b/apps/web/messages/tr/invite.json@@ -36,7 +36,6 @@"switchToRegister": "Hesap oluştur","existingAccountNotice": "Bu e-posta adresine kayıtlı bir hesap zaten var. Şifrenizle giriş yapın.","passwordsDoNotMatch": "Şifreler eşleşmiyor.",- "genericError": "Bir sorun oluştu. Lütfen tekrar deneyin.","registerFailed": "Hesabınız oluşturulamadı.","signInFailed": "Giriş yapılamadı."}diff --git a/apps/web/messages/uk/auth.json b/apps/web/messages/uk/auth.jsonindex c4cdf1e2..7b5c3e93 100644--- a/apps/web/messages/uk/auth.json+++ b/apps/web/messages/uk/auth.json@@ -100,6 +100,13 @@"emailDomainNotAllowed": "Цей інстанс приймає лише адреси на певних доменах. Використайте іншу адресу або зверніться до адміністратора.","oauthClientUnknown": "Застосунок, що запитує доступ, тут не зареєстрований. Видаліть цей сервер у застосунку й додайте його знову, щоб він зареєструвався повторно.","oauthRedirectUnknown": "Застосунок попросив повернутися на адресу, яку не реєстрував, тому авторизацію зупинено. Видаліть цей сервер у застосунку й додайте його знову.",- "oauthClientRefused": "Цьому застосунку не дозволено під’єднуватися до вашого облікового запису."+ "oauthClientRefused": "Цьому застосунку не дозволено під’єднуватися до вашого облікового запису.",+ "invalidCredentials": "Неправильна адреса електронної пошти, ім'я користувача або пароль.",+ "invalidEmail": "Введіть дійсну адресу електронної пошти.",+ "passwordTooShort": "Пароль має містити щонайменше 8 символів.",+ "passwordTooLong": "Пароль має містити не більше 128 символів.",+ "emailTaken": "Для цієї адреси вже є обліковий запис. Увійдіть у нього.",+ "tooManyRequests": "Забагато спроб. Зачекайте кілька секунд і спробуйте ще раз.",+ "emailNotVerified": "Підтвердьте адресу електронної пошти, перш ніж увійти."}}diff --git a/apps/web/messages/uk/invite.json b/apps/web/messages/uk/invite.jsonindex e911e37d..42e3eb0e 100644--- a/apps/web/messages/uk/invite.json+++ b/apps/web/messages/uk/invite.json@@ -36,7 +36,6 @@"switchToRegister": "Створити","existingAccountNotice": "Для цієї пошти вже є акаунт. Увійдіть зі своїм паролем.","passwordsDoNotMatch": "Паролі не збігаються.",- "genericError": "Щось пішло не так. Спробуйте ще раз.","registerFailed": "Не вдалося створити акаунт.","signInFailed": "Не вдалося виконати вхід."}diff --git a/apps/web/messages/zh-CN/auth.json b/apps/web/messages/zh-CN/auth.jsonindex af77b1e4..3feec07d 100644--- a/apps/web/messages/zh-CN/auth.json+++ b/apps/web/messages/zh-CN/auth.json@@ -100,6 +100,13 @@"emailDomainNotAllowed": "此实例只接受特定域名的地址。请换一个地址,或联系管理员。","oauthClientUnknown": "请求访问的应用未在此处注册。请在该应用中移除此服务器并重新添加,让它重新注册。","oauthRedirectUnknown": "该应用要求返回到一个未注册的地址,因此授权已停止。请在该应用中移除此服务器并重新添加。",- "oauthClientRefused": "此应用不允许连接到你的账户。"+ "oauthClientRefused": "此应用不允许连接到你的账户。",+ "invalidCredentials": "邮箱、用户名或密码错误。",+ "invalidEmail": "请输入有效的邮箱地址。",+ "passwordTooShort": "密码至少需要 8 个字符。",+ "passwordTooLong": "密码最多 128 个字符。",+ "emailTaken": "该邮箱地址已有账户,请直接登录。",+ "tooManyRequests": "尝试次数过多,请稍等几秒后重试。",+ "emailNotVerified": "请先确认你的邮箱地址再登录。"}}diff --git a/apps/web/messages/zh-CN/invite.json b/apps/web/messages/zh-CN/invite.jsonindex 3a80381d..001e4670 100644--- a/apps/web/messages/zh-CN/invite.json+++ b/apps/web/messages/zh-CN/invite.json@@ -36,7 +36,6 @@"switchToRegister": "创建账户","existingAccountNotice": "此邮箱已有账户,请使用密码登录。","passwordsDoNotMatch": "两次输入的密码不一致。",- "genericError": "出现错误,请重试。","registerFailed": "无法创建账户。","signInFailed": "无法登录。"}diff --git a/apps/web/src/features/auth/components/reset-password/AuthResetPasswordForm.test.tsx b/apps/web/src/features/auth/components/reset-password/AuthResetPasswordForm.test.tsxnew file mode 100644index 00000000..25c8763d--- /dev/null+++ b/apps/web/src/features/auth/components/reset-password/AuthResetPasswordForm.test.tsx@@ -0,0 +1,150 @@+import assert from 'node:assert/strict';+import { createRequire } from 'node:module';+import { afterEach, beforeEach, describe, it } from 'node:test';+import { act } from 'react';+import type { Root } from 'react-dom/client';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { NextIntlClientProvider } from 'next-intl';+import { AppRouterContext } from 'next/dist/shared/lib/app-router-context.shared-runtime';+import { SearchParamsContext } from 'next/dist/shared/lib/hooks-client-context.shared-runtime';+import { JSDOM } from 'jsdom';+import { qk } from '@/services/queryKeys';+import auth from '../../../../../messages/en/auth.json';++// A reset link the server no longer accepts gets the dead-link screen and its way to a+// new link, not an error line under a form that cannot succeed.+const replacedGlobals = [+ 'window',+ 'document',+ 'navigator',+ 'Node',+ 'Element',+ 'HTMLElement',+ 'HTMLInputElement',+ 'HTMLFormElement',+ 'SVGElement',+ 'Event',+ 'MutationObserver',+ 'getComputedStyle',+ 'IS_REACT_ACT_ENVIRONMENT',+] as const;++let dom: JSDOM;+let root: Root;+let client: QueryClient;+let originals: Map<string, PropertyDescriptor | undefined>;+let restore: (() => void) | undefined;++// Loading the test helper without Bun's globals preserves the web app's fetch type.+const { spyOn } = createRequire(import.meta.url)('bun:test') as {+ spyOn: (+ target: object,+ method: string,+ ) => {+ mockImplementation: (implementation: () => Promise<unknown>) => { mockRestore: () => void };+ };+};++const router = { push() {}, replace() {}, refresh() {}, back() {}, forward() {}, prefetch() {} };++async function refuseReset(code: string, message: string) {+ const authClient = await import('@/lib/auth-client');+ // better-auth captures fetch at module import, which can precede this fixture in a combined run.+ const spy = spyOn(authClient, 'resetPassword').mockImplementation(async () => ({+ data: null,+ error: { code, message, status: 400, statusText: 'BAD_REQUEST' },+ }));+ restore = () => spy.mockRestore();+}++async function submit() {+ const { default: AuthResetPasswordForm } = await import('./AuthResetPasswordForm');+ await act(async () =>+ root.render(+ <AppRouterContext.Provider value={router as never}>+ <SearchParamsContext.Provider+ value={new URLSearchParams('token=t1&[email protected]') as never}+ >+ <QueryClientProvider client={client}>+ <NextIntlClientProvider locale="en" messages={{ auth }} timeZone="UTC">+ <AuthResetPasswordForm />+ </NextIntlClientProvider>+ </QueryClientProvider>+ </SearchParamsContext.Provider>+ </AppRouterContext.Provider>,+ ),+ );+ const fields = document.querySelectorAll<HTMLInputElement>('input[type="password"]');+ for (const field of fields) {+ await act(async () => {+ const setter = Object.getOwnPropertyDescriptor(+ dom.window.HTMLInputElement.prototype,+ 'value',+ )!.set!;+ setter.call(field, 'new-password-123');+ field.dispatchEvent(new dom.window.Event('input', { bubbles: true }));+ });+ }+ await act(async () => {+ document.querySelector('form')!.requestSubmit();+ await new Promise((resolve) => setTimeout(resolve, 20));+ });+}++beforeEach(async () => {+ originals = new Map(+ replacedGlobals.map((name) => [name, Object.getOwnPropertyDescriptor(globalThis, name)]),+ );+ dom = new JSDOM('<!doctype html><div id="root"></div>', {+ url: 'https://example.test/reset-password?token=t1',+ pretendToBeVisual: true,+ });+ for (const name of replacedGlobals) {+ if (name in dom.window) {+ Object.defineProperty(globalThis, name, {+ configurable: true,+ value: dom.window[name as keyof typeof dom.window],+ });+ }+ }+ Object.defineProperties(globalThis, {+ getComputedStyle: { configurable: true, value: dom.window.getComputedStyle.bind(dom.window) },+ IS_REACT_ACT_ENVIRONMENT: { configurable: true, value: true },+ });+ Object.defineProperty(window, '__ITSAPLAN_ENV__', {+ value: { apiUrl: 'https://example.test', privacyUrl: '', termsUrl: '' },+ });+ client = new QueryClient({ defaultOptions: { queries: { retry: false, staleTime: Infinity } } });+ client.setQueryData(qk.authConfig, { emailPassword: true });+ const { createRoot } = await import('react-dom/client');+ root = createRoot(document.querySelector('#root')!);+});++afterEach(async () => {+ restore?.();+ await act(async () => root.unmount());+ client.clear();+ dom.window.close();+ for (const [name, descriptor] of originals) {+ if (descriptor) Object.defineProperty(globalThis, name, descriptor);+ else Reflect.deleteProperty(globalThis, name);+ }+});++describe('AuthResetPasswordForm', () => {+ it('shows the dead-link screen when the link was already used or expired', async () => {+ await refuseReset('INVALID_TOKEN', 'Invalid token');+ await submit();++ assert.ok(document.body.textContent?.includes(auth.resetPassword.deadLinkDescription));+ assert.equal(document.querySelector('form'), null);+ });++ it('words any other refusal under the form', async () => {+ await refuseReset('PASSWORD_TOO_LONG', 'Password too long');+ await submit();++ assert.ok(document.querySelector('form'));+ assert.ok(document.body.textContent?.includes(auth.errors.passwordTooLong));+ });+});diff --git a/apps/web/src/features/auth/components/reset-password/AuthResetPasswordForm.tsx b/apps/web/src/features/auth/components/reset-password/AuthResetPasswordForm.tsxindex ee146a6e..db4c8b6d 100644--- a/apps/web/src/features/auth/components/reset-password/AuthResetPasswordForm.tsx+++ b/apps/web/src/features/auth/components/reset-password/AuthResetPasswordForm.tsx@@ -10,9 +10,11 @@ import { Input } from '@/components/ui/input';import { useAuthConfig } from '@/services/authConfig.service';import AuthFormHeader from '../AuthFormHeader';import AuthMessagePanel from '../AuthMessagePanel';-import { setNewPassword } from '../../services/auth.service';+import { AuthError, setNewPassword } from '../../services/auth.service';import { useAuthAction } from '../../hooks/useAuthAction';+const DEAD_LINK_CODES = new Set(['INVALID_TOKEN', 'USER_NOT_FOUND']);+// The screen the reset link opens. better-auth redirects here with ?token= when the// token is valid, and with ?error= when it expired or was already used.export default function AuthResetPasswordForm() {@@ -28,6 +30,9 @@ export default function AuthResetPasswordForm() {const [password, setPassword] = useState('');const [confirm, setConfirm] = useState('');+ // The link was used, expired or names an account that is gone: the same dead-link+ // screen as a link that arrives broken.+ const [linkDead, setLinkDead] = useState(false);const { error, pending, setError, run } = useAuthAction();function onSubmit(event: FormEvent) {@@ -38,9 +43,17 @@ export default function AuthResetPasswordForm() {}run(async () => {- const { signedIn } = await setNewPassword({ token, email, newPassword: password });- router.push(signedIn ? '/' : '/login?reset=1');- router.refresh();+ try {+ const { signedIn } = await setNewPassword({ token, email, newPassword: password });+ router.push(signedIn ? '/' : '/login?reset=1');+ router.refresh();+ } catch (err) {+ if (err instanceof AuthError && DEAD_LINK_CODES.has(err.code ?? '')) {+ setLinkDead(true);+ return;+ }+ throw err;+ }},{ redirect: false },);@@ -60,7 +73,7 @@ export default function AuthResetPasswordForm() {);}- if (!token || linkError) {+ if (!token || linkError || linkDead) {return (<AuthMessagePaneltitle={t('resetPassword.deadLinkTitle')}diff --git a/apps/web/src/features/auth/hooks/useAuthAction.ts b/apps/web/src/features/auth/hooks/useAuthAction.tsindex dc0e40af..0e5709bf 100644--- a/apps/web/src/features/auth/hooks/useAuthAction.ts+++ b/apps/web/src/features/auth/hooks/useAuthAction.ts@@ -2,8 +2,7 @@import { useState } from 'react';import { useRouter } from 'next/navigation';-import { useTranslations } from 'next-intl';-import { registrationRefusalKey } from '@/utils/registrationRefusals';+import { useRefusalMessage } from '@/hooks/useRefusalMessage';// Runs an auth action while tracking pending + error, and redirects into the// planner on success. `setError` is exposed so a form can report client-side@@ -13,13 +12,11 @@ import { registrationRefusalKey } from '@/utils/registrationRefusals';// the same screen with a "check your inbox" message instead, so they pass// `redirect: false` and keep `pending` cleared.//-// A failure carries the message the auth server sent, except a refusal of the-// registration gate, which is shown by its code in the visitor's language; `fallback`-// covers the ones that arrive without a message and where the generic wording is too-// vague.+// A failure is worded by useRefusalMessage; `fallback` is the text for a refusal it+// cannot name, shown instead of the server's English message.export function useAuthAction() {const router = useRouter();- const t = useTranslations('auth.errors');+ const refusalMessage = useRefusalMessage();const [error, setError] = useState<string | null>(null);const [pending, setPending] = useState(false);@@ -38,9 +35,7 @@ export function useAuthAction() {router.push('/');router.refresh();} catch (err) {- const message = err instanceof Error ? err.message : '';- const refusal = registrationRefusalKey((err as { code?: unknown } | null)?.code);- setError(refusal ? t(refusal) : message || options?.fallback || t('generic'));+ setError(refusalMessage(err, options?.fallback));setPending(false);}}diff --git a/apps/web/src/features/auth/hooks/useRedirectError.ts b/apps/web/src/features/auth/hooks/useRedirectError.tsindex 0a29825a..bc05acc5 100644--- a/apps/web/src/features/auth/hooks/useRedirectError.ts+++ b/apps/web/src/features/auth/hooks/useRedirectError.ts@@ -1,7 +1,7 @@'use client';import { useTranslations } from 'next-intl';-import { REGISTRATION_REFUSAL_KEYS } from '@/utils/registrationRefusals';+import { AUTH_REFUSAL_KEYS } from '@/utils/authRefusals';// Some auth failures reach the sign-in screen as a redirect rather than a rejected// promise, and carry their reason in ?error=<code> (plus ?error_description=<text>@@ -22,14 +22,12 @@ const MESSAGE_KEYS = {signup_disabled: 'signupDisabled',INVITE_EXPIRED: 'inviteExpired',OIDC_DISABLED: 'ssoDisabled',- PASSWORD_AUTH_DISABLED: 'passwordDisabled',- ACCOUNT_DEACTIVATED: 'accountDeactivated',email_not_found: 'emailNotFound',// The confirmation link failed. better-auth redirects with these uppercase codes.TOKEN_EXPIRED: 'tokenExpired',INVALID_TOKEN: 'invalidToken',USER_NOT_FOUND: 'userNotFound',- ...REGISTRATION_REFUSAL_KEYS,+ ...AUTH_REFUSAL_KEYS,// The client or its return address is unknown: a client can keep a registration the// instance has since lost, as an upgrade that drops the old ones does.invalid_client: 'oauthClientUnknown',diff --git a/apps/web/src/features/auth/services/auth.service.test.ts b/apps/web/src/features/auth/services/auth.service.test.tsindex 4e8d3d74..bf1b5812 100644--- a/apps/web/src/features/auth/services/auth.service.test.ts+++ b/apps/web/src/features/auth/services/auth.service.test.ts@@ -1,31 +1,42 @@import assert from 'node:assert/strict';import { describe, it } from 'node:test';-import { EmailNotConfirmedError, signInError } from './auth.service';+import { AuthError, EmailNotConfirmedError, authError } from './auth.service';-// The sign-in form offers to send the confirmation link again only when the address is-// what stopped the sign-in. The api answers 403 for other refusals too.-describe('signInError', () => {+describe('authError', () => {+ // The form words a refusal by these, since the server's message is English.+ it('keeps the code and the status of the refusal', () => {+ const error = authError({ code: 'INVALID_EMAIL_OR_PASSWORD', message: 'Invalid', status: 401 });+ assert.ok(error instanceof AuthError);+ assert.equal(error.code, 'INVALID_EMAIL_OR_PASSWORD');+ assert.equal(error.status, 401);+ assert.equal(error.message, 'Invalid');+ });++ // The sign-in form offers to send the confirmation link again only when the address+ // is what stopped the sign-in. The api answers 403 for other refusals too.it('reports an unconfirmed address', () => {- const error = signInError({+ const error = authError({code: 'EMAIL_NOT_VERIFIED',message: 'Confirm your email address before signing in',+ status: 403,});assert.ok(error instanceof EmailNotConfirmedError);});it('does not report a deactivated account as unconfirmed', () => {- const error = signInError({+ const error = authError({code: 'ACCOUNT_DEACTIVATED',message: 'This account is deactivated',+ status: 403,});assert.ok(!(error instanceof EmailNotConfirmedError));- assert.equal(error.message, 'This account is deactivated');});it('does not report a disabled password form as unconfirmed', () => {- const error = signInError({+ const error = authError({code: 'PASSWORD_AUTH_DISABLED',message: 'Password sign-in is disabled on this instance',+ status: 403,});assert.ok(!(error instanceof EmailNotConfirmedError));});diff --git a/apps/web/src/features/auth/services/auth.service.ts b/apps/web/src/features/auth/services/auth.service.tsindex 7e5b3d1f..9072ec77 100644--- a/apps/web/src/features/auth/services/auth.service.ts+++ b/apps/web/src/features/auth/services/auth.service.ts@@ -12,14 +12,33 @@ import {const appUrl = (path: string) =>typeof window === 'undefined' ? path : `${window.location.origin}${path}`;-// Each call throws with the API message on failure; on success the session cookie-// is set and the proxy lets the user into the planner. A failure without a-// message throws an empty one, and the caller (useAuthAction) words it.+// Each call throws an AuthError on failure; on success the session cookie is set and+// the proxy lets the user into the planner. The caller words the failure by its code+// and status, since the server's message is English.++// A refusal from the auth server, with better-auth's code and the HTTP status.+export class AuthError extends Error {+ constructor(+ message: string,+ readonly code?: string,+ readonly status?: number,+ ) {+ super(message);+ this.name = 'AuthError';+ }+}// Sign-in was refused because the address is not confirmed yet. The verification gate// in @repo/auth answers 403 with this code, as better-auth does; a deactivated account// and a disabled password form are 403s too, and must not offer the link again.-export class EmailNotConfirmedError extends Error {}+export class EmailNotConfirmedError extends AuthError {}++export function authError(error: { message?: string; code?: string; status?: number }): AuthError {+ const { message = '', code, status } = error;+ return code === 'EMAIL_NOT_VERIFIED'+ ? new EmailNotConfirmedError(message, code, status)+ : new AuthError(message, code, status);+}// The sign-in screen has one field for two identifiers: an address goes to// /sign-in/email, anything else to /sign-in/username. An address is the only thing@@ -36,14 +55,7 @@ export async function signInWithPassword(input: {const result = isEmailAddress(identifier)? await signIn.email({ email: identifier, password: input.password }): await signIn.username({ username: identifier, password: input.password });- if (result.error) throw signInError(result.error);-}--export function signInError(error: { message?: string; code?: string }): Error {- const message = error.message ?? '';- return error.code === 'EMAIL_NOT_VERIFIED'- ? new EmailNotConfirmedError(message)- : new Error(message);+ if (result.error) throw authError(result.error);}// autoSignIn (set in @repo/auth) signs the user in right after sign-up, unless the@@ -52,17 +64,14 @@ export function signInError(error: { message?: string; code?: string }): Error {// callbackURL is where the confirmation link lands when the instance sends one.//// On an invite-only instance the API rejects the sign-up unless the address has a-// pending project invite, and the thrown message says so.+// pending project invite, with a code the form words.export async function signUpWithEmail(input: { email: string; password: string }): Promise<void> {const result = await signUp.email({...input,name: input.email.split('@')[0] || input.email,callbackURL: appUrl('/login?verified=1'),});- // The code lets the form say why the gate refused the address, in the visitor's language.- if (result.error) {- throw Object.assign(new Error(result.error.message ?? ''), { code: result.error.code });- }+ if (result.error) throw authError(result.error);}// Sends the password reset link. The address is not confirmed to exist: better-auth@@ -76,7 +85,7 @@ export async function sendPasswordResetEmail(email: string): Promise<void> {email,redirectTo: appUrl(`/reset-password?email=${encodeURIComponent(email)}`),});- if (result.error) throw new Error(result.error.message ?? '');+ if (result.error) throw authError(result.error);}// Consumes the token from the reset link, sets the new password, and signs the user@@ -88,7 +97,7 @@ export async function setNewPassword(input: {newPassword: string;}): Promise<{ signedIn: boolean }> {const result = await resetPassword({ token: input.token, newPassword: input.newPassword });- if (result.error) throw new Error(result.error.message ?? '');+ if (result.error) throw authError(result.error);if (!input.email) return { signedIn: false };const attempt = await signIn.email({ email: input.email, password: input.newPassword });return { signedIn: !attempt.error };@@ -104,7 +113,7 @@ export async function sendMagicLink(email: string): Promise<void> {callbackURL: appUrl('/'),errorCallbackURL: appUrl('/login'),});- if (result.error) throw new Error(result.error.message ?? '');+ if (result.error) throw authError(result.error);}// Sends the address confirmation link again, for someone held back at sign-in.@@ -113,7 +122,7 @@ export async function resendVerificationEmail(email: string): Promise<void> {email,callbackURL: appUrl('/login?verified=1'),});- if (result.error) throw new Error(result.error.message ?? '');+ if (result.error) throw authError(result.error);}// Starts the Google round trip. Unlike every other call here this one navigates away@@ -130,7 +139,7 @@ export async function signInWithGoogle(returnTo?: string): Promise<void> {callbackURL: appUrl(returnTo ?? '/'),errorCallbackURL: appUrl(returnTo ?? '/login'),});- if (result.error) throw new Error(result.error.message ?? '');+ if (result.error) throw authError(result.error);}// Starts the round trip through the instance's own OIDC provider. Same shape as the@@ -142,10 +151,10 @@ export async function signInWithOidc(returnTo?: string): Promise<void> {callbackURL: appUrl(returnTo ?? '/'),errorCallbackURL: appUrl(returnTo ?? '/login'),});- if (result.error) throw new Error(result.error.message ?? '');+ if (result.error) throw authError(result.error);}export async function signInWithPasskey(): Promise<void> {const result = await signIn.passkey();- if (result?.error) throw new Error(result.error.message ?? '');+ if (result?.error) throw authError(result.error);}diff --git a/apps/web/src/features/invite/components/InviteAuthForm.tsx b/apps/web/src/features/invite/components/InviteAuthForm.tsxindex d0726442..0d0bcb6a 100644--- a/apps/web/src/features/invite/components/InviteAuthForm.tsx+++ b/apps/web/src/features/invite/components/InviteAuthForm.tsx@@ -14,17 +14,16 @@ import {FieldSeparator,} from '@/components/ui/field';import { Input } from '@/components/ui/input';-import { registrationRefusalKey } from '@/utils/registrationRefusals';import { useAuthConfig } from '@/services/authConfig.service';import AuthLoginAlternatives from '@/features/auth/components/login/AuthLoginAlternatives';import { useRedirectError } from '@/features/auth/hooks/useRedirectError';+import { useRefusalMessage } from '@/hooks/useRefusalMessage';import {signInWithGoogle,signInWithOidc,signInWithPasskey,} from '@/features/auth/services/auth.service';import {- InviteAuthError,isExistingAccountError,registerAndAccept,signInForInvite,@@ -49,6 +48,7 @@ export default function InviteAuthForm({}) {const t = useTranslations('invite');const tAuth = useTranslations('auth.errors');+ const refusalMessage = useRefusalMessage();const tLogin = useTranslations('auth.login');const router = useRouter();const passwordEnabled = useAuthConfig()?.emailPassword !== false;@@ -104,16 +104,13 @@ export default function InviteAuthForm({switchMode('signin');setNotice(t('existingAccountNotice'));} else {- const refusal =- err instanceof InviteAuthError ? registrationRefusalKey(err.code) : undefined;- if (refusal) setError(tAuth(refusal));- else setError(err instanceof Error ? err.message : t('genericError'));+ setError(refusalMessage(err));}setPending(false);}}- async function signInOtherwise(start: () => Promise<void>, fallback = t('genericError')) {+ async function signInOtherwise(start: () => Promise<void>, fallback?: string) {setError(null);setNotice(null);setPending(true);@@ -121,7 +118,7 @@ export default function InviteAuthForm({await start();router.refresh();} catch (err) {- setError((err instanceof Error && err.message) || fallback);+ setError(refusalMessage(err, fallback));}setPending(false);}diff --git a/apps/web/src/features/invite/services/invite.service.ts b/apps/web/src/features/invite/services/invite.service.tsindex 864c5b2b..f11da5f8 100644--- a/apps/web/src/features/invite/services/invite.service.ts+++ b/apps/web/src/features/invite/services/invite.service.ts@@ -22,6 +22,7 @@ export class InviteAuthError extends Error {constructor(message: string,readonly code?: string,+ readonly status?: number,) {super(message);this.name = 'InviteAuthError';@@ -32,7 +33,9 @@ export class InviteAuthError extends Error {export function isExistingAccountError(err: unknown): boolean {return (err instanceof InviteAuthError &&- (err.code === 'USER_ALREADY_EXISTS' || /already\s*exist/i.test(err.message))+ (err.code === 'USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL' ||+ err.code === 'USER_ALREADY_EXISTS' ||+ /already\s*exist/i.test(err.message)));}@@ -52,7 +55,11 @@ export async function registerAndAccept(input: {name: input.email.split('@')[0] || input.email,});if (result.error) {- throw new InviteAuthError(result.error.message ?? input.registerFailed, result.error.code);+ throw new InviteAuthError(+ result.error.message ?? input.registerFailed,+ result.error.code,+ result.error.status,+ );}return acceptInvite(input.token);}@@ -66,6 +73,10 @@ export async function signInForInvite(input: {}): Promise<void> {const result = await signIn.email({ email: input.email, password: input.password });if (result.error) {- throw new InviteAuthError(result.error.message ?? input.signInFailed, result.error.code);+ throw new InviteAuthError(+ result.error.message ?? input.signInFailed,+ result.error.code,+ result.error.status,+ );}}diff --git a/apps/web/src/hooks/useRefusalMessage.test.tsx b/apps/web/src/hooks/useRefusalMessage.test.tsxnew file mode 100644index 00000000..7a038249--- /dev/null+++ b/apps/web/src/hooks/useRefusalMessage.test.tsx@@ -0,0 +1,109 @@+import assert from 'node:assert/strict';+import { afterEach, beforeEach, describe, it } from 'node:test';+import { act } from 'react';+import type { Root } from 'react-dom/client';+import { NextIntlClientProvider } from 'next-intl';+import { JSDOM } from 'jsdom';+import auth from '../../messages/en/auth.json';+import es from '../../messages/es-ES/auth.json';+import { useRefusalMessage } from './useRefusalMessage';++// The server's messages are English; a form shows the visitor's language instead.+const replacedGlobals = [+ 'window',+ 'document',+ 'navigator',+ 'HTMLElement',+ 'IS_REACT_ACT_ENVIRONMENT',+] as const;+let dom: JSDOM;+let root: Root;+let originalGlobalDescriptors: Map<string, PropertyDescriptor | undefined>;++// The shape of the errors the auth service throws (a feature module this layer does not import).+function refusal(message: string, code?: string, status?: number) {+ return Object.assign(new Error(message), { code, status });+}++function Message({ err, fallback }: { err: unknown; fallback?: string }) {+ return <p>{useRefusalMessage()(err, fallback)}</p>;+}++function render(+ err: unknown,+ {+ fallback,+ locale = 'en',+ messages = { auth },+ }: { fallback?: string; locale?: string; messages?: object } = {},+): string {+ act(() =>+ root.render(+ <NextIntlClientProvider locale={locale} messages={messages} timeZone="UTC">+ <Message err={err} fallback={fallback} />+ </NextIntlClientProvider>,+ ),+ );+ return document.querySelector('p')?.textContent ?? '';+}++beforeEach(async () => {+ originalGlobalDescriptors = new Map(+ replacedGlobals.map((name) => [name, Object.getOwnPropertyDescriptor(globalThis, name)]),+ );+ dom = new JSDOM('<!doctype html><div id="root"></div>', { url: 'https://example.test/login' });+ Object.defineProperties(globalThis, {+ window: { configurable: true, value: dom.window },+ document: { configurable: true, value: dom.window.document },+ navigator: { configurable: true, value: dom.window.navigator },+ HTMLElement: { configurable: true, value: dom.window.HTMLElement },+ IS_REACT_ACT_ENVIRONMENT: { configurable: true, value: true },+ });+ const { createRoot } = await import('react-dom/client');+ const element = document.querySelector('#root');+ assert.ok(element);+ root = createRoot(element);+});++afterEach(() => {+ act(() => root.unmount());+ dom.window.close();+ for (const [name, descriptor] of originalGlobalDescriptors) {+ if (descriptor) Object.defineProperty(globalThis, name, descriptor);+ else Reflect.deleteProperty(globalThis, name);+ }+});++describe('useRefusalMessage', () => {+ it('words a refusal by its code, in the visitor language', () => {+ const err = refusal('Invalid email or password', 'INVALID_EMAIL_OR_PASSWORD', 401);+ assert.equal(render(err), auth.errors.invalidCredentials);+ assert.equal(+ render(err, { locale: 'es-ES', messages: { auth: es } }),+ es.errors.invalidCredentials,+ );+ });++ it('words a rate-limited request by its status', () => {+ const err = refusal('Too many requests. Please try again later.', undefined, 429);+ assert.equal(render(err), auth.errors.tooManyRequests);+ });++ it('takes the text a build names for a code of its own', () => {+ const messages = {+ auth: { ...auth, errors: { ...auth.errors, codes: { SEAT_LIMIT: 'No seats left.' } } },+ };+ assert.equal(render(refusal('Seat limit', 'SEAT_LIMIT', 403), { messages }), 'No seats left.');+ });++ // The passkey client always sends "Auth cancelled", in English.+ it('prefers the caller fallback to the server message for an unnamed code', () => {+ const err = refusal('Auth cancelled', 'AUTH_CANCELLED', 400);+ assert.equal(render(err, { fallback: auth.errors.passkey }), auth.errors.passkey);+ });++ it('shows the server message for an unnamed code, and the generic text without one', () => {+ assert.equal(render(refusal('Something odd', 'ODD', 400)), 'Something odd');+ assert.equal(render(refusal('', 'ODD', 400)), auth.errors.generic);+ });+});diff --git a/apps/web/src/hooks/useRefusalMessage.ts b/apps/web/src/hooks/useRefusalMessage.tsnew file mode 100644index 00000000..bd7ef2a4--- /dev/null+++ b/apps/web/src/hooks/useRefusalMessage.ts@@ -0,0 +1,23 @@+'use client';++import { useTranslations } from 'next-intl';+import { authRefusalKey } from '@/utils/authRefusals';++// Words a refusal from the auth server for a form, in the visitor's language: by its+// code or status first, then by a text a build names under auth.errors.codes. The+// caller's `fallback` comes before the server's message because the passkey client+// always sends one, "Auth cancelled", in English; without either, the generic text.+export function useRefusalMessage() {+ const t = useTranslations('auth.errors');++ return function refusalMessage(err: unknown, fallback?: string): string {+ const { code, status } = (err ?? {}) as { code?: unknown; status?: number };+ const key = authRefusalKey(code, status);+ if (key) return t(key);+ if (typeof code === 'string') {+ const own = `codes.${code}` as Parameters<typeof t.has>[0];+ if (t.has(own)) return t(own);+ }+ return fallback || (err instanceof Error && err.message) || t('generic');+ };+}diff --git a/apps/web/src/utils/authRefusals.test.ts b/apps/web/src/utils/authRefusals.test.tsnew file mode 100644index 00000000..ee7726a3--- /dev/null+++ b/apps/web/src/utils/authRefusals.test.ts@@ -0,0 +1,39 @@+import assert from 'node:assert/strict';+import { describe, it } from 'node:test';+import { authRefusalKey } from './authRefusals';++describe('authRefusalKey', () => {+ it('names each refusal of the registration gate', () => {+ assert.equal(authRefusalKey('REGISTRATION_CLOSED'), 'registrationClosed');+ assert.equal(authRefusalKey('INVITE_ONLY'), 'inviteOnly');+ assert.equal(authRefusalKey('EMAIL_DOMAIN_NOT_ALLOWED'), 'emailDomainNotAllowed');+ });++ it('names the refusals of the sign-in, sign-up and reset forms', () => {+ assert.equal(authRefusalKey('INVALID_EMAIL_OR_PASSWORD'), 'invalidCredentials');+ assert.equal(authRefusalKey('INVALID_USERNAME_OR_PASSWORD'), 'invalidCredentials');+ assert.equal(authRefusalKey('USERNAME_TOO_SHORT'), 'invalidCredentials');+ assert.equal(authRefusalKey('USERNAME_TOO_LONG'), 'invalidCredentials');+ assert.equal(authRefusalKey('INVALID_USERNAME'), 'invalidCredentials');+ assert.equal(authRefusalKey('INVALID_EMAIL'), 'invalidEmail');+ assert.equal(authRefusalKey('VALIDATION_ERROR'), 'invalidEmail');+ assert.equal(authRefusalKey('PASSWORD_TOO_SHORT'), 'passwordTooShort');+ assert.equal(authRefusalKey('PASSWORD_TOO_LONG'), 'passwordTooLong');+ assert.equal(authRefusalKey('USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL'), 'emailTaken');+ assert.equal(authRefusalKey('USER_ALREADY_EXISTS'), 'emailTaken');+ assert.equal(authRefusalKey('ACCOUNT_DEACTIVATED'), 'accountDeactivated');+ assert.equal(authRefusalKey('PASSWORD_AUTH_DISABLED'), 'passwordDisabled');+ assert.equal(authRefusalKey('EMAIL_NOT_VERIFIED'), 'emailNotVerified');+ });++ it('names a rate-limited request by its status, which carries no code', () => {+ assert.equal(authRefusalKey(undefined, 429), 'tooManyRequests');+ });++ it('leaves any other code to the caller', () => {+ assert.equal(authRefusalKey('INVALID_TOKEN'), undefined);+ assert.equal(authRefusalKey('AUTH_CANCELLED', 400), undefined);+ assert.equal(authRefusalKey('toString'), undefined);+ assert.equal(authRefusalKey(undefined), undefined);+ });+});diff --git a/apps/web/src/utils/authRefusals.ts b/apps/web/src/utils/authRefusals.tsnew file mode 100644index 00000000..19f512ea--- /dev/null+++ b/apps/web/src/utils/authRefusals.ts@@ -0,0 +1,39 @@+// What the auth server refuses a sign-in, sign-up or reset with, by code: a form's+// error and a round trip's ?error= alike. Its messages are English whatever the+// visitor's language, so they are shown by code instead. The values are keys under+// auth.errors in the catalogs. INVALID_TOKEN and USER_NOT_FOUND are left out: the+// confirmation link and the reset form mean different things by them.+export const AUTH_REFUSAL_KEYS = {+ REGISTRATION_CLOSED: 'registrationClosed',+ INVITE_ONLY: 'inviteOnly',+ EMAIL_DOMAIN_NOT_ALLOWED: 'emailDomainNotAllowed',+ ACCOUNT_DEACTIVATED: 'accountDeactivated',+ PASSWORD_AUTH_DISABLED: 'passwordDisabled',+ EMAIL_NOT_VERIFIED: 'emailNotVerified',+ // The sign-in form has one field for an address or a username; whatever is wrong+ // with it, the visitor's next step is the same.+ INVALID_EMAIL_OR_PASSWORD: 'invalidCredentials',+ INVALID_USERNAME_OR_PASSWORD: 'invalidCredentials',+ USERNAME_TOO_SHORT: 'invalidCredentials',+ USERNAME_TOO_LONG: 'invalidCredentials',+ INVALID_USERNAME: 'invalidCredentials',+ // The address is the only field these forms can send that fails the api's schema: the+ // password fields are required, and their length has codes of its own.+ INVALID_EMAIL: 'invalidEmail',+ VALIDATION_ERROR: 'invalidEmail',+ PASSWORD_TOO_SHORT: 'passwordTooShort',+ PASSWORD_TOO_LONG: 'passwordTooLong',+ USER_ALREADY_EXISTS: 'emailTaken',+ USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL: 'emailTaken',+} as const;++// The rate limiter answers 429 with a message and no code.+export function authRefusalKey(+ code: unknown,+ status?: number,+): (typeof AUTH_REFUSAL_KEYS)[keyof typeof AUTH_REFUSAL_KEYS] | 'tooManyRequests' | undefined {+ if (status === 429) return 'tooManyRequests';+ return typeof code === 'string' && Object.hasOwn(AUTH_REFUSAL_KEYS, code)+ ? AUTH_REFUSAL_KEYS[code as keyof typeof AUTH_REFUSAL_KEYS]+ : undefined;+}diff --git a/apps/web/src/utils/registrationRefusals.test.ts b/apps/web/src/utils/registrationRefusals.test.tsdeleted file mode 100644index 54f92d18..00000000--- a/apps/web/src/utils/registrationRefusals.test.ts+++ /dev/null@@ -1,17 +0,0 @@-import assert from 'node:assert/strict';-import { describe, it } from 'node:test';-import { registrationRefusalKey } from './registrationRefusals';--describe('registrationRefusalKey', () => {- it('names each refusal of the registration gate', () => {- assert.equal(registrationRefusalKey('REGISTRATION_CLOSED'), 'registrationClosed');- assert.equal(registrationRefusalKey('INVITE_ONLY'), 'inviteOnly');- assert.equal(registrationRefusalKey('EMAIL_DOMAIN_NOT_ALLOWED'), 'emailDomainNotAllowed');- });-- it('leaves any other code to the caller', () => {- assert.equal(registrationRefusalKey('USER_ALREADY_EXISTS'), undefined);- assert.equal(registrationRefusalKey('toString'), undefined);- assert.equal(registrationRefusalKey(undefined), undefined);- });-});diff --git a/apps/web/src/utils/registrationRefusals.ts b/apps/web/src/utils/registrationRefusals.tsdeleted file mode 100644index a4f619dd..00000000--- a/apps/web/src/utils/registrationRefusals.ts+++ /dev/null@@ -1,16 +0,0 @@-// The registration gate's refusals, by the codes the api sends with them on every-// sign-up path: a form's error and a round trip's ?error= alike. The values are keys-// under auth.errors in the catalogs.-export const REGISTRATION_REFUSAL_KEYS = {- REGISTRATION_CLOSED: 'registrationClosed',- INVITE_ONLY: 'inviteOnly',- EMAIL_DOMAIN_NOT_ALLOWED: 'emailDomainNotAllowed',-} as const;--export function registrationRefusalKey(- code: unknown,-): (typeof REGISTRATION_REFUSAL_KEYS)[keyof typeof REGISTRATION_REFUSAL_KEYS] | undefined {- return typeof code === 'string' && Object.hasOwn(REGISTRATION_REFUSAL_KEYS, code)- ? REGISTRATION_REFUSAL_KEYS[code as keyof typeof REGISTRATION_REFUSAL_KEYS]- : undefined;-}