Skip to content

⭐️⭐️⭐️ 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.

fix(web): a refused sign-up says why, in the visitor's language (#553)

Pasqual Troncone80a868355a5b
diff --git a/apps/api/src/__tests__/integration/registration-refusal-redirect.test.ts b/apps/api/src/__tests__/integration/registration-refusal-redirect.test.ts
new file mode 100644
index 00000000..46d98222
--- /dev/null
+++ b/apps/api/src/__tests__/integration/registration-refusal-redirect.test.ts
@@ -0,0 +1,167 @@
+import { afterEach, beforeEach, describe, expect, it } from 'bun:test';
+import { app, authedApi } from '#tests/helpers/app';
+import { openMagicLink, signUpTestUser } from '#tests/helpers/auth';
+import { resetDb } from '#tests/helpers/db';
+
+// The web's sign-in page reads ?error= after a provider round trip, so the form of that
+// parameter is the contract this pins: the registration gate's refusal code, on every
+// sign-up path (see useRedirectError in the web).
+function startProvider() {
+ return Bun.serve({
+ port: 0,
+ fetch(req) {
+ const { origin, pathname } = new URL(req.url);
+ switch (pathname) {
+ case '/.well-known/openid-configuration':
+ return Response.json({
+ issuer: origin,
+ authorization_endpoint: `${origin}/authorize`,
+ token_endpoint: `${origin}/token`,
+ userinfo_endpoint: `${origin}/userinfo`,
+ });
+ case '/token':
+ return Response.json({ access_token: 'token', token_type: 'Bearer', expires_in: 3600 });
+ case '/userinfo':
+ return Response.json({
+ sub: 'idp-newcomer',
+ email: '[email protected]',
+ email_verified: true,
+ name: 'Newcomer',
+ });
+ default:
+ return new Response('Not found', { status: 404 });
+ }
+ },
+ });
+}
+
+// Google's token endpoint is fixed, so its exchange is answered here. better-auth reads
+// the profile from the id_token without verifying it on the callback.
+const realFetch = globalThis.fetch;
+function answerGoogleToken() {
+ const part = (value: object) => Buffer.from(JSON.stringify(value)).toString('base64url');
+ const idToken = `${part({ alg: 'none' })}.${part({
+ sub: 'google-newcomer',
+ email: '[email protected]',
+ email_verified: true,
+ name: 'Newcomer',
+ })}.`;
+ globalThis.fetch = (async (input: string | URL | Request, init?: RequestInit) => {
+ const url = input instanceof Request ? input.url : String(input);
+ if (url.startsWith('https://oauth2.googleapis.com/token')) {
+ return Response.json({
+ access_token: 'token',
+ id_token: idToken,
+ token_type: 'Bearer',
+ expires_in: 3600,
+ });
+ }
+ return realFetch(input, init);
+ }) as typeof fetch;
+}
+
+function cookiesOf(res: Response): string {
+ return res.headers
+ .getSetCookie()
+ .map((c) => c.split(';')[0])
+ .join('; ');
+}
+
+describe('a sign-up the registration gate refuses', () => {
+ let provider: ReturnType<typeof Bun.serve>;
+
+ beforeEach(async () => {
+ await resetDb();
+ provider = startProvider();
+ });
+
+ afterEach(async () => {
+ globalThis.fetch = realFetch;
+ await provider.stop(true);
+ });
+
+ async function setUp(registration: 'invite' | 'closed') {
+ const god = authedApi((await signUpTestUser({ name: 'Root' })).cookie);
+ const google = await god.god['google-settings'].put({
+ enabled: true,
+ clientId: 'google-client',
+ clientSecret: 'google-secret',
+ });
+ expect(google.status).toBe(200);
+ const oidc = await god.god['oidc-settings'].put({
+ discoveryUrl: `http://localhost:${provider.port}/.well-known/openid-configuration`,
+ clientId: 'itsaplan',
+ clientSecret: 'client-secret',
+ label: 'Test IdP',
+ enabled: true,
+ });
+ expect(oidc.status).toBe(200);
+ expect((await god.god['auth-settings'].put({ registration })).status).toBe(200);
+ }
+
+ // The better-auth endpoints are not modelled by Eden Treaty, so they are driven
+ // through the app handler.
+ const routes = {
+ oidc: {
+ start: '/api/auth/sign-in/social',
+ body: { provider: 'oidc', callbackURL: '/' },
+ callback: '/api/auth/oauth2/callback/oidc',
+ },
+ google: {
+ start: '/api/auth/sign-in/social',
+ body: { provider: 'google', callbackURL: '/' },
+ callback: '/api/auth/callback/google',
+ },
+ };
+
+ async function errorAfterProvider(via: keyof typeof routes): Promise<string | null> {
+ const route = routes[via];
+ if (via === 'google') answerGoogleToken();
+ const start = await app.handle(
+ new Request(`http://localhost${route.start}`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify(route.body),
+ }),
+ );
+ expect(start.status).toBe(200);
+ const { url } = (await start.json()) as { url: string };
+ const state = new URL(url).searchParams.get('state') ?? '';
+
+ const callback = await app.handle(
+ new Request(`http://localhost${route.callback}?code=code-1&state=${state}`, {
+ headers: { cookie: cookiesOf(start) },
+ }),
+ );
+ expect(callback.status).toBe(302);
+ const location = new URL(callback.headers.get('location') ?? '', 'http://localhost');
+ return location.searchParams.get('error');
+ }
+
+ for (const via of ['oidc', 'google'] as const) {
+ it(`redirects a ${via} sign-up on a closed instance with REGISTRATION_CLOSED`, async () => {
+ await setUp('closed');
+ expect(await errorAfterProvider(via)).toBe('REGISTRATION_CLOSED');
+ });
+
+ it(`redirects a ${via} sign-up without an invite with INVITE_ONLY`, async () => {
+ await setUp('invite');
+ expect(await errorAfterProvider(via)).toBe('INVITE_ONLY');
+ });
+ }
+
+ // The link is asked for from the sign-in page, which names itself as errorCallbackURL.
+ it('sends a refused magic-link sign-up on a closed instance to sign-in with its code', async () => {
+ await setUp('closed');
+ const location = await openMagicLink('[email protected]', 'magic-closed');
+ expect(location.pathname).toBe('/login');
+ expect(location.searchParams.get('error')).toBe('REGISTRATION_CLOSED');
+ });
+
+ it('sends a refused magic-link sign-up without an invite to sign-in with its code', async () => {
+ await setUp('invite');
+ const location = await openMagicLink('[email protected]', 'magic-stranger');
+ expect(location.pathname).toBe('/login');
+ expect(location.searchParams.get('error')).toBe('INVITE_ONLY');
+ });
+});
diff --git a/apps/web/messages/ar/auth.json b/apps/web/messages/ar/auth.json
index e4e3579c..bc5c4ed0 100644
--- a/apps/web/messages/ar/auth.json
+++ b/apps/web/messages/ar/auth.json
@@ -93,6 +93,8 @@
"userNotFound": "رابط التأكيد ده بتاع حساب مبقاش موجود.",
"ssoDisabled": "الدخول الموحّد غير متاح على هذا الخادم.",
"passwordDisabled": "يتم تسجيل الدخول على هذا الخادم عبر مزوّد الهوية فقط.",
- "accountDeactivated": "هذا الحساب معطّل. اطلب من المسؤول إعادة تفعيله."
+ "accountDeactivated": "هذا الحساب معطّل. اطلب من المسؤول إعادة تفعيله.",
+ "registrationClosed": "هذه النسخة لا تقبل حسابات جديدة. اطلب الوصول من المسؤول.",
+ "inviteOnly": "هذه النسخة تقبل المدعوّين فقط. اطلب دعوة من المسؤول."
}
}
diff --git a/apps/web/messages/en/auth.json b/apps/web/messages/en/auth.json
index d6abb62d..01c123cb 100644
--- a/apps/web/messages/en/auth.json
+++ b/apps/web/messages/en/auth.json
@@ -93,6 +93,8 @@
"userNotFound": "This confirmation link belongs to an account that no longer exists.",
"ssoDisabled": "Single sign-on is not available on this instance.",
"passwordDisabled": "This instance signs people in through its identity provider only.",
- "accountDeactivated": "This account is deactivated. Ask your administrator to restore it."
+ "accountDeactivated": "This account is deactivated. Ask your administrator to restore it.",
+ "registrationClosed": "This instance is not open for new accounts. Ask your administrator for access.",
+ "inviteOnly": "This instance only admits people who have been invited. Ask your administrator for an invite."
}
}
diff --git a/apps/web/messages/es-ES/auth.json b/apps/web/messages/es-ES/auth.json
index 54220854..3d772ecd 100644
--- a/apps/web/messages/es-ES/auth.json
+++ b/apps/web/messages/es-ES/auth.json
@@ -93,6 +93,8 @@
"userNotFound": "Este enlace de confirmación pertenece a una cuenta que ya no existe.",
"ssoDisabled": "El inicio de sesión único no está disponible en esta instancia.",
"passwordDisabled": "Esta instancia inicia sesión de las personas solo a través de su proveedor de identidades.",
- "accountDeactivated": "Esta cuenta está desactivada. Pide a tu administrador que la restaure."
+ "accountDeactivated": "Esta cuenta está desactivada. Pide a tu administrador que la restaure.",
+ "registrationClosed": "Esta instancia no admite cuentas nuevas. Pide acceso a tu administrador.",
+ "inviteOnly": "Esta instancia solo admite a quienes han sido invitados. Pide una invitación a tu administrador."
}
}
diff --git a/apps/web/messages/fr/auth.json b/apps/web/messages/fr/auth.json
index 8c9fd81b..c765c573 100644
--- a/apps/web/messages/fr/auth.json
+++ b/apps/web/messages/fr/auth.json
@@ -93,6 +93,8 @@
"userNotFound": "Ce lien de confirmation appartient à un compte qui n'existe plus.",
"ssoDisabled": "L'authentification unique n'est pas disponible sur cette instance.",
"passwordDisabled": "Cette instance ne connecte les utilisateurs que via son fournisseur d'identité.",
- "accountDeactivated": "Ce compte est désactivé. Demandez à votre administrateur de le rétablir."
+ "accountDeactivated": "Ce compte est désactivé. Demandez à votre administrateur de le rétablir.",
+ "registrationClosed": "Cette instance n'accepte pas de nouveaux comptes. Demandez l'accès à votre administrateur.",
+ "inviteOnly": "Cette instance n'admet que les personnes invitées. Demandez une invitation à votre administrateur."
}
}
diff --git a/apps/web/messages/id/auth.json b/apps/web/messages/id/auth.json
index d9d65e0e..51d4d71f 100644
--- a/apps/web/messages/id/auth.json
+++ b/apps/web/messages/id/auth.json
@@ -93,6 +93,8 @@
"userNotFound": "Tautan konfirmasi ini milik akun yang sudah tidak ada.",
"ssoDisabled": "Single sign-on tidak tersedia di instance ini.",
"passwordDisabled": "Instance ini hanya mengizinkan pengguna masuk melalui penyedia identitasnya.",
- "accountDeactivated": "Akun ini telah dinonaktifkan. Minta administrator Anda untuk memulihkannya."
+ "accountDeactivated": "Akun ini telah dinonaktifkan. Minta administrator Anda untuk memulihkannya.",
+ "registrationClosed": "Instance ini tidak menerima akun baru. Minta akses kepada administrator Anda.",
+ "inviteOnly": "Instance ini hanya menerima orang yang diundang. Minta undangan kepada administrator Anda."
}
}
diff --git a/apps/web/messages/ko/auth.json b/apps/web/messages/ko/auth.json
index bca851d0..2eb098dc 100644
--- a/apps/web/messages/ko/auth.json
+++ b/apps/web/messages/ko/auth.json
@@ -93,6 +93,8 @@
"userNotFound": "이 인증 링크에 연결된 계정이 더 이상 존재하지 않습니다.",
"ssoDisabled": "이 서버에서는 SSO를 사용할 수 없습니다.",
"passwordDisabled": "이 서버에서는 ID 공급자를 통해서만 로그인할 수 있습니다.",
- "accountDeactivated": "비활성화된 계정입니다. 관리자에게 계정 복구를 요청하세요."
+ "accountDeactivated": "비활성화된 계정입니다. 관리자에게 계정 복구를 요청하세요.",
+ "registrationClosed": "이 서버는 새 계정을 받지 않습니다. 관리자에게 접근 권한을 요청하세요.",
+ "inviteOnly": "이 서버는 초대받은 사람만 가입할 수 있습니다. 관리자에게 초대를 요청하세요."
}
}
diff --git a/apps/web/messages/pt-BR/auth.json b/apps/web/messages/pt-BR/auth.json
index a9c88c45..5e7d6742 100644
--- a/apps/web/messages/pt-BR/auth.json
+++ b/apps/web/messages/pt-BR/auth.json
@@ -93,6 +93,8 @@
"userNotFound": "Este link de confirmação pertence a uma conta que não existe mais.",
"ssoDisabled": "O single sign-on não está disponível nesta instância.",
"passwordDisabled": "Esta instância conecta pessoas apenas pelo seu provedor de identidade.",
- "accountDeactivated": "Esta conta está desativada. Peça ao seu administrador para restaurá-la."
+ "accountDeactivated": "Esta conta está desativada. Peça ao seu administrador para restaurá-la.",
+ "registrationClosed": "Esta instância não aceita contas novas. Peça acesso ao seu administrador.",
+ "inviteOnly": "Esta instância só admite pessoas convidadas. Peça um convite ao seu administrador."
}
}
diff --git a/apps/web/messages/ru/auth.json b/apps/web/messages/ru/auth.json
index 64ea6135..a8c04246 100644
--- a/apps/web/messages/ru/auth.json
+++ b/apps/web/messages/ru/auth.json
@@ -93,6 +93,8 @@
"userNotFound": "Ссылка для подтверждения принадлежит аккаунту, которого больше не существует.",
"ssoDisabled": "Единый вход недоступен на этом сервере.",
"passwordDisabled": "На этом сервере вход выполняется только через поставщика удостоверений.",
- "accountDeactivated": "Учётная запись отключена. Обратитесь к администратору."
+ "accountDeactivated": "Учётная запись отключена. Обратитесь к администратору.",
+ "registrationClosed": "Этот инстанс не принимает новые учётные записи. Запросите доступ у администратора.",
+ "inviteOnly": "В этот инстанс допускаются только приглашённые. Попросите приглашение у администратора."
}
}
diff --git a/apps/web/messages/uk/auth.json b/apps/web/messages/uk/auth.json
index 6eb3853d..e8951bf6 100644
--- a/apps/web/messages/uk/auth.json
+++ b/apps/web/messages/uk/auth.json
@@ -93,6 +93,8 @@
"userNotFound": "Посилання для підтвердження належить акаунту, якого більше не існує.",
"ssoDisabled": "Єдиний вхід недоступний на цьому сервері.",
"passwordDisabled": "На цьому сервері вхід виконується лише через постачальника ідентифікації.",
- "accountDeactivated": "Обліковий запис вимкнено. Зверніться до адміністратора."
+ "accountDeactivated": "Обліковий запис вимкнено. Зверніться до адміністратора.",
+ "registrationClosed": "Цей інстанс не приймає нових облікових записів. Попросіть доступ в адміністратора.",
+ "inviteOnly": "До цього інстансу допускаються лише запрошені. Попросіть запрошення в адміністратора."
}
}
diff --git a/apps/web/messages/zh-CN/auth.json b/apps/web/messages/zh-CN/auth.json
index ec5d4f74..e6018626 100644
--- a/apps/web/messages/zh-CN/auth.json
+++ b/apps/web/messages/zh-CN/auth.json
@@ -93,6 +93,8 @@
"userNotFound": "此验证链接对应的账户已不存在。",
"ssoDisabled": "此实例未启用单点登录。",
"passwordDisabled": "此实例仅通过身份提供方登录。",
- "accountDeactivated": "该账号已停用,请联系管理员恢复。"
+ "accountDeactivated": "该账号已停用,请联系管理员恢复。",
+ "registrationClosed": "此实例不接受新账户,请联系管理员申请访问权限。",
+ "inviteOnly": "此实例仅限受邀用户加入,请联系管理员获取邀请。"
}
}
diff --git a/apps/web/src/features/auth/components/login/AuthLoginForm.tsx b/apps/web/src/features/auth/components/login/AuthLoginForm.tsx
index a0bd5dec..3c2eb3f6 100644
--- a/apps/web/src/features/auth/components/login/AuthLoginForm.tsx
+++ b/apps/web/src/features/auth/components/login/AuthLoginForm.tsx
@@ -61,9 +61,9 @@ export default function AuthLoginForm() {
// `apiFailure` in lib/api/core/client.ts sends the browser here with ?expired=1 after the API
// refused the session, so the screen can say why the user is back on it.
const sessionExpired = params.get('expired') === '1';
- // A Google sign-in or a confirmation link that could not complete comes back here
- // as a redirect rather than as a rejected promise, so its reason arrives in the
- // query string.
+ // A Google, OIDC or magic-link sign-in, or a confirmation link, that could not
+ // complete comes back here as a redirect rather than as a rejected promise, so its
+ // reason arrives in the query string.
const redirectErrorMessage = useRedirectError();
const redirectError = redirectErrorMessage(params.get('error'), params.get('error_description'));
// The confirmation link carries ?verified=1 and adds ?error=… when it failed, so
diff --git a/apps/web/src/features/auth/hooks/useAuthAction.ts b/apps/web/src/features/auth/hooks/useAuthAction.ts
index e06e29f4..dc0e40af 100644
--- a/apps/web/src/features/auth/hooks/useAuthAction.ts
+++ b/apps/web/src/features/auth/hooks/useAuthAction.ts
@@ -3,6 +3,7 @@
import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { useTranslations } from 'next-intl';
+import { registrationRefusalKey } from '@/utils/registrationRefusals';
// 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
@@ -12,8 +13,10 @@ import { useTranslations } from 'next-intl';
// 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; `fallback` covers the ones
-// that arrive without one and where the generic wording is too vague.
+// 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.
export function useAuthAction() {
const router = useRouter();
const t = useTranslations('auth.errors');
@@ -36,7 +39,8 @@ export function useAuthAction() {
router.refresh();
} catch (err) {
const message = err instanceof Error ? err.message : '';
- setError(message || options?.fallback || t('generic'));
+ const refusal = registrationRefusalKey((err as { code?: unknown } | null)?.code);
+ setError(refusal ? t(refusal) : message || options?.fallback || t('generic'));
setPending(false);
}
}
diff --git a/apps/web/src/features/auth/hooks/useRedirectError.test.tsx b/apps/web/src/features/auth/hooks/useRedirectError.test.tsx
new file mode 100644
index 00000000..d773540a
--- /dev/null
+++ b/apps/web/src/features/auth/hooks/useRedirectError.test.tsx
@@ -0,0 +1,85 @@
+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 { useRedirectError } from './useRedirectError';
+
+const replacedGlobals = [
+ 'window',
+ 'document',
+ 'navigator',
+ 'HTMLElement',
+ 'IS_REACT_ACT_ENVIRONMENT',
+] as const;
+let dom: JSDOM;
+let root: Root;
+let originalGlobalDescriptors: Map<string, PropertyDescriptor | undefined>;
+
+function Message({ error, description }: { error: string; description: string | null }) {
+ return <p>{useRedirectError()(error, description)}</p>;
+}
+
+function render(error: string, description: string | null = null): string {
+ act(() =>
+ root.render(
+ <NextIntlClientProvider locale="en" messages={{ auth }} timeZone="UTC">
+ <Message error={error} description={description} />
+ </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);
+ }
+});
+
+// The ?error= values are the ones the api's registration-refusal-redirect test pins.
+describe('useRedirectError', () => {
+ it('names a closed registration', () => {
+ assert.equal(render('REGISTRATION_CLOSED'), auth.errors.registrationClosed);
+ });
+
+ // better-auth sends the gate's English message along; the code wins over it.
+ it('names a refusal by its code, not by the description sent with it', () => {
+ assert.equal(
+ render('REGISTRATION_CLOSED', 'Registration is closed on this instance'),
+ auth.errors.registrationClosed,
+ );
+ });
+
+ it('names an invite-only instance', () => {
+ assert.equal(render('INVITE_ONLY'), auth.errors.inviteOnly);
+ });
+
+ it('falls back to the description, then to the generic text, for an unknown error', () => {
+ assert.equal(render('something_else', 'Provider said no'), 'Provider said no');
+ assert.equal(render('something_else'), auth.errors.generic);
+ });
+});
diff --git a/apps/web/src/features/auth/hooks/useRedirectError.ts b/apps/web/src/features/auth/hooks/useRedirectError.ts
index b34210c2..22ad210a 100644
--- a/apps/web/src/features/auth/hooks/useRedirectError.ts
+++ b/apps/web/src/features/auth/hooks/useRedirectError.ts
@@ -1,13 +1,15 @@
'use client';
import { useTranslations } from 'next-intl';
+import { REGISTRATION_REFUSAL_KEYS } from '@/utils/registrationRefusals';
// 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>
// when the instance itself refused — the registration gate passes its own message
-// that way). Three flows land here: the Google round trip, the OIDC one, and the
-// confirmation link from the address verification email. Codes raised by better-auth
-// carry no description, so the ones a visitor can act on are spelled out here.
+// that way). Four flows land here: the Google round trip, the OIDC one, the magic link,
+// and the confirmation link from the address verification email. Codes raised by
+// better-auth carry no description, and the gate's is in English, so the ones a visitor
+// can act on are spelled out here.
//
// Linking a provider account to an account whose email was never confirmed is refused
// unless the instance trusts provider addresses: anyone could have registered that
@@ -25,6 +27,7 @@ const MESSAGE_KEYS = {
TOKEN_EXPIRED: 'tokenExpired',
INVALID_TOKEN: 'invalidToken',
USER_NOT_FOUND: 'userNotFound',
+ ...REGISTRATION_REFUSAL_KEYS,
} as const;
export function useRedirectError() {
diff --git a/apps/web/src/features/auth/services/auth.service.ts b/apps/web/src/features/auth/services/auth.service.ts
index 974593cd..6a1fab26 100644
--- a/apps/web/src/features/auth/services/auth.service.ts
+++ b/apps/web/src/features/auth/services/auth.service.ts
@@ -55,7 +55,10 @@ export async function signUpWithEmail(input: { email: string; password: string }
name: input.email.split('@')[0] || input.email,
callbackURL: appUrl('/login?verified=1'),
});
- if (result.error) throw new Error(result.error.message ?? '');
+ // 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 });
+ }
}
// Sends the password reset link. The address is not confirmed to exist: better-auth
diff --git a/apps/web/src/features/invite/components/InviteAuthForm.tsx b/apps/web/src/features/invite/components/InviteAuthForm.tsx
index cea306a3..1ed12dd7 100644
--- a/apps/web/src/features/invite/components/InviteAuthForm.tsx
+++ b/apps/web/src/features/invite/components/InviteAuthForm.tsx
@@ -7,7 +7,9 @@ import { projectPath, projectRefOf } from '@/utils/paths';
import { Button } from '@/components/ui/button';
import { Field, FieldDescription, FieldError, FieldGroup, FieldLabel } from '@/components/ui/field';
import { Input } from '@/components/ui/input';
+import { registrationRefusalKey } from '@/utils/registrationRefusals';
import {
+ InviteAuthError,
isExistingAccountError,
registerAndAccept,
signInForInvite,
@@ -29,6 +31,7 @@ export default function InviteAuthForm({
hasAccount: boolean;
}) {
const t = useTranslations('invite');
+ const tAuth = useTranslations('auth.errors');
const router = useRouter();
const [mode, setMode] = useState<Mode>(hasAccount ? 'signin' : 'register');
const [password, setPassword] = useState('');
@@ -79,7 +82,10 @@ export default function InviteAuthForm({
switchMode('signin');
setNotice(t('existingAccountNotice'));
} else {
- setError(err instanceof Error ? err.message : t('genericError'));
+ const refusal =
+ err instanceof InviteAuthError ? registrationRefusalKey(err.code) : undefined;
+ if (refusal) setError(tAuth(refusal));
+ else setError(err instanceof Error ? err.message : t('genericError'));
}
setPending(false);
}
diff --git a/apps/web/src/utils/registrationRefusals.test.ts b/apps/web/src/utils/registrationRefusals.test.ts
new file mode 100644
index 00000000..fb4c87ca
--- /dev/null
+++ b/apps/web/src/utils/registrationRefusals.test.ts
@@ -0,0 +1,16 @@
+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');
+ });
+
+ 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.ts
new file mode 100644
index 00000000..ca1cfd8c
--- /dev/null
+++ b/apps/web/src/utils/registrationRefusals.ts
@@ -0,0 +1,15 @@
+// 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',
+} 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;
+}
diff --git a/docs/self-hosting.md b/docs/self-hosting.md
index fa71da46..3a5e2c81 100644
--- a/docs/self-hosting.md
+++ b/docs/self-hosting.md
@@ -88,8 +88,9 @@ The first sign-in creates the account, and the registration mode under **Authent
decides whether it may: `open` creates it, `invite only` needs a pending invite that has
not expired, `closed` refuses it. Invites expire after the days set under **Authentication**
(7 by default, 0 for never); an expired one is renewed from the member list under a new
-link, and a sign-in refused because the invite expired is told so. On a closed instance,
-provision people with SCIM.
+link. A refused sign-in returns to the sign-in page, which says why: the instance is
+closed, it needs an invite, or the invite expired. On a closed instance, provision people
+with SCIM.
A sign-in whose address already has an account joins that account instead of creating a
second one. That needs the provider to report the address as verified and the account to