From b2afa92f5ce652ae682791be1de4052d77f1e5eb Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 12:21:05 +0000 Subject: [PATCH 1/6] fix(auth): localize a cloud-managed runtime's password-door refusal toAuthError reads code, message, details and userMessage from the ADR-0112 envelope when better-auth's flat body has none, and forgotPassword, resetPassword and setInitialPassword now go through it. The sign-in refusal map and a new password-door map turn 409 RESOURCE_CONFLICT into a localized sentence that points at the identity provider's button. Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01Q4EjjQkY5yXZrN9BEA3rEK --- .../src/pages/auth/ForgotPasswordPage.tsx | 2 + .../src/pages/auth/ResetPasswordPage.tsx | 7 ++- .../src/pages/auth/SetPasswordPage.tsx | 7 ++- .../src/console/auth/ForgotPasswordPage.tsx | 2 + .../src/console/auth/signInRefusalMessages.ts | 30 +++++++++++ ui/packages/app-shell/src/index.ts | 2 +- ui/packages/auth/src/ForgotPasswordForm.tsx | 17 ++++-- ui/packages/auth/src/LoginForm.tsx | 17 +----- ui/packages/auth/src/createAuthClient.ts | 53 ++++++++++++++----- ui/packages/auth/src/refusal-text.ts | 26 +++++++++ ui/packages/i18n/src/locales/ar.ts | 2 + ui/packages/i18n/src/locales/de.ts | 2 + ui/packages/i18n/src/locales/en.ts | 4 ++ ui/packages/i18n/src/locales/es.ts | 2 + ui/packages/i18n/src/locales/fr.ts | 2 + ui/packages/i18n/src/locales/ja.ts | 2 + ui/packages/i18n/src/locales/ko.ts | 2 + ui/packages/i18n/src/locales/pt-BR.ts | 2 + ui/packages/i18n/src/locales/ru.ts | 2 + ui/packages/i18n/src/locales/zh-Hans.ts | 2 + ui/packages/i18n/src/locales/zh-Hant.ts | 2 + 21 files changed, 151 insertions(+), 36 deletions(-) create mode 100644 ui/packages/auth/src/refusal-text.ts diff --git a/ui/apps/console/src/pages/auth/ForgotPasswordPage.tsx b/ui/apps/console/src/pages/auth/ForgotPasswordPage.tsx index d17ad43e20e..ffe2026f158 100644 --- a/ui/apps/console/src/pages/auth/ForgotPasswordPage.tsx +++ b/ui/apps/console/src/pages/auth/ForgotPasswordPage.tsx @@ -10,6 +10,7 @@ import { Link } from 'react-router-dom'; import { ForgotPasswordForm } from '@object-ui/auth'; import { useObjectTranslation } from '@object-ui/i18n'; import { Card } from '@object-ui/components'; +import { passwordDoorRefusalMessages } from '@object-ui/app-shell'; import { AuthLayout } from './AuthLayout'; function RouterLink(props: { href: string; className?: string; children: React.ReactNode }) { @@ -29,6 +30,7 @@ export function ForgotPasswordPage() { ( {children} @@ -21,6 +22,7 @@ export function ForgotPasswordPage() { title={t('auth.forgotPassword.title')} description={t('auth.forgotPassword.description')} linkComponent={RouterLink} + errorMessages={passwordDoorRefusalMessages(t)} labels={{ emailLabel: t('auth.forgotPassword.emailLabel'), emailPlaceholder: t('auth.forgotPassword.emailPlaceholder'), diff --git a/ui/packages/app-shell/src/console/auth/signInRefusalMessages.ts b/ui/packages/app-shell/src/console/auth/signInRefusalMessages.ts index e79391e1e7e..daa0b56c6f3 100644 --- a/ui/packages/app-shell/src/console/auth/signInRefusalMessages.ts +++ b/ui/packages/app-shell/src/console/auth/signInRefusalMessages.ts @@ -77,5 +77,35 @@ export function signInRefusalMessages( ACCOUNT_TEMPORARILY_LOCKED: t('auth.login.errors.twoFactorLocked', { defaultValue: 'Too many failed attempts. Your account is temporarily locked. Try again later.', }), + // objectstack#34171 — a cloud-managed runtime refuses the password sign-in + // with 409 `RESOURCE_CONFLICT` (plugin-auth `cloudManagedRefusal`, and the + // hosted relay in front of it): its people sign in through its identity + // provider, whose button the page draws above the form. Self-hosted + // deployments never answer this code on sign-in. + RESOURCE_CONFLICT: t('auth.login.errors.managedPasswordSignIn', { + defaultValue: + "This deployment signs you in through its identity provider, so a password can't be used here. Use the identity provider's button above to sign in.", + }), + }; +} + +/** + * Refusal `code` → localized text for the doors that request, reset or set a + * password: the forgot-password form's `errorMessages`, the reset-password + * page and the set-password page (objectstack#34171). + * + * A cloud-managed runtime refuses each of those doors with 409 + * `RESOURCE_CONFLICT`, because no local password is set or reset there for + * anyone; the sentence sends the person to the identity provider's button on + * the sign-in page. It is kept apart from `signInRefusalMessages` on purpose: + * that map's two-factor sentences (`INVALID_CODE`, …) describe the sign-in step + * and would be wrong on a reset door. Any other code keeps the server's text. + */ +export function passwordDoorRefusalMessages(t: TranslateFn): Record { + return { + RESOURCE_CONFLICT: t('auth.login.errors.managedPasswordReset', { + defaultValue: + "This deployment signs you in through its identity provider, so no password is set or reset here. Sign in with the identity provider's button on the sign-in page.", + }), }; } diff --git a/ui/packages/app-shell/src/index.ts b/ui/packages/app-shell/src/index.ts index 0fc1b501719..4e80c83031e 100644 --- a/ui/packages/app-shell/src/index.ts +++ b/ui/packages/app-shell/src/index.ts @@ -323,7 +323,7 @@ export { AppContent as DefaultAppContent } from './console/AppContent.js'; export { MarketplacePage } from './console/marketplace/MarketplacePage.js'; export { MarketplacePackagePage } from './console/marketplace/MarketplacePackagePage.js'; export { LoginPage as DefaultLoginPage } from './console/auth/LoginPage.js'; -export { signInRefusalMessages } from './console/auth/signInRefusalMessages.js'; +export { signInRefusalMessages, passwordDoorRefusalMessages } from './console/auth/signInRefusalMessages.js'; export { RegisterPage as DefaultRegisterPage } from './console/auth/RegisterPage.js'; export { signUpCaptchaFailedMessage, diff --git a/ui/packages/auth/src/ForgotPasswordForm.tsx b/ui/packages/auth/src/ForgotPasswordForm.tsx index 945d49f7a67..e4c11d9fa35 100644 --- a/ui/packages/auth/src/ForgotPasswordForm.tsx +++ b/ui/packages/auth/src/ForgotPasswordForm.tsx @@ -9,6 +9,7 @@ import React, { useEffect, useRef, useState } from 'react'; import { useAuth } from './useAuth.js'; import type { AuthLinkComponentProps } from './types.js'; +import { refusalText } from './refusal-text.js'; import { AUTH_FIELD_LABEL_CLASS, AUTH_INPUT_CLASS, @@ -90,6 +91,15 @@ export interface ForgotPasswordFormProps { labels?: ForgotPasswordFormLabels; /** Hide the icon disc above the form title. Defaults to false. */ hideIcon?: boolean; + /** + * Map of refusal `code` → localized message, as `LoginForm`'s + * `errorMessages` (objectstack#34171). A refusal with a known code shows the + * mapped string instead of the raw English server message (a cloud-managed + * runtime refuses the reset doors with 409 `RESOURCE_CONFLICT`); a refusal + * whose code the map has no entry for, or that carries none, shows the + * server message as before. `CODE:cause` keys are tried first. + */ + errorMessages?: Record; } const DefaultLink = ({ href, className, children }: AuthLinkComponentProps) => ( @@ -134,6 +144,7 @@ export function ForgotPasswordForm({ hideIcon = false, linkComponent: LinkComp = DefaultLink, labels = {}, + errorMessages, }: ForgotPasswordFormProps) { const { forgotPassword, @@ -245,7 +256,7 @@ export function ForgotPasswordForm({ onSuccess?.(); } catch (err) { const authError = err instanceof Error ? err : new Error(String(err)); - setError(authError.message); + setError(refusalText(authError, errorMessages)); onError?.(authError); } finally { resetRequestPending.current = false; @@ -268,7 +279,7 @@ export function ForgotPasswordForm({ setOtpCooldown(60); } catch (err) { const authError = err instanceof Error ? err : new Error(String(err)); - setError(authError.message); + setError(refusalText(authError, errorMessages)); onError?.(authError); } finally { setOtpSending(false); @@ -285,7 +296,7 @@ export function ForgotPasswordForm({ onSuccess?.(); } catch (err) { const authError = err instanceof Error ? err : new Error(String(err)); - setError(authError.message); + setError(refusalText(authError, errorMessages)); onError?.(authError); } finally { setResetting(false); diff --git a/ui/packages/auth/src/LoginForm.tsx b/ui/packages/auth/src/LoginForm.tsx index eaba863d194..758b392ce90 100644 --- a/ui/packages/auth/src/LoginForm.tsx +++ b/ui/packages/auth/src/LoginForm.tsx @@ -11,6 +11,7 @@ import { useAuth } from './useAuth.js'; import { SocialSignInButtons } from './SocialSignInButtons.js'; import { looksLikePhoneIdentifier, normalizePhoneIdentifier } from './phone-identifier.js'; import { TwoFactorChallengeForm } from './TwoFactorChallengeForm.js'; +import { refusalText } from './refusal-text.js'; import type { AuthLinkComponentProps } from './types.js'; import { AUTH_FIELD_LABEL_CLASS, @@ -171,22 +172,6 @@ export interface LoginFormProps { hideHeader?: boolean; } -/** - * The text a refused sign-in shows: the host's sentence for the refusal's - * `CODE:cause` (`details.cause`, objectstack#32432), else for its `code`, else - * the server's message. The server tells a client to branch on `code` and - * `details.cause`, never on the message, so the message is only the fallback. - */ -function refusalText(error: Error, errorMessages: Record | undefined): string { - const { code, details } = error as Error & { code?: string; details?: { cause?: unknown } }; - const cause = typeof details?.cause === 'string' && details.cause !== '' ? details.cause : undefined; - return ( - (code && cause && errorMessages?.[`${code}:${cause}`]) || - (code && errorMessages?.[code]) || - error.message - ); -} - /** * The "Sign in with SSO" request's watchdog: the same window and sentence as * the provider buttons' sign-in watchdog (`signInWithProvider` in diff --git a/ui/packages/auth/src/createAuthClient.ts b/ui/packages/auth/src/createAuthClient.ts index f0b13181c87..d78216271fc 100644 --- a/ui/packages/auth/src/createAuthClient.ts +++ b/ui/packages/auth/src/createAuthClient.ts @@ -103,6 +103,8 @@ interface BetterAuthErrorLike { dependents?: unknown; userMessage?: unknown; details?: unknown; + /** The ADR-0112 envelope's `error` object, when the body is `{ success: false, error }`. */ + error?: unknown; } /** @@ -196,23 +198,46 @@ function readDependents(raw: unknown): AuthErrorDependent[] | undefined { * and the absence of a code, never by the English sentence, so the status is * carried as well. The two-factor and invitation-preview errors in this file * already carry theirs. + * + * ## And the ADR-0112 envelope is read too (objectstack#34171) + * + * Not every refusal on these routes is better-auth's own flat body. A door + * the runtime answers before better-auth runs answers in the platform's + * ADR-0112 envelope, `{ success: false, error: { code, message, details } }`: + * a cloud-managed runtime's 409 `RESOURCE_CONFLICT` on the password doors is + * one (plugin-auth `cloudManagedRefusal`, and the hosted relay in front of + * it). better-fetch spreads that body too, so its half arrives nested under + * `error.error`. Each of `code`, `message`, `details` and `userMessage` is + * read from the flat body first and from the envelope's `error` only when the + * flat body has none, so a better-auth refusal answers exactly as before. Read + * at the top level only, the envelope's code was dropped and the page drew + * `Auth request failed with status 409` in every language. */ function toAuthError( error: BetterAuthErrorLike, fallbackMessage?: string, ): AuthClientError { + const envelope: BetterAuthErrorLike = isPlainObject(error.error) ? (error.error as BetterAuthErrorLike) : {}; + const message = error.message ?? stringOrUndefined(envelope.message); + const code = error.code || stringOrUndefined(envelope.code); + const userMessage = error.userMessage ?? envelope.userMessage; + const details = error.details ?? envelope.details; const err = new Error( - error.message ?? fallbackMessage ?? `Auth request failed with status ${error.status}`, + message ?? fallbackMessage ?? `Auth request failed with status ${error.status}`, ) as AuthClientError; - if (error.code) err.code = error.code; + if (code) err.code = code; if (typeof error.status === 'number') err.status = error.status; const dependents = readDependents(error.dependents); if (dependents) err.dependents = dependents; - if (typeof error.userMessage === 'string' && error.userMessage.trim()) err.userMessage = error.userMessage; - if (isPlainObject(error.details)) err.details = error.details; + if (typeof userMessage === 'string' && userMessage.trim()) err.userMessage = userMessage; + if (isPlainObject(details)) err.details = details; return err; } +function stringOrUndefined(value: unknown): string | undefined { + return typeof value === 'string' ? value : undefined; +} + function isPlainObject(value: unknown): value is Record { return typeof value === 'object' && value !== null && !Array.isArray(value); } @@ -951,16 +976,14 @@ export function createAuthClient(config: AuthClientConfig): AuthClient { email, redirectTo: resolveSpaRoute('/reset-password'), }); - if (error) { - throw new Error(error.message ?? `Auth request failed with status ${error.status}`); - } + // `toAuthError` keeps the refusal's code (objectstack#34171): a + // cloud-managed runtime refuses this door with 409 RESOURCE_CONFLICT. + if (error) throw toAuthError(error); }, async resetPassword(token: string, newPassword: string) { const { error } = await betterAuth.resetPassword({ token, newPassword }); - if (error) { - throw new Error(error.message ?? `Auth request failed with status ${error.status}`); - } + if (error) throw toAuthError(error); }, // --- Phone-number OTP (framework#2780) ------------------------------- @@ -1079,12 +1102,14 @@ export function createAuthClient(config: AuthClientConfig): AuthClient { body: JSON.stringify({ newPassword }), }); if (!response.ok) { - let message = `Set password failed with status ${response.status}`; + let body: BetterAuthErrorLike = {}; try { - const body = (await response.json()) as { error?: { message?: string; code?: string } }; - if (body?.error?.message) message = body.error.message; + const parsed: unknown = await response.json(); + if (isPlainObject(parsed)) body = parsed; } catch { /* not JSON */ } - throw new Error(message); + // `toAuthError` reads the ADR-0112 envelope's code (objectstack#34171): + // a cloud-managed runtime refuses this door with 409 RESOURCE_CONFLICT. + throw toAuthError({ ...body, status: response.status }, `Set password failed with status ${response.status}`); } }, diff --git a/ui/packages/auth/src/refusal-text.ts b/ui/packages/auth/src/refusal-text.ts new file mode 100644 index 00000000000..e84d8270150 --- /dev/null +++ b/ui/packages/auth/src/refusal-text.ts @@ -0,0 +1,26 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * The text a refused auth request shows: the host's sentence for the refusal's + * `CODE:cause` (`details.cause`, objectstack#32432), else for its `code`, else + * the server's message. The server tells a client to branch on `code` and + * `details.cause`, never on the message, so the message is only the fallback. + * + * Shared by `LoginForm` and `ForgotPasswordForm` (objectstack#34171), whose + * `errorMessages` props are the same kind of map. + */ +export function refusalText(error: Error, errorMessages: Record | undefined): string { + const { code, details } = error as Error & { code?: string; details?: { cause?: unknown } }; + const cause = typeof details?.cause === 'string' && details.cause !== '' ? details.cause : undefined; + return ( + (code && cause && errorMessages?.[`${code}:${cause}`]) || + (code && errorMessages?.[code]) || + error.message + ); +} diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index 08abb87aec9..db6c20a59fc 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -3339,6 +3339,8 @@ const ar = { twoFactorTooManyAttempts: "رموز غير صحيحة كثيرة جدًا. سجّل الدخول بكلمة المرور مرة أخرى.", twoFactorExpired: "انتهت صلاحية تسجيل الدخول هذا. سجّل الدخول بكلمة المرور مرة أخرى.", twoFactorLocked: "محاولات فاشلة كثيرة جدًا. حسابك مقفل مؤقتًا. حاول مرة أخرى لاحقًا.", + managedPasswordSignIn: "يتم تسجيل الدخول في هذا النشر عبر موفر الهوية الخاص به، لذا لا يمكن استخدام كلمة مرور هنا. استخدم زر موفر الهوية أعلاه لتسجيل الدخول.", + managedPasswordReset: "يتم تسجيل الدخول في هذا النشر عبر موفر الهوية الخاص به، لذا لا يتم تعيين كلمة مرور أو إعادة تعيينها هنا. سجّل الدخول باستخدام زر موفر الهوية في صفحة تسجيل الدخول.", invalidCredentials: "بريد إلكتروني أو كلمة مرور غير صحيحة. بعد عدة محاولات فاشلة، يتوقف تسجيل الدخول مؤقتًا لبعض الوقت. نسيت كلمة المرور؟ أعد تعيينها لتسجيل الدخول على الفور.", invalidCredentialsNoMail: 'بريد إلكتروني أو كلمة مرور غير صحيحة. بعد عدة محاولات فاشلة، يتوقف تسجيل الدخول مؤقتًا لبعض الوقت. نسيت كلمة المرور؟ اطلب من المسؤول إعادة تعيينها.', emailNotVerified: "يرجى التحقق من بريدك الإلكتروني قبل تسجيل الدخول.", diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index 2f0ee34a83b..a7568148dcb 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -3032,6 +3032,8 @@ const de = { twoFactorTooManyAttempts: "Zu viele falsche Codes. Melden Sie sich erneut mit Ihrem Passwort an.", twoFactorExpired: "Diese Anmeldung ist abgelaufen. Melden Sie sich erneut mit Ihrem Passwort an.", twoFactorLocked: "Zu viele fehlgeschlagene Versuche. Ihr Konto ist vorübergehend gesperrt. Versuchen Sie es später erneut.", + managedPasswordSignIn: "Diese Bereitstellung meldet Sie über ihren Identitätsanbieter an, daher kann hier kein Passwort verwendet werden. Melden Sie sich über die Schaltfläche des Identitätsanbieters oben an.", + managedPasswordReset: "Diese Bereitstellung meldet Sie über ihren Identitätsanbieter an, daher wird hier kein Passwort festgelegt oder zurückgesetzt. Melden Sie sich auf der Anmeldeseite über die Schaltfläche des Identitätsanbieters an.", invalidCredentials: "Ungültige E-Mail oder Passwort. Nach mehreren fehlgeschlagenen Versuchen wird die Anmeldung für eine Weile pausiert. Passwort vergessen? Setzen Sie es zurück, um sich sofort anzumelden.", invalidCredentialsNoMail: 'Ungültige E-Mail oder Passwort. Nach mehreren fehlgeschlagenen Versuchen wird die Anmeldung für eine Weile pausiert. Passwort vergessen? Bitten Sie Ihre Administration, es zurückzusetzen.', emailNotVerified: "Bitte bestätigen Sie Ihre E-Mail-Adresse, bevor Sie sich anmelden.", diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index a61df1a5cb2..941fe7e1217 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -3749,6 +3749,10 @@ const en = { twoFactorTooManyAttempts: 'Too many incorrect codes. Sign in with your password again.', twoFactorExpired: 'This sign-in has expired. Sign in with your password again.', twoFactorLocked: 'Too many failed attempts. Your account is temporarily locked. Try again later.', + // objectstack#34171 — a cloud-managed runtime's 409 `RESOURCE_CONFLICT` on the + // password doors (`signInRefusalMessages`, `passwordDoorRefusalMessages`). + managedPasswordSignIn: "This deployment signs you in through its identity provider, so a password can't be used here. Use the identity provider's button above to sign in.", + managedPasswordReset: "This deployment signs you in through its identity provider, so no password is set or reset here. Sign in with the identity provider's button on the sign-in page.", }, }, register: { diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index 5147089966e..1b7af43bcd9 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -3110,6 +3110,8 @@ const es = { twoFactorTooManyAttempts: "Demasiados códigos incorrectos. Vuelva a iniciar sesión con su contraseña.", twoFactorExpired: "Este inicio de sesión ha caducado. Vuelva a iniciar sesión con su contraseña.", twoFactorLocked: "Demasiados intentos fallidos. Su cuenta está bloqueada temporalmente. Inténtelo más tarde.", + managedPasswordSignIn: "Esta implementación inicia sesión a través de su proveedor de identidad, así que aquí no se puede usar una contraseña. Usa el botón del proveedor de identidad de arriba para iniciar sesión.", + managedPasswordReset: "Esta implementación inicia sesión a través de su proveedor de identidad, así que aquí no se establece ni se restablece ninguna contraseña. Inicia sesión con el botón del proveedor de identidad en la página de inicio de sesión.", invalidCredentials: "Correo o contraseña inválidos. Tras varios intentos fallidos, el inicio de sesión se pausa durante un tiempo. ¿Olvidaste tu contraseña? Restablécela para iniciar sesión de inmediato.", invalidCredentialsNoMail: 'Correo o contraseña inválidos. Tras varios intentos fallidos, el inicio de sesión se pausa durante un tiempo. ¿Olvidaste tu contraseña? Pide a tu administrador que la restablezca.', emailNotVerified: "Verifique su correo electrónico antes de iniciar sesión.", diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index 93e28a4436d..fb0dc64d659 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -3106,6 +3106,8 @@ const fr = { twoFactorTooManyAttempts: "Trop de codes incorrects. Reconnectez-vous avec votre mot de passe.", twoFactorExpired: "Cette connexion a expiré. Reconnectez-vous avec votre mot de passe.", twoFactorLocked: "Trop de tentatives échouées. Votre compte est temporairement verrouillé. Réessayez plus tard.", + managedPasswordSignIn: "Ce déploiement vous connecte via son fournisseur d'identité, aucun mot de passe ne peut donc être utilisé ici. Utilisez le bouton du fournisseur d'identité ci-dessus pour vous connecter.", + managedPasswordReset: "Ce déploiement vous connecte via son fournisseur d'identité, aucun mot de passe n'est donc défini ni réinitialisé ici. Connectez-vous avec le bouton du fournisseur d'identité sur la page de connexion.", invalidCredentials: "E-mail ou mot de passe invalide. Après plusieurs échecs, la connexion est suspendue pendant un moment. Mot de passe oublié ? Réinitialisez-le pour vous connecter immédiatement.", invalidCredentialsNoMail: 'E-mail ou mot de passe invalide. Après plusieurs échecs, la connexion est suspendue pendant un moment. Mot de passe oublié ? Demandez à votre administrateur de le réinitialiser.', emailNotVerified: "Veuillez vérifier votre adresse e-mail avant de vous connecter.", diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index e3ff0347854..a4d41e05603 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -3034,6 +3034,8 @@ const ja = { twoFactorTooManyAttempts: "誤ったコードの入力が多すぎます。パスワードでもう一度サインインしてください。", twoFactorExpired: "このサインインは期限切れです。パスワードでもう一度サインインしてください。", twoFactorLocked: "失敗した試行が多すぎるため、アカウントが一時的にロックされています。しばらくしてからもう一度お試しください。", + managedPasswordSignIn: "このデプロイは ID プロバイダー経由でサインインするため、ここではパスワードを使用できません。上の ID プロバイダーのボタンからサインインしてください。", + managedPasswordReset: "このデプロイは ID プロバイダー経由でサインインするため、ここではパスワードの設定やリセットは行いません。サインインページの ID プロバイダーのボタンからサインインしてください。", invalidCredentials: "メールアドレスまたはパスワードが正しくありません。失敗が続くと、サインインはしばらく一時停止されます。パスワードをお忘れの場合は、リセットするとすぐにサインインできます。", invalidCredentialsNoMail: 'メールアドレスまたはパスワードが正しくありません。失敗が続くと、サインインはしばらく一時停止されます。パスワードをお忘れの場合は、管理者にリセットを依頼してください。', emailNotVerified: "サインインする前にメールアドレスを確認してください。", diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index 3934d5cb4a1..7c0ade98290 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -3032,6 +3032,8 @@ const ko = { twoFactorTooManyAttempts: "잘못된 코드를 너무 많이 입력했습니다. 비밀번호로 다시 로그인하세요.", twoFactorExpired: "이 로그인이 만료되었습니다. 비밀번호로 다시 로그인하세요.", twoFactorLocked: "실패한 시도가 너무 많아 계정이 일시적으로 잠겼습니다. 나중에 다시 시도하세요.", + managedPasswordSignIn: "이 배포는 ID 공급자를 통해 로그인하므로 여기서는 비밀번호를 사용할 수 없습니다. 위의 ID 공급자 버튼을 눌러 로그인하세요.", + managedPasswordReset: "이 배포는 ID 공급자를 통해 로그인하므로 여기서는 비밀번호를 설정하거나 재설정하지 않습니다. 로그인 페이지에서 ID 공급자 버튼을 눌러 로그인하세요.", invalidCredentials: "잘못된 이메일 또는 비밀번호입니다. 여러 번 실패하면 잠시 동안 로그인이 일시 중지됩니다. 비밀번호를 잊으셨나요? 재설정하면 바로 로그인할 수 있습니다.", invalidCredentialsNoMail: '잘못된 이메일 또는 비밀번호입니다. 여러 번 실패하면 잠시 동안 로그인이 일시 중지됩니다. 비밀번호를 잊으셨나요? 관리자에게 재설정을 요청하세요.', emailNotVerified: "로그인하기 전에 이메일을 확인하세요.", diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index afd9926d3b0..98747e95c71 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -3105,6 +3105,8 @@ const pt = { twoFactorTooManyAttempts: "Muitos códigos incorretos. Faça login novamente com sua senha.", twoFactorExpired: "Este login expirou. Faça login novamente com sua senha.", twoFactorLocked: "Muitas tentativas malsucedidas. Sua conta está temporariamente bloqueada. Tente novamente mais tarde.", + managedPasswordSignIn: "Esta implantação faz o login pelo provedor de identidade dela, por isso não é possível usar uma senha aqui. Use o botão do provedor de identidade acima para entrar.", + managedPasswordReset: "Esta implantação faz o login pelo provedor de identidade dela, por isso nenhuma senha é definida ou redefinida aqui. Entre com o botão do provedor de identidade na página de login.", invalidCredentials: "E-mail ou senha inválidos. Após várias tentativas sem sucesso, o login fica pausado por um tempo. Esqueceu a senha? Redefina-a para entrar imediatamente.", invalidCredentialsNoMail: 'E-mail ou senha inválidos. Após várias tentativas sem sucesso, o login fica pausado por um tempo. Esqueceu a senha? Peça ao seu administrador para redefini-la.', emailNotVerified: "Por favor, verifique seu e-mail antes de fazer login.", diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index aaefb8c644b..8fc45c752c3 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -3193,6 +3193,8 @@ const ru = { twoFactorTooManyAttempts: "Слишком много неверных кодов. Войдите с паролем ещё раз.", twoFactorExpired: "Срок действия этого входа истёк. Войдите с паролем ещё раз.", twoFactorLocked: "Слишком много неудачных попыток. Учётная запись временно заблокирована. Повторите попытку позже.", + managedPasswordSignIn: "В этом развёртывании вход выполняется через поставщика удостоверений, поэтому пароль здесь использовать нельзя. Войдите с помощью кнопки поставщика удостоверений выше.", + managedPasswordReset: "В этом развёртывании вход выполняется через поставщика удостоверений, поэтому пароль здесь не задаётся и не сбрасывается. Войдите с помощью кнопки поставщика удостоверений на странице входа.", invalidCredentials: "Неверный email или пароль. После нескольких неудачных попыток вход приостанавливается на некоторое время. Забыли пароль? Сбросьте его, чтобы сразу войти.", invalidCredentialsNoMail: 'Неверный email или пароль. После нескольких неудачных попыток вход приостанавливается на некоторое время. Забыли пароль? Попросите администратора сбросить его.', emailNotVerified: "Пожалуйста, подтвердите email перед входом.", diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index 020c0566c46..ee675d228a3 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -3156,6 +3156,8 @@ const zh = { twoFactorTooManyAttempts: '错误次数过多,请重新使用密码登录。', twoFactorExpired: '本次登录已过期,请重新使用密码登录。', twoFactorLocked: '失败次数过多,您的账户已被暂时锁定,请稍后再试。', + managedPasswordSignIn: "此部署通过其身份提供方登录,这里不能使用密码。请点击上方的身份提供方按钮登录。", + managedPasswordReset: "此部署通过其身份提供方登录,这里不设置也不重置密码。请在登录页点击身份提供方按钮登录。", }, // objectui#3546 slice three — phone/OTP sign-in. `{seconds}` is LoginForm's own // literal `.replace()` hole, not i18next interpolation: keep the single braces. diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index bb768577152..af6995cb18b 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -3156,6 +3156,8 @@ const zhHant = { twoFactorTooManyAttempts: '錯誤次數過多,請重新使用密碼登入。', twoFactorExpired: '本次登入已過期,請重新使用密碼登入。', twoFactorLocked: '失敗次數過多,您的賬戶已被暫時鎖定,請稍後再試。', + managedPasswordSignIn: "此部署透過其身分提供者登入,這裡不能使用密碼。請點選上方的身分提供者按鈕登入。", + managedPasswordReset: "此部署透過其身分提供者登入,這裡不設定也不重設密碼。請在登入頁點選身分提供者按鈕登入。", }, // objectui#3546 slice three — phone/OTP sign-in. `{seconds}` is LoginForm's own // literal `.replace()` hole, not i18next interpolation: keep the single braces. From 8e8a190d75e54ce1e2029cf556944df093d75ef4 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 12:22:40 +0000 Subject: [PATCH 2/6] test(auth): pin the envelope code and the localized managed refusal Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01Q4EjjQkY5yXZrN9BEA3rEK --- .../loginRefusalCodes-11058.test.tsx | 50 +++++++- .../passwordDoorRefusal-34171.test.tsx | 116 ++++++++++++++++++ .../forgot-password-success-message.test.tsx | 40 ++++++ .../managedRefusalEnvelope-34171.test.ts | 94 ++++++++++++++ 4 files changed, 299 insertions(+), 1 deletion(-) create mode 100644 ui/packages/app-shell/src/console/auth/__tests__/passwordDoorRefusal-34171.test.tsx create mode 100644 ui/packages/auth/src/__tests__/managedRefusalEnvelope-34171.test.ts diff --git a/ui/packages/app-shell/src/console/auth/__tests__/loginRefusalCodes-11058.test.tsx b/ui/packages/app-shell/src/console/auth/__tests__/loginRefusalCodes-11058.test.tsx index e33368fcb2b..41f85cf3fdb 100644 --- a/ui/packages/app-shell/src/console/auth/__tests__/loginRefusalCodes-11058.test.tsx +++ b/ui/packages/app-shell/src/console/auth/__tests__/loginRefusalCodes-11058.test.tsx @@ -76,7 +76,12 @@ async function submitRefused( config?: unknown, extra?: Record, ): Promise { - const client = createAuthClient({ baseURL: AUTH_URL, fetchFn: refusingServer(status, code, message, config, extra) }); + return submitAgainst(refusingServer(status, code, message, config, extra)); +} + +/** Submit the zh form against `fetchFn`; return the banner text. */ +async function submitAgainst(fetchFn: typeof fetch): Promise { + const client = createAuthClient({ baseURL: AUTH_URL, fetchFn }); render( @@ -190,3 +195,46 @@ describe('DefaultLoginPage — a SCIM-deactivated sign-in is not shown as a ban expect(text).toBe(BAN_MESSAGE); }); }); + +// objectstack#34171 — a cloud-managed runtime refuses the password sign-in with +// 409 `RESOURCE_CONFLICT` in the ADR-0112 envelope, `{ success: false, error: +// { code, message } }` (plugin-auth `cloudManagedRefusal`, and the hosted relay +// in front of it), not in better-auth's flat body. The whole read path runs: +// `createAuthClient` reads the envelope's code, `LoginForm` looks it up in this +// package's map, and the page shows the zh sentence that points at the +// identity provider's button, never the server's English sentence or the +// client's status line. +describe('DefaultLoginPage — a cloud-managed password refusal is localized (objectstack#34171)', () => { + const HOSTED_SENTENCE = + 'This environment is hosted: everyone signs in through the cloud, with their own cloud account, and no local password ' + + 'is kept here for anyone. Sign in with ObjectOS Cloud. No password was set or accepted.'; + + function envelopeServer(status: number, code: string, message: string): typeof fetch { + const json = (s: number, body: unknown) => + new Response(JSON.stringify(body), { status: s, headers: { 'Content-Type': 'application/json' } }); + return (async (input: string | URL | Request) => { + const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url; + if (url.includes('/sign-in/email')) return json(status, { success: false, error: { code, message } }); + if (url.endsWith('/config')) return json(200, {}); + return json(200, null); + }) as typeof fetch; + } + + it('the zh pack translates the managed sign-in sentence', () => { + expect(zhErrors.managedPasswordSignIn).toBeTruthy(); + expect(zhErrors.managedPasswordSignIn).not.toBe(enErrors.managedPasswordSignIn); + }); + + it('409 RESOURCE_CONFLICT in the envelope shows the localized sentence, not the server or status text', async () => { + const text = await submitAgainst(envelopeServer(409, 'RESOURCE_CONFLICT', HOSTED_SENTENCE)); + expect(text).toBe(zhErrors.managedPasswordSignIn); + expect(screen.queryByText(HOSTED_SENTENCE)).toBeNull(); + expect(screen.queryByText(/Auth request failed/)).toBeNull(); + }); + + it('CONTROL: another code in the envelope still shows its own server message', async () => { + const raw = 'The server refused this sign-in for a reason the page has no text for.'; + const text = await submitAgainst(envelopeServer(400, 'UNMAPPED_REFUSAL_FOR_TEST', raw)); + expect(text).toBe(raw); + }); +}); diff --git a/ui/packages/app-shell/src/console/auth/__tests__/passwordDoorRefusal-34171.test.tsx b/ui/packages/app-shell/src/console/auth/__tests__/passwordDoorRefusal-34171.test.tsx new file mode 100644 index 00000000000..2c28992ed62 --- /dev/null +++ b/ui/packages/app-shell/src/console/auth/__tests__/passwordDoorRefusal-34171.test.tsx @@ -0,0 +1,116 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * objectstack#34171 — a cloud-managed runtime refuses "Forgot password?" with + * 409 `RESOURCE_CONFLICT` in the ADR-0112 envelope, because no local password + * is set or reset there for anyone. The forgot-password page this package + * publishes shows that refusal in the session's language and points at the + * identity provider's button, not the server's English sentence. + * + * Rendered as shipped: the exported page, `@object-ui/auth`'s real form, a real + * `AuthProvider` over a real `createAuthClient`, and a real `I18nProvider`. + * Only `fetch` is a stub. The expected text is read from the locale packs. + */ + +import '@testing-library/jest-dom/vitest'; +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { render, screen, cleanup } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { MemoryRouter } from 'react-router-dom'; +import { I18nProvider } from '@object-ui/i18n'; +import { builtInLocales, registerBuiltInLocales } from '@object-ui/i18n/locales'; +import { AuthProvider, createAuthClient } from '@object-ui/auth'; +import { ForgotPasswordPage } from '../ForgotPasswordPage'; +import { passwordDoorRefusalMessages, signInRefusalMessages } from '../signInRefusalMessages'; + +registerBuiltInLocales(); + +const AUTH_URL = 'http://localhost/api/v1/auth'; +const MANAGED_SENTENCE = + "This environment is cloud-managed: you sign in through the hosting organisation's identity provider, and no " + + 'local password is set or reset here for anyone, an administrator included. No reset link or code was sent.'; + +/** `/request-password-reset` answers `body` with `status`; everything else answers empty. */ +function server(status: number, body: unknown): typeof fetch { + const json = (s: number, b: unknown) => + new Response(JSON.stringify(b), { status: s, headers: { 'Content-Type': 'application/json' } }); + return (async (input: string | URL | Request) => { + const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url; + if (url.includes('/request-password-reset')) return json(status, body); + if (url.endsWith('/config')) return json(200, {}); + return json(200, null); + }) as typeof fetch; +} + +async function submitAgainst(fetchFn: typeof fetch): Promise { + const client = createAuthClient({ baseURL: AUTH_URL, fetchFn }); + render( + + + + + + + , + ); + const l = builtInLocales['zh-Hans'].auth.forgotPassword; + await userEvent.type(await screen.findByLabelText(l.emailLabel), 'someone@example.com'); + await userEvent.click(screen.getByRole('button', { name: l.submitButton })); + return (await screen.findByRole('alert')).textContent ?? ''; +} + +beforeEach(() => { + window.localStorage.clear(); + vi.spyOn(console, 'warn').mockImplementation(() => {}); +}); + +afterEach(() => { + cleanup(); + vi.restoreAllMocks(); +}); + +const zhErrors = builtInLocales['zh-Hans'].auth.login.errors; +const enErrors = builtInLocales.en.auth.login.errors; + +describe('ForgotPasswordPage — a cloud-managed reset refusal is localized (objectstack#34171)', () => { + it('the zh pack translates the managed reset sentence', () => { + expect(zhErrors.managedPasswordReset).toBeTruthy(); + expect(zhErrors.managedPasswordReset).not.toBe(enErrors.managedPasswordReset); + }); + + it('409 RESOURCE_CONFLICT in the envelope shows the localized sentence, not the server text', async () => { + const text = await submitAgainst( + server(409, { success: false, error: { code: 'RESOURCE_CONFLICT', message: MANAGED_SENTENCE } }), + ); + expect(text).toBe(zhErrors.managedPasswordReset); + expect(screen.queryByText(MANAGED_SENTENCE)).toBeNull(); + }); + + it('CONTROL: another refusal still shows its own server message', async () => { + const raw = 'The server refused this reset for a reason the page has no text for.'; + const text = await submitAgainst(server(400, { code: 'UNMAPPED_REFUSAL_FOR_TEST', message: raw })); + expect(text).toBe(raw); + }); +}); + +describe('passwordDoorRefusalMessages — the reset doors carry only the managed sentence (objectstack#34171)', () => { + const t = ((key: string, opts?: { defaultValue?: string }) => opts?.defaultValue ?? key) as never; + + it('maps RESOURCE_CONFLICT and nothing from the sign-in step', () => { + const map = passwordDoorRefusalMessages(t); + expect(Object.keys(map)).toEqual(['RESOURCE_CONFLICT']); + // The sign-in map's two-factor sentence must not reach a reset door. + expect(map.INVALID_CODE).toBeUndefined(); + expect(signInRefusalMessages(t).INVALID_CODE).toBeTruthy(); + }); + + it('the sign-in and reset sentences differ: the sign-in one points above, the reset one at the sign-in page', () => { + expect(passwordDoorRefusalMessages(t).RESOURCE_CONFLICT).not.toBe(signInRefusalMessages(t).RESOURCE_CONFLICT); + }); +}); diff --git a/ui/packages/auth/src/__tests__/forgot-password-success-message.test.tsx b/ui/packages/auth/src/__tests__/forgot-password-success-message.test.tsx index 65e1098b59d..c787ee83621 100644 --- a/ui/packages/auth/src/__tests__/forgot-password-success-message.test.tsx +++ b/ui/packages/auth/src/__tests__/forgot-password-success-message.test.tsx @@ -263,3 +263,43 @@ describe('ForgotPasswordForm — a submit while a reset request is pending is ig expect(reset.forgotPassword).toHaveBeenCalledTimes(2); }); }); + +// objectstack#34171 — the form maps a refusal by `code` through its +// `errorMessages` prop, as `LoginForm` does: a cloud-managed runtime refuses the +// reset request with 409 `RESOURCE_CONFLICT`. A code the map lacks keeps the +// server's message. +describe('ForgotPasswordForm — a refusal is mapped by code through errorMessages (objectstack#34171)', () => { + const MANAGED = 'Host text: sign in with the identity provider button.'; + + async function bannerAfter(err: Error, errorMessages?: Record): Promise { + const forgotPassword = vi.fn().mockRejectedValue(err); + render( + + + , + ); + await submit('user@example.com'); + return (await screen.findByRole('alert')).textContent ?? ''; + } + + function coded(code: string, message: string): Error { + const err = new Error(message) as Error & { code?: string }; + err.code = code; + return err; + } + + it('RESOURCE_CONFLICT shows the mapped sentence, not the server message', async () => { + const text = await bannerAfter(coded('RESOURCE_CONFLICT', 'Server English sentence.'), { RESOURCE_CONFLICT: MANAGED }); + expect(text).toBe(MANAGED); + }); + + it('CONTROL: a code the map lacks keeps the server message', async () => { + const text = await bannerAfter(coded('SOMETHING_ELSE', 'Server English sentence.'), { RESOURCE_CONFLICT: MANAGED }); + expect(text).toBe('Server English sentence.'); + }); + + it('CONTROL: with no errorMessages the server message is shown as before', async () => { + const text = await bannerAfter(coded('RESOURCE_CONFLICT', 'Server English sentence.')); + expect(text).toBe('Server English sentence.'); + }); +}); diff --git a/ui/packages/auth/src/__tests__/managedRefusalEnvelope-34171.test.ts b/ui/packages/auth/src/__tests__/managedRefusalEnvelope-34171.test.ts new file mode 100644 index 00000000000..5428622f4ec --- /dev/null +++ b/ui/packages/auth/src/__tests__/managedRefusalEnvelope-34171.test.ts @@ -0,0 +1,94 @@ +/** + * objectstack#34171 — the ADR-0112 envelope's code survives the client boundary. + * + * A cloud-managed runtime refuses the password doors with 409 + * `RESOURCE_CONFLICT` in the platform envelope, `{ success: false, error: { + * code, message } }` (plugin-auth `cloudManagedRefusal`, and the hosted relay + * in front of it), not in better-auth's flat `{ code, message }`. better-fetch + * spreads that body under `error.error`, and `toAuthError` read only the top + * level, so every door rejected with `Auth request failed with status 409` and + * no code: no host map could localize it. This drives the REAL client over a + * mocked `fetch`, like `authErrorStatus-33650.test.ts` next door. + */ + +import { describe, it, expect, vi } from 'vitest'; +import { createAuthClient } from '../createAuthClient'; + +const MANAGED = 'This environment is cloud-managed: no local password is set or reset here.'; +const ENVELOPE = { success: false, error: { code: 'RESOURCE_CONFLICT', message: MANAGED } }; + +function answering(pathFragment: string, status: number, body: unknown) { + return vi.fn(async (input: string | URL | Request) => { + const url = typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url; + const hit = url.includes(pathFragment); + return new Response(JSON.stringify(hit ? body : {}), { + status: hit ? status : 200, + headers: { 'Content-Type': 'application/json' }, + }); + }); +} + +type Rejection = Error & { code?: string; status?: number; details?: Record; userMessage?: string }; + +async function rejectionOf(promise: Promise): Promise { + try { + await promise; + } catch (err) { + return err as Rejection; + } + throw new Error('expected the call to reject, but it resolved'); +} + +function clientFor(pathFragment: string, status: number, body: unknown) { + const fetchFn = answering(pathFragment, status, body); + return createAuthClient({ baseURL: 'http://localhost/api/auth', fetchFn: fetchFn as unknown as typeof fetch }); +} + +describe('#34171 — an ADR-0112 envelope refusal keeps its code on every password door', () => { + const doors: Array<[string, string, (c: ReturnType) => Promise]> = [ + ['signIn', '/sign-in/email', (c) => c.signIn({ email: 'a@example.com', password: 'pw' })], + ['forgotPassword', '/request-password-reset', (c) => c.forgotPassword('a@example.com')], + ['resetPassword', '/reset-password', (c) => c.resetPassword('tok', 'new-password-1')], + ['setInitialPassword', '/set-initial-password', (c) => c.setInitialPassword('new-password-1')], + ]; + + it.each(doors)('%s: code RESOURCE_CONFLICT, the envelope message, status 409', async (_name, path, call) => { + const err = await rejectionOf(call(clientFor(path, 409, ENVELOPE))); + expect(err.code).toBe('RESOURCE_CONFLICT'); + expect(err.status).toBe(409); + expect(err.message).toBe(MANAGED); + }); + + it('carries the envelope\'s details and userMessage too', async () => { + const body = { + success: false, + error: { code: 'RESOURCE_CONFLICT', message: MANAGED, details: { door: 'signIn' }, userMessage: 'Shown text.' }, + }; + const err = await rejectionOf(clientFor('/sign-in/email', 409, body).signIn({ email: 'a@example.com', password: 'pw' })); + expect(err.details).toEqual({ door: 'signIn' }); + expect(err.userMessage).toBe('Shown text.'); + }); + + it('CONTROL: better-auth\'s flat refusal answers exactly as before', async () => { + const err = await rejectionOf( + clientFor('/sign-in/email', 401, { code: 'INVALID_EMAIL_OR_PASSWORD', message: 'Invalid email or password' }) + .signIn({ email: 'a@example.com', password: 'pw' }), + ); + expect(err.code).toBe('INVALID_EMAIL_OR_PASSWORD'); + expect(err.message).toBe('Invalid email or password'); + expect(err.status).toBe(401); + }); + + it('CONTROL: the flat body wins where both name a code or a message', async () => { + const body = { code: 'FLAT_CODE', message: 'Flat message', error: { code: 'NESTED_CODE', message: 'Nested message' } }; + const err = await rejectionOf(clientFor('/sign-in/email', 400, body).signIn({ email: 'a@example.com', password: 'pw' })); + expect(err.code).toBe('FLAT_CODE'); + expect(err.message).toBe('Flat message'); + }); + + it('CONTROL: a body with neither keeps the status line and no code', async () => { + const err = await rejectionOf(clientFor('/sign-in/email', 500, {}).signIn({ email: 'a@example.com', password: 'pw' })); + expect(err.code).toBeUndefined(); + expect(err.message).toBe('Auth request failed with status 500'); + }); +}); From cec63529df6d1e4636471422f8c5afdc9521af26 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 12:29:09 +0000 Subject: [PATCH 3/6] test(console): pin the localized managed refusal on reset and set-password Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01Q4EjjQkY5yXZrN9BEA3rEK --- .../passwordDoorRefusal-34171.test.tsx | 112 ++++++++++++++++++ 1 file changed, 112 insertions(+) create mode 100644 ui/apps/console/src/pages/auth/__tests__/passwordDoorRefusal-34171.test.tsx diff --git a/ui/apps/console/src/pages/auth/__tests__/passwordDoorRefusal-34171.test.tsx b/ui/apps/console/src/pages/auth/__tests__/passwordDoorRefusal-34171.test.tsx new file mode 100644 index 00000000000..9edbb9e371f --- /dev/null +++ b/ui/apps/console/src/pages/auth/__tests__/passwordDoorRefusal-34171.test.tsx @@ -0,0 +1,112 @@ +/** + * objectstack#34171 — a cloud-managed runtime refuses the reset-password and + * set-password doors with 409 `RESOURCE_CONFLICT`, because no local password is + * set or reset there for anyone. The console's two pages show that refusal in + * the session's language, pointing at the identity provider's button, through + * app-shell's `passwordDoorRefusalMessages`. Any other refusal keeps the + * server's text. Only `useAuth` and the toast are replaced; the pages, the + * refusal map and the zh pack are real. + */ + +import '@testing-library/jest-dom/vitest'; +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { render, screen, cleanup, waitFor } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { MemoryRouter } from 'react-router-dom'; +import { toast } from 'sonner'; +import { I18nProvider } from '@object-ui/i18n'; +import { builtInLocales, registerBuiltInLocales } from '@object-ui/i18n/locales'; + +let authState: Record; +vi.mock('@object-ui/auth', async (importOriginal) => ({ + ...(await importOriginal>()), + useAuth: () => authState, +})); + +vi.mock('sonner', async (importOriginal) => { + const actual = await importOriginal>(); + return { ...actual, toast: { success: vi.fn(), error: vi.fn() } }; +}); + +const { ResetPasswordPage } = await import('../ResetPasswordPage'); +const { SetPasswordPage } = await import('../SetPasswordPage'); + +registerBuiltInLocales(); + +const zh = builtInLocales['zh-Hans'].auth; +const SERVER_TEXT = 'This environment is cloud-managed: no local password is set or reset here.'; + +function coded(code: string, message: string): Error { + const err = new Error(message) as Error & { code?: string; status?: number }; + err.code = code; + return err; +} + +function renderAt(path: string, page: React.ReactElement) { + render( + + {page} + , + ); +} + +async function fillAndSubmit(labels: { newPassword: string; confirmPassword: string; submit: string }) { + await userEvent.type(await screen.findByLabelText(labels.newPassword), 'new-password-1'); + await userEvent.type(screen.getByLabelText(labels.confirmPassword), 'new-password-1'); + await userEvent.click(screen.getByRole('button', { name: labels.submit })); +} + +/** The description of the one error toast the page raised. */ +async function toastDescription(): Promise { + await waitFor(() => expect(toast.error).toHaveBeenCalledTimes(1)); + return (vi.mocked(toast.error).mock.calls[0][1] as { description?: unknown } | undefined)?.description; +} + +beforeEach(() => { + window.localStorage.clear(); + vi.mocked(toast.error).mockClear(); +}); + +afterEach(() => { + cleanup(); +}); + +describe('ResetPasswordPage — a cloud-managed refusal is localized (objectstack#34171)', () => { + async function refusedWith(err: Error): Promise { + authState = { resetPassword: vi.fn().mockRejectedValue(err) }; + renderAt('/reset-password?token=tok', ); + await fillAndSubmit(zh.resetPassword); + return toastDescription(); + } + + it('RESOURCE_CONFLICT shows the localized reset sentence, not the server text', async () => { + expect(await refusedWith(coded('RESOURCE_CONFLICT', SERVER_TEXT))).toBe(zh.login.errors.managedPasswordReset); + }); + + it('CONTROL: another refusal keeps its server message', async () => { + expect(await refusedWith(coded('INVALID_TOKEN', 'Invalid token'))).toBe('Invalid token'); + }); +}); + +describe('SetPasswordPage — a cloud-managed refusal is localized (objectstack#34171)', () => { + async function refusedWith(err: Error): Promise { + authState = { + user: { id: 'u1', name: 'Dana', email: 'dana@example.com' }, + isLoading: false, + setInitialPassword: vi.fn().mockRejectedValue(err), + }; + renderAt('/set-password', ); + await fillAndSubmit(zh.setPassword); + return toastDescription(); + } + + it('RESOURCE_CONFLICT shows the localized reset sentence, not the server text', async () => { + expect(await refusedWith(coded('RESOURCE_CONFLICT', SERVER_TEXT))).toBe(zh.login.errors.managedPasswordReset); + }); + + it('CONTROL: another refusal keeps its server message', async () => { + expect(await refusedWith(coded('CREDENTIAL_ACCOUNT_EXISTS', 'A password is already set'))).toBe( + 'A password is already set', + ); + }); +}); From 4766166e8e8cdc16438abe7ba58485bda0691a96 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 12:31:07 +0000 Subject: [PATCH 4/6] chore: changeset for the localized managed password refusal Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01Q4EjjQkY5yXZrN9BEA3rEK --- .../34171-managed-password-refusal-copy.md | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 .changeset/34171-managed-password-refusal-copy.md diff --git a/.changeset/34171-managed-password-refusal-copy.md b/.changeset/34171-managed-password-refusal-copy.md new file mode 100644 index 00000000000..f9a9409ec87 --- /dev/null +++ b/.changeset/34171-managed-password-refusal-copy.md @@ -0,0 +1,20 @@ +--- +'@object-ui/auth': patch +'@object-ui/app-shell': patch +'@object-ui/i18n': patch +'@object-ui/console': patch +--- + +fix(auth): a cloud-managed runtime's password refusal is shown in the session's language and points at the identity provider's button + +Clause-②: no +Metadata-protocol: none + +A cloud-managed runtime refuses the password doors (sign-in, forgot password, reset password, set password) with 409 `RESOURCE_CONFLICT` in the platform's error envelope, `{ success: false, error: { code, message } }`. The auth client read only better-auth's flat `{ code, message }`, so the code was dropped and every one of those pages showed `Auth request failed with status 409` in English, whatever the language. + +- **`@object-ui/auth`.** The client's error builder reads `code`, `message`, `details` and `userMessage` from the envelope's `error` when the flat body has none; a better-auth refusal answers exactly as before. `forgotPassword`, `resetPassword` and `setInitialPassword` now keep the refusal's code and status too. `ForgotPasswordForm` gains an `errorMessages` prop, the same code-to-text map `LoginForm` takes; without it the server's message is shown as before. +- **`@object-ui/app-shell`.** `signInRefusalMessages` maps `RESOURCE_CONFLICT` to a sentence that says the deployment signs people in through its identity provider and points at its button above the form. The new `passwordDoorRefusalMessages` carries the matching sentence for the forgot, reset and set-password doors, and the package's forgot-password page passes it. +- **`@object-ui/i18n`.** Two keys, `auth.login.errors.managedPasswordSignIn` and `auth.login.errors.managedPasswordReset`, in every locale. +- **`@object-ui/console`.** The forgot-password, reset-password and set-password pages show the same sentence. + +Self-hosted deployments never answer this refusal on these doors, so nothing changes there. Nothing to migrate. From fe59df0bce3265232f9864cf8efa4e648453f554 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 12:44:43 +0000 Subject: [PATCH 5/6] chore(i18n): regenerate zh-Hant from zh-Hans Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01Q4EjjQkY5yXZrN9BEA3rEK --- ui/packages/i18n/src/locales/zh-Hant.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index af6995cb18b..ab61399ecda 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -3156,8 +3156,8 @@ const zhHant = { twoFactorTooManyAttempts: '錯誤次數過多,請重新使用密碼登入。', twoFactorExpired: '本次登入已過期,請重新使用密碼登入。', twoFactorLocked: '失敗次數過多,您的賬戶已被暫時鎖定,請稍後再試。', - managedPasswordSignIn: "此部署透過其身分提供者登入,這裡不能使用密碼。請點選上方的身分提供者按鈕登入。", - managedPasswordReset: "此部署透過其身分提供者登入,這裡不設定也不重設密碼。請在登入頁點選身分提供者按鈕登入。", + managedPasswordSignIn: "此部署通過其身份提供方登入,這裡不能使用密碼。請點選上方的身份提供方按鈕登入。", + managedPasswordReset: "此部署通過其身份提供方登入,這裡不設定也不重置密碼。請在登入頁點選身份提供方按鈕登入。", }, // objectui#3546 slice three — phone/OTP sign-in. `{seconds}` is LoginForm's own // literal `.replace()` hole, not i18next interpolation: keep the single braces. From e28f6454095044252e53d347e8046a1f1d23d5fd Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 13:27:15 +0000 Subject: [PATCH 6/6] fix(auth): name the self-hosted producers of the password-door refusal and pin them Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01Q4EjjQkY5yXZrN9BEA3rEK --- .../34171-managed-password-refusal-copy.md | 6 ++-- .../passwordDoorRefusal-34171.test.tsx | 31 +++++++++++++++++++ .../src/console/auth/signInRefusalMessages.ts | 18 ++++++++--- 3 files changed, 48 insertions(+), 7 deletions(-) diff --git a/.changeset/34171-managed-password-refusal-copy.md b/.changeset/34171-managed-password-refusal-copy.md index f9a9409ec87..0568909ffbc 100644 --- a/.changeset/34171-managed-password-refusal-copy.md +++ b/.changeset/34171-managed-password-refusal-copy.md @@ -7,14 +7,14 @@ fix(auth): a cloud-managed runtime's password refusal is shown in the session's language and points at the identity provider's button -Clause-②: no +Clause-②: yes (widening) — `@object-ui/auth` `ForgotPasswordFormProps` gains the optional `errorMessages`; `@object-ui/i18n` gains `auth.login.errors.managedPasswordSignIn` and `auth.login.errors.managedPasswordReset` in every locale Metadata-protocol: none -A cloud-managed runtime refuses the password doors (sign-in, forgot password, reset password, set password) with 409 `RESOURCE_CONFLICT` in the platform's error envelope, `{ success: false, error: { code, message } }`. The auth client read only better-auth's flat `{ code, message }`, so the code was dropped and every one of those pages showed `Auth request failed with status 409` in English, whatever the language. +A cloud-managed runtime refuses the password doors (sign-in, forgot password, reset password, set password) with 409 `RESOURCE_CONFLICT`. Its code never reached the pages. The hosted relay and the set-password route answer in the platform's error envelope, `{ success: false, error: { code, message } }`, which the auth client did not read. Forgot and reset dropped the code where the client threw. So each of those pages showed the server's English sentence or `Auth request failed with status 409`, whatever the language. - **`@object-ui/auth`.** The client's error builder reads `code`, `message`, `details` and `userMessage` from the envelope's `error` when the flat body has none; a better-auth refusal answers exactly as before. `forgotPassword`, `resetPassword` and `setInitialPassword` now keep the refusal's code and status too. `ForgotPasswordForm` gains an `errorMessages` prop, the same code-to-text map `LoginForm` takes; without it the server's message is shown as before. - **`@object-ui/app-shell`.** `signInRefusalMessages` maps `RESOURCE_CONFLICT` to a sentence that says the deployment signs people in through its identity provider and points at its button above the form. The new `passwordDoorRefusalMessages` carries the matching sentence for the forgot, reset and set-password doors, and the package's forgot-password page passes it. - **`@object-ui/i18n`.** Two keys, `auth.login.errors.managedPasswordSignIn` and `auth.login.errors.managedPasswordReset`, in every locale. - **`@object-ui/console`.** The forgot-password, reset-password and set-password pages show the same sentence. -Self-hosted deployments never answer this refusal on these doors, so nothing changes there. Nothing to migrate. +On the sign-in door only a cloud-managed runtime answers this code, so a self-hosted sign-in is unchanged. On the reset and set-password doors a self-hosted deployment answers the same 409 `RESOURCE_CONFLICT` in two cases: an account its identity provider provisions while SSO-only mode is on, and a pending SSO person not yet signed in. Those pages now show the same localized sentence in place of the server's English one; it is true for that reader too. Nothing to migrate. diff --git a/ui/apps/console/src/pages/auth/__tests__/passwordDoorRefusal-34171.test.tsx b/ui/apps/console/src/pages/auth/__tests__/passwordDoorRefusal-34171.test.tsx index 9edbb9e371f..7ba360e4860 100644 --- a/ui/apps/console/src/pages/auth/__tests__/passwordDoorRefusal-34171.test.tsx +++ b/ui/apps/console/src/pages/auth/__tests__/passwordDoorRefusal-34171.test.tsx @@ -110,3 +110,34 @@ describe('SetPasswordPage — a cloud-managed refusal is localized (objectstack# ); }); }); + +// The same code has two self-hosted producers on these doors (plugin-auth +// `sso-only-local-password.ts`, `pending-sso-marker.ts`). The sentence is true +// for their reader too, so the mapping stands for them: an SSO-only refusal of +// an IdP-provisioned account shows the same localized sentence. +describe('Reset and set-password pages — a self-hosted SSO-only refusal shows the same sentence (objectstack#34171)', () => { + const SSO_ONLY_RESET = + 'This environment is in SSO-only mode and your account is provisioned by your identity provider, so you sign in ' + + 'through single sign-on and your local password cannot be reset here. Sign in with SSO. No password was set.'; + const SSO_ONLY_SET = + 'This environment is in SSO-only mode and your account is provisioned by your identity provider, so you sign in ' + + 'through single sign-on and a local password cannot be set for you here. Sign in with SSO. No password was set.'; + + it('reset-password: the SSO-only 409 RESOURCE_CONFLICT shows the localized reset sentence', async () => { + authState = { resetPassword: vi.fn().mockRejectedValue(coded('RESOURCE_CONFLICT', SSO_ONLY_RESET)) }; + renderAt('/reset-password?token=tok', ); + await fillAndSubmit(zh.resetPassword); + expect(await toastDescription()).toBe(zh.login.errors.managedPasswordReset); + }); + + it('set-password: the SSO-only 409 RESOURCE_CONFLICT shows the localized reset sentence', async () => { + authState = { + user: { id: 'u1', name: 'Dana', email: 'dana@example.com' }, + isLoading: false, + setInitialPassword: vi.fn().mockRejectedValue(coded('RESOURCE_CONFLICT', SSO_ONLY_SET)), + }; + renderAt('/set-password', ); + await fillAndSubmit(zh.setPassword); + expect(await toastDescription()).toBe(zh.login.errors.managedPasswordReset); + }); +}); diff --git a/ui/packages/app-shell/src/console/auth/signInRefusalMessages.ts b/ui/packages/app-shell/src/console/auth/signInRefusalMessages.ts index daa0b56c6f3..7a69e6fa1cd 100644 --- a/ui/packages/app-shell/src/console/auth/signInRefusalMessages.ts +++ b/ui/packages/app-shell/src/console/auth/signInRefusalMessages.ts @@ -94,10 +94,20 @@ export function signInRefusalMessages( * password: the forgot-password form's `errorMessages`, the reset-password * page and the set-password page (objectstack#34171). * - * A cloud-managed runtime refuses each of those doors with 409 - * `RESOURCE_CONFLICT`, because no local password is set or reset there for - * anyone; the sentence sends the person to the identity provider's button on - * the sign-in page. It is kept apart from `signInRefusalMessages` on purpose: + * Three plugin-auth producers answer 409 `RESOURCE_CONFLICT` on these doors, + * and the sentence is true for the reader of each: the person signs in through + * the identity provider, and no local password is set or reset here for them. + * + * - `cloud-managed.ts`: a cloud-managed runtime sets or resets no local + * password for anyone (and the hosted relay in front of it answers the same). + * - `sso-only-local-password.ts`: on a self-hosted deployment in SSO-only + * mode, an account the identity provider provisions has no local password + * set or reset (`reset-password`, `set-initial-password`). + * - `pending-sso-marker.ts`: a pending SSO person, added ahead of a first + * single sign-on, in every mode. + * + * The sentence sends the person to the identity provider's button on the + * sign-in page. It is kept apart from `signInRefusalMessages` on purpose: * that map's two-factor sentences (`INVALID_CODE`, …) describe the sign-in step * and would be wrong on a reset door. Any other code keeps the server's text. */