Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions .changeset/33498-link-refusal-other-codes-notice.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
---
'@object-ui/console': patch
'@object-ui/i18n': patch
---

fix(console): a signed-in person whose account link is refused as already linked to another user, or as unable to link, is told why on the page they land on

Clause-②: yes (widening) — the `@object-ui/i18n` locale packs gain two keys, `auth.login.errors.linkAlreadyLinkedToOtherUser` and `auth.login.errors.linkUnableToLink`, in all eleven shipped locales; no key is renamed or removed.
Metadata-protocol: none

Linking another sign-in to your account can be refused by the server for two more reasons besides a different email: the provider account is already linked to a different user here (`account_already_linked_to_different_user`), or it could not be linked at all (`unable_to_link_account`, chiefly when the sign-in service did not confirm the account's email as verified). Both send you back to the Console sign-in page, which, because you are still signed in, sent you straight on to the console with no word. Each now travels the same way as the email mismatch: the page you land on shows an error toast with its own sentence, in your language, until you close it. The sentence names no other user or email, and nothing from the URL is shown as it came. The refusals themselves are unchanged.
Original file line number Diff line number Diff line change
Expand Up @@ -210,3 +210,61 @@ describe('a signed-in person whose link was refused for an email mismatch is tol
expect(sessionStorage.getItem(LINK_REFUSAL_STORAGE_KEY)).toBeNull();
});
});

/**
* objectstack#33498 — better-auth's two other refusals of a signed-in link
* (`linkOAuthAccount`, `oauth2/link-account.mjs`) travel the same way, each
* with its own sentence: `account_already_linked_to_different_user` (the
* provider account belongs to another user here) and `unable_to_link_account`
* (chiefly an untrusted provider that did not assert the email as verified).
*/
describe('the other two link refusals are told where the signed-in person lands (objectstack#33498)', () => {
const SENTENCES = {
account_already_linked_to_different_user: {
en: en.auth.login.errors.linkAlreadyLinkedToOtherUser,
'zh-Hans': zh.auth.login.errors.linkAlreadyLinkedToOtherUser,
},
unable_to_link_account: {
en: en.auth.login.errors.linkUnableToLink,
'zh-Hans': zh.auth.login.errors.linkUnableToLink,
},
email_does_not_match: { en: EN_SENTENCE, 'zh-Hans': ZH_SENTENCE },
} as const;

it('each code has a sentence of its own, in each language', () => {
for (const language of ['en', 'zh-Hans'] as const) {
const shown = Object.values(SENTENCES).map((s) => s[language]);
for (const sentence of shown) expect(typeof sentence).toBe('string');
expect(new Set(shown).size).toBe(shown.length);
}
});

it.each([
['account_already_linked_to_different_user', 'en'],
['account_already_linked_to_different_user', 'zh-Hans'],
['unable_to_link_account', 'en'],
['unable_to_link_account', 'zh-Hans'],
// CONTROL: the first link refusal keeps its own sentence beside the new ones.
['email_does_not_match', 'en'],
['email_does_not_match', 'zh-Hans'],
] as const)('%s under %s: the landing page shows that code’s sentence, and nothing the URL carried', async (code, language) => {
const landed = await arriveSignedIn(
`?error=${code}&error_description=${encodeURIComponent('bob@example.com already owns it')}`,
language,
);
expect(landed).toBe('/');

const notice = await screen.findByTestId('link-refusal-notice', undefined, { timeout: 3000 });
expect(notice.textContent).toBe(SENTENCES[code][language]);
expect(document.body.textContent).not.toContain('bob@example.com');
expect(sessionStorage.getItem(LINK_REFUSAL_STORAGE_KEY)).toBeNull();
});

it('CONTROL: a vendor callback code that is not a link refusal still shows nothing new', async () => {
const landed = await arriveSignedIn('?error=email_not_found');
expect(landed).toBe('/');
await settle();
expect(screen.queryByTestId('link-refusal-notice')).toBeNull();
expect(sessionStorage.getItem(LINK_REFUSAL_STORAGE_KEY)).toBeNull();
});
});
24 changes: 24 additions & 0 deletions ui/apps/console/src/pages/auth/ssoCallbackRefusal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,18 @@ const LINK_EMAIL_MISMATCH: RefusalCopy = {
"The account was not linked: its email address doesn't match the one on the account you're signed in with. Link an account that uses the same email address.",
};

const LINK_ALREADY_LINKED_TO_OTHER_USER: RefusalCopy = {
key: 'auth.login.errors.linkAlreadyLinkedToOtherUser',
defaultValue:
'The account was not linked: it is already linked to a different user of this system. Link a different account, or sign in as the user it is linked to and unlink it there first.',
};

const LINK_UNABLE_TO_LINK: RefusalCopy = {
key: 'auth.login.errors.linkUnableToLink',
defaultValue:
'The account could not be linked. Check that its email address is verified with that sign-in service, then try again. If it still fails, ask your administrator.',
};

/**
* Callback `error` code → the sentence for a person who is ALREADY signed in.
*
Expand All @@ -142,12 +154,24 @@ const LINK_EMAIL_MISMATCH: RefusalCopy = {
* - `email_does_not_match`: better-auth refused to link a provider account
* whose email differs from the signed-in account's
* (`accountLinking.allowDifferentEmails` is off). No account row is written.
* - `account_already_linked_to_different_user`: the provider account is
* already linked to another user here (its email now matches the
* signed-in account's, or different emails are allowed). Nothing is
* moved. The sentence names no one.
* - `unable_to_link_account`: better-auth would not link it, chiefly because
* a provider that is not trusted did not assert the email as verified
* (also when linking is turned off, or the account row cannot be written).
*
* All three are `linkOAuthAccount`'s refusals (better-auth
* `oauth2/link-account.mjs`), redirected by the callback to the error URL.
*
* Only these codes travel; any other `error` a signed-in person arrives with
* is left where it was, and nothing from the URL is ever shown as it came.
*/
const SIGNED_IN_LINK_REFUSALS: Readonly<Record<string, RefusalCopy>> = {
email_does_not_match: LINK_EMAIL_MISMATCH,
account_already_linked_to_different_user: LINK_ALREADY_LINKED_TO_OTHER_USER,
unable_to_link_account: LINK_UNABLE_TO_LINK,
};

/** Whether `code` is a link refusal a signed-in person is told about where they land. */
Expand Down
2 changes: 2 additions & 0 deletions ui/packages/i18n/src/locales/ar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3008,6 +3008,8 @@ const ar = {
ssoBackToConsole: "العودة إلى وحدة التحكم",
ssoSwitchAccountHint: "يفتح «تبديل الحساب» خدمة تسجيل الدخول في علامة تبويب جديدة ويسجّل خروجك هناك. ثم سجّل الدخول هنا مرة أخرى بحساب لديه صلاحية الوصول.",
linkEmailMismatch: "لم يتم ربط الحساب: عنوان بريده الإلكتروني لا يطابق عنوان البريد الإلكتروني للحساب الذي سجّلت الدخول به. اربط حسابًا يستخدم عنوان البريد الإلكتروني نفسه.",
linkAlreadyLinkedToOtherUser: "لم يتم ربط الحساب: إنه مرتبط بالفعل بمستخدم آخر في هذا النظام. اربط حسابًا آخر، أو سجّل الدخول باسم المستخدم المرتبط به وألغِ الربط من هناك أولًا.",
linkUnableToLink: "تعذّر ربط الحساب. تأكد من أن عنوان بريده الإلكتروني مُتحقَّق منه لدى خدمة تسجيل الدخول تلك، ثم أعد المحاولة. إذا استمر الفشل، فاتصل بالمسؤول.",
twoFactorInvalidCode: "هذا الرمز غير صالح. تحقّق من تطبيق المصادقة وحاول مرة أخرى.",
twoFactorInvalidBackupCode: "رمز النسخ الاحتياطي هذا غير صالح أو سبق استخدامه.",
twoFactorTooManyAttempts: "رموز غير صحيحة كثيرة جدًا. سجّل الدخول بكلمة المرور مرة أخرى.",
Expand Down
2 changes: 2 additions & 0 deletions ui/packages/i18n/src/locales/de.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2734,6 +2734,8 @@ const de = {
ssoBackToConsole: "Zurück zur Konsole",
ssoSwitchAccountHint: "Konto wechseln öffnet Ihren Anmeldedienst in einem neuen Tab und meldet Sie dort ab. Melden Sie sich anschließend hier erneut mit einem Konto an, das Zugriff hat.",
linkEmailMismatch: "Das Konto wurde nicht verknüpft: Seine E-Mail-Adresse stimmt nicht mit der des Kontos überein, mit dem Sie angemeldet sind. Verknüpfen Sie ein Konto mit derselben E-Mail-Adresse.",
linkAlreadyLinkedToOtherUser: "Das Konto wurde nicht verknüpft: Es ist bereits mit einem anderen Benutzer dieses Systems verknüpft. Verknüpfen Sie ein anderes Konto, oder melden Sie sich als der Benutzer an, mit dem es verknüpft ist, und heben Sie die Verknüpfung dort zuerst auf.",
linkUnableToLink: "Das Konto konnte nicht verknüpft werden. Prüfen Sie, ob seine E-Mail-Adresse bei diesem Anmeldedienst bestätigt ist, und versuchen Sie es erneut. Wenn es weiterhin fehlschlägt, wenden Sie sich an Ihren Administrator.",
twoFactorInvalidCode: "Dieser Code ist ungültig. Prüfen Sie Ihre Authenticator-App und versuchen Sie es erneut.",
twoFactorInvalidBackupCode: "Dieser Backup-Code ist ungültig oder wurde bereits verwendet.",
twoFactorTooManyAttempts: "Zu viele falsche Codes. Melden Sie sich erneut mit Ihrem Passwort an.",
Expand Down
3 changes: 3 additions & 0 deletions ui/packages/i18n/src/locales/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3394,6 +3394,9 @@ const en = {
ssoSwitchAccountHint: "Switch account opens your sign-in service in a new tab and signs you out there. Then sign in here again with an account that has access.",
// A signed-in person's link refused by the callback (`email_does_not_match`), shown where they land.
linkEmailMismatch: "The account was not linked: its email address doesn't match the one on the account you're signed in with. Link an account that uses the same email address.",
// objectstack#33498 — the vendor's other two link refusals, shown the same way.
linkAlreadyLinkedToOtherUser: "The account was not linked: it is already linked to a different user of this system. Link a different account, or sign in as the user it is linked to and unlink it there first.",
linkUnableToLink: "The account could not be linked. Check that its email address is verified with that sign-in service, then try again. If it still fails, ask your administrator.",
// objectstack#29105 — refusals of the two-factor sign-in step, by the
// server's code (`signInRefusalMessages`).
twoFactorInvalidCode: 'That code is not valid. Check your authenticator app and try again.',
Expand Down
2 changes: 2 additions & 0 deletions ui/packages/i18n/src/locales/es.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2804,6 +2804,8 @@ const es = {
ssoBackToConsole: "Volver a la consola",
ssoSwitchAccountHint: "Cambiar de cuenta abre tu servicio de inicio de sesión en una pestaña nueva y cierra allí tu sesión. Después, vuelve a iniciar sesión aquí con una cuenta que tenga acceso.",
linkEmailMismatch: "La cuenta no se vinculó: su dirección de correo electrónico no coincide con la de la cuenta con la que iniciaste sesión. Vincula una cuenta que use la misma dirección de correo electrónico.",
linkAlreadyLinkedToOtherUser: "La cuenta no se vinculó: ya está vinculada a otro usuario de este sistema. Vincula otra cuenta, o inicia sesión como el usuario al que está vinculada y desvincúlala allí primero.",
linkUnableToLink: "No se pudo vincular la cuenta. Comprueba que su dirección de correo electrónico esté verificada en ese servicio de inicio de sesión y vuelve a intentarlo. Si sigue fallando, contacta con tu administrador.",
twoFactorInvalidCode: "Ese código no es válido. Revise su aplicación de autenticación e inténtelo de nuevo.",
twoFactorInvalidBackupCode: "Ese código de respaldo no es válido o ya se ha utilizado.",
twoFactorTooManyAttempts: "Demasiados códigos incorrectos. Vuelva a iniciar sesión con su contraseña.",
Expand Down
2 changes: 2 additions & 0 deletions ui/packages/i18n/src/locales/fr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2800,6 +2800,8 @@ const fr = {
ssoBackToConsole: "Retour à la console",
ssoSwitchAccountHint: "Changer de compte ouvre votre service de connexion dans un nouvel onglet et vous y déconnecte. Reconnectez-vous ensuite ici avec un compte qui a accès.",
linkEmailMismatch: "Le compte n'a pas été lié : son adresse e-mail ne correspond pas à celle du compte avec lequel vous êtes connecté. Liez un compte qui utilise la même adresse e-mail.",
linkAlreadyLinkedToOtherUser: "Le compte n'a pas été lié : il est déjà lié à un autre utilisateur de ce système. Liez un autre compte, ou connectez-vous en tant qu'utilisateur auquel il est lié et supprimez d'abord la liaison depuis ce compte.",
linkUnableToLink: "Le compte n'a pas pu être lié. Vérifiez que son adresse e-mail est confirmée auprès de ce service de connexion, puis réessayez. Si le problème persiste, contactez votre administrateur.",
twoFactorInvalidCode: "Ce code n'est pas valide. Vérifiez votre application d'authentification et réessayez.",
twoFactorInvalidBackupCode: "Ce code de secours n'est pas valide ou a déjà été utilisé.",
twoFactorTooManyAttempts: "Trop de codes incorrects. Reconnectez-vous avec votre mot de passe.",
Expand Down
2 changes: 2 additions & 0 deletions ui/packages/i18n/src/locales/ja.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2736,6 +2736,8 @@ const ja = {
ssoBackToConsole: "コンソールに戻る",
ssoSwitchAccountHint: "「アカウントを切り替える」を選ぶと、新しいタブでサインインサービスが開き、そこでサインアウトします。その後、アクセス権のあるアカウントでここから再度サインインしてください。",
linkEmailMismatch: "アカウントはリンクされませんでした。そのメールアドレスが、サインイン中のアカウントのメールアドレスと一致しません。同じメールアドレスを使用するアカウントをリンクしてください。",
linkAlreadyLinkedToOtherUser: "アカウントはリンクされませんでした。このシステムの別のユーザーに既にリンクされています。別のアカウントをリンクするか、リンク先のユーザーとしてサインインし、先にそちらでリンクを解除してください。",
linkUnableToLink: "アカウントをリンクできませんでした。そのメールアドレスがそのサインインサービスで確認済みであることを確かめてから、もう一度お試しください。それでも失敗する場合は、管理者にお問い合わせください。",
twoFactorInvalidCode: "コードが無効です。認証アプリを確認して、もう一度お試しください。",
twoFactorInvalidBackupCode: "このバックアップコードは無効か、すでに使用されています。",
twoFactorTooManyAttempts: "誤ったコードの入力が多すぎます。パスワードでもう一度サインインしてください。",
Expand Down
2 changes: 2 additions & 0 deletions ui/packages/i18n/src/locales/ko.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2734,6 +2734,8 @@ const ko = {
ssoBackToConsole: "콘솔로 돌아가기",
ssoSwitchAccountHint: "계정 전환을 누르면 새 탭에서 로그인 서비스가 열리고 그곳에서 로그아웃됩니다. 그런 다음 액세스 권한이 있는 계정으로 여기에서 다시 로그인하세요.",
linkEmailMismatch: "계정이 연결되지 않았습니다. 해당 계정의 이메일 주소가 현재 로그인한 계정의 이메일 주소와 일치하지 않습니다. 같은 이메일 주소를 사용하는 계정을 연결하세요.",
linkAlreadyLinkedToOtherUser: "계정이 연결되지 않았습니다. 이 시스템의 다른 사용자에게 이미 연결되어 있습니다. 다른 계정을 연결하거나, 해당 계정이 연결된 사용자로 로그인하여 먼저 그곳에서 연결을 해제하세요.",
linkUnableToLink: "계정을 연결할 수 없습니다. 해당 계정의 이메일 주소가 그 로그인 서비스에서 인증되었는지 확인한 후 다시 시도하세요. 계속 실패하면 관리자에게 문의하세요.",
twoFactorInvalidCode: "코드가 올바르지 않습니다. 인증 앱을 확인한 후 다시 시도하세요.",
twoFactorInvalidBackupCode: "백업 코드가 올바르지 않거나 이미 사용되었습니다.",
twoFactorTooManyAttempts: "잘못된 코드를 너무 많이 입력했습니다. 비밀번호로 다시 로그인하세요.",
Expand Down
2 changes: 2 additions & 0 deletions ui/packages/i18n/src/locales/pt-BR.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2799,6 +2799,8 @@ const pt = {
ssoBackToConsole: "Voltar ao console",
ssoSwitchAccountHint: "Trocar de conta abre seu serviço de login em uma nova aba e encerra sua sessão lá. Depois, entre aqui novamente com uma conta que tenha acesso.",
linkEmailMismatch: "A conta não foi vinculada: o endereço de e-mail dela não corresponde ao da conta com a qual você entrou. Vincule uma conta que use o mesmo endereço de e-mail.",
linkAlreadyLinkedToOtherUser: "A conta não foi vinculada: ela já está vinculada a outro usuário deste sistema. Vincule outra conta ou entre como o usuário ao qual ela está vinculada e desvincule-a lá primeiro.",
linkUnableToLink: "Não foi possível vincular a conta. Verifique se o endereço de e-mail dela está confirmado nesse serviço de login e tente novamente. Se continuar falhando, fale com seu administrador.",
twoFactorInvalidCode: "Esse código não é válido. Verifique seu aplicativo autenticador e tente novamente.",
twoFactorInvalidBackupCode: "Esse código de backup não é válido ou já foi usado.",
twoFactorTooManyAttempts: "Muitos códigos incorretos. Faça login novamente com sua senha.",
Expand Down
2 changes: 2 additions & 0 deletions ui/packages/i18n/src/locales/ru.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2879,6 +2879,8 @@ const ru = {
ssoBackToConsole: "Вернуться в консоль",
ssoSwitchAccountHint: "«Сменить учётную запись» открывает вашу службу входа в новой вкладке и выполняет там выход. Затем снова войдите здесь с учётной записью, у которой есть доступ.",
linkEmailMismatch: "Учётная запись не связана: её адрес электронной почты не совпадает с адресом учётной записи, с которой вы вошли. Свяжите учётную запись с тем же адресом электронной почты.",
linkAlreadyLinkedToOtherUser: "Учётная запись не связана: она уже связана с другим пользователем этой системы. Свяжите другую учётную запись или войдите как пользователь, с которым она связана, и сначала отвяжите её там.",
linkUnableToLink: "Не удалось связать учётную запись. Убедитесь, что её адрес электронной почты подтверждён в этой службе входа, и повторите попытку. Если ошибка повторится, обратитесь к администратору.",
twoFactorInvalidCode: "Неверный код. Проверьте приложение-аутентификатор и попробуйте ещё раз.",
twoFactorInvalidBackupCode: "Резервный код неверен или уже использован.",
twoFactorTooManyAttempts: "Слишком много неверных кодов. Войдите с паролем ещё раз.",
Expand Down
Loading
Loading