⭐️⭐️⭐️ Open-source, self-hosted alternative to Linear and Plane. Project management and issue tracking where teams and AI agents work side by side to plan and ship products.
TypeScript agenticagileai-agentsbug-reportingbug-trackerganttissue-trackerjirajira-alternativekanbanlinearlinear-alternativeopen-sourceproduct-managementproject-managementroadmapself-hostedsprint-planningteam-collaborationtrello-alternative
feat: trust addresses from sign-in providers when linking accounts (#342)
Croff0fad29aaf390
diff --git a/apps/api/src/modules/god/__tests__/integration/god-oidc.test.ts b/apps/api/src/modules/god/__tests__/integration/god-oidc.test.tsindex be5535ad..9e46b75d 100644--- a/apps/api/src/modules/god/__tests__/integration/god-oidc.test.ts+++ b/apps/api/src/modules/god/__tests__/integration/god-oidc.test.ts@@ -113,6 +113,24 @@ describe('god OIDC and password settings', () => {});});+ describe('trusting provider emails', () => {+ it('is off by default and round-trips', async () => {+ const { god } = await setup();++ expect((await god.api.god['auth-settings'].get()).data).toMatchObject({+ trustProviderEmails: false,+ });++ const res = await god.api.god['auth-settings'].put({ trustProviderEmails: true });++ expect(res.status).toBe(200);+ expect(res.data).toMatchObject({ trustProviderEmails: true });+ expect((await god.api.god['auth-settings'].get()).data).toMatchObject({+ trustProviderEmails: true,+ });+ });+ });+describe('turning off password sign-in', () => {it('refuses while no single sign-on provider is configured', async () => {const { god } = await setup();diff --git a/apps/api/src/modules/god/model.ts b/apps/api/src/modules/god/model.tsindex 303d9242..d4b46f34 100644--- a/apps/api/src/modules/god/model.ts+++ b/apps/api/src/modules/god/model.ts@@ -34,6 +34,7 @@ export const AuthSettingsResponse = t.Object({requireEmailVerification: t.Boolean(),magicLink: t.Boolean(),emailPassword: t.Boolean(),+ trustProviderEmails: t.Boolean(),// The settings that depend on outbound email cannot be turned on without a mail// provider, and the UI explains why.hasEmailProvider: t.Boolean(),@@ -47,6 +48,7 @@ export const AuthSettingsBody = t.Object({requireEmailVerification: t.Optional(t.Boolean()),magicLink: t.Optional(t.Boolean()),emailPassword: t.Optional(t.Boolean()),+ trustProviderEmails: t.Optional(t.Boolean()),});export const EmailSettingsResponse = t.Object({diff --git a/apps/web/messages/ar/auth.json b/apps/web/messages/ar/auth.jsonindex 24405132..770eea38 100644--- a/apps/web/messages/ar/auth.json+++ b/apps/web/messages/ar/auth.json@@ -83,10 +83,9 @@"generic": "حدث خطأ ما. حاول مرة أخرى.","passkey": "تعذّر تسجيل الدخول عبر passkey. حاول مرة أخرى.","passwordsDoNotMatch": "كلمتا المرور غير متطابقتين.",- "google": "تعذّر تسجيل الدخول عبر Google. حاول مرة أخرى.",- "linkRefused": "البريد ده ليه حساب بالفعل. سجّل دخولك بكلمة مروره وأكّد العنوان الأول، وبعدين تقدر تستخدم Google.",+ "linkRefused": "العنوان ده ليه حساب بالفعل. سجّل دخولك بكلمة مروره وأكّد العنوان، وبعدين حاول تاني.","signupDisabled": "هذه النسخة لا تقبل حسابات جديدة.",- "emailNotFound": "Google مرجّعش عنوان بريد للحساب ده.",+ "emailNotFound": "مزوّد تسجيل الدخول مرجّعش عنوان بريد. اطلب من المسؤول يراجع scopes المزوّد.","tokenExpired": "رابط التأكيد ده انتهت صلاحيته. سجّل دخولك من تحت عشان يوصلك رابط جديد.","invalidToken": "رابط التأكيد ده مش صالح. سجّل دخولك من تحت عشان يوصلك رابط جديد.","userNotFound": "رابط التأكيد ده بتاع حساب مبقاش موجود.",diff --git a/apps/web/messages/ar/god.json b/apps/web/messages/ar/god.jsonindex 32a0aea1..b6768fd1 100644--- a/apps/web/messages/ar/god.json+++ b/apps/web/messages/ar/god.json@@ -137,6 +137,8 @@"requireVerificationHint": "الحساب الجديد لازم يأكّد عنوان بريده الأول عشان يقدر يسجّل دخول.","magicLink": "روابط تسجيل الدخول","magicLinkHint": "تدّي الناس خيار إنها تسجّل دخول برابط بيوصل على البريد، جنب كلمة المرور.",+ "trustProviderEmails": "ثق في العناوين من مزوّدي تسجيل الدخول",+ "trustProviderEmailsHint": "Google و OpenID Connect بيدخّلوا الشخص على الحساب اللي فيه عنوانه بالفعل، سواء اتأكد هنا أو لأ. شغّله بس لو إنت اللي بتقرّر مين يقدر يسجّل عند المزوّد.","emailPassword": "البريد وكلمة المرور","emailPasswordHint": "إظهار نموذج تسجيل الدخول والتسجيل. عطّله ليتم الدخول عبر مزوّد تسجيل الدخول فقط.","needsSso": "اضبط مزوّد تسجيل دخول من قسم التكاملات أولاً."diff --git a/apps/web/messages/en/auth.json b/apps/web/messages/en/auth.jsonindex ab0e115b..2d176e06 100644--- a/apps/web/messages/en/auth.json+++ b/apps/web/messages/en/auth.json@@ -83,10 +83,9 @@"generic": "Something went wrong. Please try again.","passkey": "Could not sign in with your passkey. Please try again.","passwordsDoNotMatch": "Passwords do not match.",- "google": "Could not sign in with Google. Please try again.",- "linkRefused": "This email already has an account. Sign in with its password and confirm the address first, then Google can be used.",+ "linkRefused": "This email address already has an account. Sign in with its password and confirm the address, then try again.","signupDisabled": "This instance is not accepting new accounts.",- "emailNotFound": "Google did not return an email address for this account.",+ "emailNotFound": "The sign-in provider did not return an email address. Ask your administrator to check the provider's scopes.","tokenExpired": "This confirmation link has expired. Sign in below to get a new one.","invalidToken": "This confirmation link is not valid. Sign in below to get a new one.","userNotFound": "This confirmation link belongs to an account that no longer exists.",diff --git a/apps/web/messages/en/god.json b/apps/web/messages/en/god.jsonindex f7e10de4..54b29cd1 100644--- a/apps/web/messages/en/god.json+++ b/apps/web/messages/en/god.json@@ -137,6 +137,8 @@"requireVerificationHint": "A new account must confirm its address before it can sign in.","magicLink": "Sign-in links","magicLinkHint": "Offer signing in with a link sent by email, alongside the password.",+ "trustProviderEmails": "Trust addresses from sign-in providers",+ "trustProviderEmailsHint": "Google and OpenID Connect sign a person in to the account that already has their address, confirmed here or not. Turn this on only where you control who can register at the provider.","emailPassword": "Email and password","emailPasswordHint": "Offer the sign-in and sign-up form. Turn it off to let people in through a sign-in provider only.","needsSso": "Set up a sign-in provider under Integrations first."diff --git a/apps/web/messages/fr/auth.json b/apps/web/messages/fr/auth.jsonindex 65479144..0c39bbbe 100644--- a/apps/web/messages/fr/auth.json+++ b/apps/web/messages/fr/auth.json@@ -83,10 +83,9 @@"generic": "Une erreur est survenue. Veuillez réessayer.","passkey": "Impossible de vous connecter avec votre clé d'accès. Veuillez réessayer.","passwordsDoNotMatch": "Les mots de passe ne correspondent pas.",- "google": "Impossible de vous connecter avec Google. Veuillez réessayer.",- "linkRefused": "Un compte existe déjà pour cette adresse. Connectez-vous avec son mot de passe et confirmez l'adresse, puis vous pourrez utiliser Google.",+ "linkRefused": "Cette adresse e-mail a déjà un compte. Connectez-vous avec son mot de passe, confirmez l'adresse, puis réessayez.","signupDisabled": "Cette instance n'accepte pas de nouveaux comptes.",- "emailNotFound": "Google n'a pas renvoyé d'adresse e-mail pour ce compte.",+ "emailNotFound": "Le fournisseur de connexion n'a pas renvoyé d'adresse e-mail. Demandez à votre administrateur de vérifier les scopes du fournisseur.","tokenExpired": "Ce lien de confirmation a expiré. Connectez-vous ci-dessous pour en recevoir un nouveau.","invalidToken": "Ce lien de confirmation n'est pas valide. Connectez-vous ci-dessous pour en recevoir un nouveau.","userNotFound": "Ce lien de confirmation appartient à un compte qui n'existe plus.",diff --git a/apps/web/messages/fr/god.json b/apps/web/messages/fr/god.jsonindex 50d7010f..ffa2c8a9 100644--- a/apps/web/messages/fr/god.json+++ b/apps/web/messages/fr/god.json@@ -137,6 +137,8 @@"requireVerificationHint": "Un nouveau compte doit confirmer son adresse avant de pouvoir se connecter.","magicLink": "Liens de connexion","magicLinkHint": "Proposer la connexion par lien envoyé par e-mail, en plus du mot de passe.",+ "trustProviderEmails": "Faire confiance aux adresses des fournisseurs de connexion",+ "trustProviderEmailsHint": "Google et OpenID Connect connectent la personne au compte qui porte déjà son adresse, que cette adresse soit confirmée ici ou non. À activer seulement si vous décidez qui peut s'inscrire chez le fournisseur.","emailPassword": "E-mail et mot de passe","emailPasswordHint": "Proposer le formulaire de connexion et d'inscription. Désactivez-le pour n'autoriser l'accès que via un fournisseur de connexion.","needsSso": "Configurez d'abord un fournisseur de connexion dans Intégrations."diff --git a/apps/web/messages/pt-BR/auth.json b/apps/web/messages/pt-BR/auth.jsonindex 5f53ef09..7c0b547b 100644--- a/apps/web/messages/pt-BR/auth.json+++ b/apps/web/messages/pt-BR/auth.json@@ -83,10 +83,9 @@"generic": "Algo deu errado. Tente novamente.","passkey": "Não foi possível entrar com sua chave de acesso. Tente novamente.","passwordsDoNotMatch": "As senhas não coincidem.",- "google": "Não foi possível entrar com o Google. Tente novamente.",- "linkRefused": "Este e-mail já tem uma conta. Entre com sua senha e confirme o endereço primeiro; depois o Google pode ser usado.",+ "linkRefused": "Este endereço de e-mail já tem uma conta. Entre com a senha dela, confirme o endereço e tente de novo.","signupDisabled": "Esta instância não está aceitando novas contas.",- "emailNotFound": "O Google não retornou um endereço de e-mail para esta conta.",+ "emailNotFound": "O provedor de login não retornou um endereço de e-mail. Peça ao administrador para verificar os scopes do provedor.","tokenExpired": "Este link de confirmação expirou. Entre abaixo para obter um novo.","invalidToken": "Este link de confirmação não é válido. Entre abaixo para obter um novo.","userNotFound": "Este link de confirmação pertence a uma conta que não existe mais.",diff --git a/apps/web/messages/pt-BR/god.json b/apps/web/messages/pt-BR/god.jsonindex 5f21c26c..b3ed08c4 100644--- a/apps/web/messages/pt-BR/god.json+++ b/apps/web/messages/pt-BR/god.json@@ -137,6 +137,8 @@"requireVerificationHint": "Uma nova conta deve confirmar seu endereço antes de poder entrar.","magicLink": "Links de login","magicLinkHint": "Oferecer login com um link enviado por e-mail, junto com a senha.",+ "trustProviderEmails": "Confiar nos endereços dos provedores de login",+ "trustProviderEmailsHint": "O Google e o OpenID Connect entram na conta que já tem o endereço da pessoa, confirmado aqui ou não. Ative apenas se você decide quem pode se registrar no provedor.","emailPassword": "E-mail e senha","emailPasswordHint": "Oferecer o formulário de login e registro. Desative para deixar as pessoas entrarem apenas por um provedor de login.","needsSso": "Configure um provedor de login em Integrações primeiro."diff --git a/apps/web/messages/ru/auth.json b/apps/web/messages/ru/auth.jsonindex c985fd18..979e5878 100644--- a/apps/web/messages/ru/auth.json+++ b/apps/web/messages/ru/auth.json@@ -83,10 +83,9 @@"generic": "Что-то пошло не так. Попробуйте ещё раз.","passkey": "Не удалось войти по passkey. Попробуйте ещё раз.","passwordsDoNotMatch": "Пароли не совпадают.",- "google": "Не удалось войти через Google. Попробуйте ещё раз.",- "linkRefused": "Для этой почты уже есть аккаунт. Войдите с его паролем и подтвердите адрес — после этого можно будет пользоваться Google.",+ "linkRefused": "Для этого адреса уже есть аккаунт. Войдите с его паролем, подтвердите адрес и попробуйте снова.","signupDisabled": "Этот инстанс не принимает новые аккаунты.",- "emailNotFound": "Google не вернул адрес почты для этого аккаунта.",+ "emailNotFound": "Поставщик входа не вернул адрес почты. Попросите администратора проверить scopes поставщика.","tokenExpired": "Срок действия ссылки для подтверждения истёк. Войдите ниже, чтобы получить новую.","invalidToken": "Ссылка для подтверждения недействительна. Войдите ниже, чтобы получить новую.","userNotFound": "Ссылка для подтверждения принадлежит аккаунту, которого больше не существует.",diff --git a/apps/web/messages/ru/god.json b/apps/web/messages/ru/god.jsonindex 3b4b2d1e..6d61c5dc 100644--- a/apps/web/messages/ru/god.json+++ b/apps/web/messages/ru/god.json@@ -137,6 +137,8 @@"requireVerificationHint": "Новый аккаунт должен подтвердить адрес, прежде чем сможет войти.","magicLink": "Ссылки для входа","magicLinkHint": "Предлагать вход по ссылке из письма, наряду с паролем.",+ "trustProviderEmails": "Доверять адресам от поставщиков входа",+ "trustProviderEmailsHint": "Google и OpenID Connect впускают человека в аккаунт, у которого уже есть его адрес, подтверждён он здесь или нет. Включайте, только если вы решаете, кто может зарегистрироваться у поставщика.","emailPassword": "Почта и пароль","emailPasswordHint": "Показывать форму входа и регистрации. Отключите, чтобы вход выполнялся только через поставщика.","needsSso": "Сначала настройте поставщика входа в разделе «Интеграции»."diff --git a/apps/web/messages/uk/auth.json b/apps/web/messages/uk/auth.jsonindex ff35f047..4aa99ec4 100644--- a/apps/web/messages/uk/auth.json+++ b/apps/web/messages/uk/auth.json@@ -83,10 +83,9 @@"generic": "Щось пішло не так. Спробуйте ще раз.","passkey": "Не вдалося увійти за passkey. Спробуйте ще раз.","passwordsDoNotMatch": "Паролі не збігаються.",- "google": "Не вдалося увійти через Google. Спробуйте ще раз.",- "linkRefused": "Для цієї пошти вже є акаунт. Увійдіть із його паролем і підтвердіть адресу — після цього можна буде користуватися Google.",+ "linkRefused": "Для цієї адреси вже є акаунт. Увійдіть із його паролем, підтвердіть адресу і спробуйте ще раз.","signupDisabled": "Цей інстанс не приймає нових акаунтів.",- "emailNotFound": "Google не повернув адресу пошти для цього акаунта.",+ "emailNotFound": "Постачальник входу не повернув адресу пошти. Попросіть адміністратора перевірити scopes постачальника.","tokenExpired": "Термін дії посилання для підтвердження минув. Увійдіть нижче, щоб отримати нове.","invalidToken": "Посилання для підтвердження недійсне. Увійдіть нижче, щоб отримати нове.","userNotFound": "Посилання для підтвердження належить акаунту, якого більше не існує.",diff --git a/apps/web/messages/uk/god.json b/apps/web/messages/uk/god.jsonindex 5fd86433..6dd9f603 100644--- a/apps/web/messages/uk/god.json+++ b/apps/web/messages/uk/god.json@@ -137,6 +137,8 @@"requireVerificationHint": "Новий акаунт має підтвердити адресу, перш ніж зможе увійти.","magicLink": "Посилання для входу","magicLinkHint": "Пропонувати вхід за посиланням із листа, поряд із паролем.",+ "trustProviderEmails": "Довіряти адресам від постачальників входу",+ "trustProviderEmailsHint": "Google і OpenID Connect впускають людину в акаунт, у якого вже є її адреса, підтверджена вона тут чи ні. Вмикайте, лише якщо ви вирішуєте, хто може зареєструватися в постачальника.","emailPassword": "Пошта і пароль","emailPasswordHint": "Показувати форму входу та реєстрації. Вимкніть, щоб вхід виконувався лише через постачальника.","needsSso": "Спочатку налаштуйте постачальника входу в розділі «Інтеграції»."diff --git a/apps/web/messages/zh-CN/auth.json b/apps/web/messages/zh-CN/auth.jsonindex d6b77eb7..e43fdf25 100644--- a/apps/web/messages/zh-CN/auth.json+++ b/apps/web/messages/zh-CN/auth.json@@ -83,10 +83,9 @@"generic": "出现错误,请重试。","passkey": "无法使用通行密钥登录,请重试。","passwordsDoNotMatch": "两次输入的密码不一致。",- "google": "无法使用 Google 登录,请重试。",- "linkRefused": "此邮箱已有账户。请先使用密码登录并验证邮箱,然后再使用 Google。",+ "linkRefused": "此邮箱地址已有账户。请用它的密码登录并验证邮箱,然后重试。","signupDisabled": "此实例不接受新账户注册。",- "emailNotFound": "Google 未返回此账户的邮箱地址。",+ "emailNotFound": "登录提供方没有返回邮箱地址。请让管理员检查提供方的 scopes。","tokenExpired": "此验证链接已过期。请在下方登录以获取新链接。","invalidToken": "此验证链接无效。请在下方登录以获取新链接。","userNotFound": "此验证链接对应的账户已不存在。",diff --git a/apps/web/messages/zh-CN/god.json b/apps/web/messages/zh-CN/god.jsonindex 5b33d98e..529477d1 100644--- a/apps/web/messages/zh-CN/god.json+++ b/apps/web/messages/zh-CN/god.json@@ -137,6 +137,8 @@"requireVerificationHint": "新账户必须验证邮箱后才能登录。","magicLink": "邮箱登录链接","magicLinkHint": "通过邮件发送免密码登录链接。",+ "trustProviderEmails": "信任登录提供方的邮箱地址",+ "trustProviderEmailsHint": "通过 Google 或 OpenID Connect 登录时,直接进入已使用该邮箱地址的账户,无论该地址是否在此验证过。仅当由你决定谁能在提供方注册时才开启。","emailPassword": "邮箱和密码","emailPasswordHint": "提供登录和注册表单。关闭后只能通过登录提供方进入。","needsSso": "请先在「集成」中配置登录提供方。"diff --git a/apps/web/package.json b/apps/web/package.jsonindex b1de9d61..2efabfce 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -53,7 +53,7 @@"@tiptap/suggestion": "^3.30.0","@uiw/react-color": "^2.10.3","@xyflow/react": "^12.11.3",- "better-auth": "^1.6.27",+ "better-auth": "1.6.27","class-variance-authority": "^0.7.1","cmdk": "^1.1.1","cn": "^0.2.5",diff --git a/apps/web/src/app/globals.css b/apps/web/src/app/globals.cssindex b25de96a..dc14360a 100644--- a/apps/web/src/app/globals.css+++ b/apps/web/src/app/globals.css@@ -210,6 +210,14 @@pointer-events: none;}+/* An alert states its kind by colour, and every place one appears already sits+ inside a bordered surface. The generated component carries an unconditional+ `border`, which reads as a box drawn inside a box. A caller that wants one back+ sets both the width and the colour. */+[data-slot='alert'] {+ border-width: 0;+}+/* Dialogs and sheets cover a far larger area, so they carry a wider, deeper castthan a menu. */[data-slot='dialog-content'],diff --git a/apps/web/src/components/common/page/SettingsRow.tsx b/apps/web/src/components/common/page/SettingsRow.tsxindex 9306a675..78a25c1a 100644--- a/apps/web/src/components/common/page/SettingsRow.tsx+++ b/apps/web/src/components/common/page/SettingsRow.tsx@@ -1,8 +1,11 @@import type { ReactNode } from 'react';+import { Info } from 'lucide-react';+import { Alert, AlertDescription } from '@/components/ui/alert';// One row inside a settings group: name and description on the left, the control-// (usually a switch) on the right. `note` adds a second line, for what has to be-// done before the control applies. The dividers come from the card.+// (usually a switch) on the right. `note` is what has to be done before the control+// applies, set apart from the description so the reason a switch cannot be moved is+// not read as more of its explanation. The dividers come from the card.export default function SettingsRow({title,description,@@ -16,10 +19,15 @@ export default function SettingsRow({}) {return (<div className="flex items-center justify-between gap-6 p-4">- <div className="space-y-0.5">+ <div className="max-w-2xl space-y-1"><div className="text-sm font-medium">{title}</div><p className="text-xs text-muted-foreground">{description}</p>- {note && <p className="text-xs text-muted-foreground">{note}</p>}+ {note && (+ <Alert className="mt-2 w-fit bg-amber-500/10 px-3 py-2 text-amber-700 dark:text-amber-300">+ <Info />+ <AlertDescription className="text-xs text-current">{note}</AlertDescription>+ </Alert>+ )}</div>{control}</div>diff --git a/apps/web/src/components/ui/alert.tsx b/apps/web/src/components/ui/alert.tsxnew file mode 100644index 00000000..1ccb01fd--- /dev/null+++ b/apps/web/src/components/ui/alert.tsx@@ -0,0 +1,59 @@+import * as React from 'react';+import { cva, type VariantProps } from 'class-variance-authority';+import { cn } from '@/lib/utils';++const alertVariants = cva(+ 'relative grid w-full grid-cols-[0_1fr] items-start gap-y-0.5 rounded-lg border px-4 py-3 text-sm has-[>svg]:grid-cols-[calc(var(--spacing)*4)_1fr] has-[>svg]:gap-x-3 [&>svg]:size-4 [&>svg]:translate-y-0.5 [&>svg]:text-current',+ {+ variants: {+ variant: {+ default: 'bg-card text-card-foreground',+ destructive:+ 'bg-card text-destructive *:data-[slot=alert-description]:text-destructive/90 [&>svg]:text-current',+ },+ },+ defaultVariants: {+ variant: 'default',+ },+ },+);++function Alert({+ className,+ variant,+ ...props+}: React.ComponentProps<'div'> & VariantProps<typeof alertVariants>) {+ return (+ <div+ data-slot="alert"+ role="alert"+ className={cn(alertVariants({ variant }), className)}+ {...props}+ />+ );+}++function AlertTitle({ className, ...props }: React.ComponentProps<'div'>) {+ return (+ <div+ data-slot="alert-title"+ className={cn('col-start-2 line-clamp-1 min-h-4 font-medium tracking-tight', className)}+ {...props}+ />+ );+}++function AlertDescription({ className, ...props }: React.ComponentProps<'div'>) {+ return (+ <div+ data-slot="alert-description"+ className={cn(+ 'col-start-2 grid justify-items-start gap-1 text-sm text-muted-foreground [&_p]:leading-relaxed',+ className,+ )}+ {...props}+ />+ );+}++export { Alert, AlertTitle, AlertDescription };diff --git a/apps/web/src/features/auth/hooks/useRedirectError.ts b/apps/web/src/features/auth/hooks/useRedirectError.tsindex d755511e..46a11e93 100644--- a/apps/web/src/features/auth/hooks/useRedirectError.ts+++ b/apps/web/src/features/auth/hooks/useRedirectError.ts@@ -5,13 +5,13 @@ import { useTranslations } from 'next-intl';// 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). Two flows land here: the Google round trip, 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). 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.//-// Linking a social account to an account whose email was never confirmed is refused-// on purpose: anyone could have registered that address with a password before its-// owner arrived.+// 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+// address with a password before its owner arrived.const MESSAGE_KEYS = {unable_to_link_account: 'linkRefused',account_not_linked: 'linkRefused',@@ -36,6 +36,6 @@ export function useRedirectError() {if (!error) return null;const key = MESSAGE_KEYS[error as keyof typeof MESSAGE_KEYS];if (key) return t(key);- return description ?? t('google');+ return description ?? t('generic');};}diff --git a/apps/web/src/features/god/components/authentication/GodAuthenticationForm.tsx b/apps/web/src/features/god/components/authentication/GodAuthenticationForm.tsxindex 3fcf40b1..8ea14140 100644--- a/apps/web/src/features/god/components/authentication/GodAuthenticationForm.tsx+++ b/apps/web/src/features/god/components/authentication/GodAuthenticationForm.tsx@@ -97,6 +97,18 @@ export default function GodAuthenticationForm({/>}/>+ <SettingsRow+ title={t('trustProviderEmails')}+ description={t('trustProviderEmailsHint')}+ note={needsSso ? t('needsSso') : undefined}+ control={+ <Switch+ checked={policy.trustProviderEmails}+ disabled={policy.saving || needsSso}+ onCheckedChange={policy.setTrustProviderEmails}+ />+ }+ /></SettingsCard></SettingsSection></div>diff --git a/apps/web/src/features/god/hooks/useGodPolicyForm.ts b/apps/web/src/features/god/hooks/useGodPolicyForm.tsindex 40447d96..e814892a 100644--- a/apps/web/src/features/god/hooks/useGodPolicyForm.ts+++ b/apps/web/src/features/god/hooks/useGodPolicyForm.ts@@ -13,15 +13,15 @@ export interface GodPolicyForm {setMagicLink: (v: boolean) => void;emailPassword: boolean;setEmailPassword: (v: boolean) => void;+ trustProviderEmails: boolean;+ setTrustProviderEmails: (v: boolean) => void;dirty: boolean;saving: boolean;save: () => Promise<void>;}-// Form state for the instance sign-in policy: who may register, whether the-// email/password form is offered at all, and the two options that need outbound-// mail. Held here rather than saved on change so the whole page commits through one-// Save.+// Held in local state rather than saved on change, so the whole page commits through+// one Save.export function useGodPolicyForm(settings: InstanceAuthSettings): GodPolicyForm {const update = useUpdateInstanceAuthSettings();@@ -31,15 +31,23 @@ export function useGodPolicyForm(settings: InstanceAuthSettings): GodPolicyForm);const [magicLink, setMagicLink] = useState(settings.magicLink);const [emailPassword, setEmailPassword] = useState(settings.emailPassword);+ const [trustProviderEmails, setTrustProviderEmails] = useState(settings.trustProviderEmails);const dirty =registration !== settings.registration ||requireEmailVerification !== settings.requireEmailVerification ||magicLink !== settings.magicLink ||- emailPassword !== settings.emailPassword;+ emailPassword !== settings.emailPassword ||+ trustProviderEmails !== settings.trustProviderEmails;async function save() {- await update.mutateAsync({ registration, requireEmailVerification, magicLink, emailPassword });+ await update.mutateAsync({+ registration,+ requireEmailVerification,+ magicLink,+ emailPassword,+ trustProviderEmails,+ });}return {@@ -51,6 +59,8 @@ export function useGodPolicyForm(settings: InstanceAuthSettings): GodPolicyFormsetMagicLink,emailPassword,setEmailPassword,+ trustProviderEmails,+ setTrustProviderEmails,dirty,saving: update.isPending,save,diff --git a/apps/web/src/lib/api/endpoints/god.ts b/apps/web/src/lib/api/endpoints/god.tsindex 141d81f2..d5fbd2f5 100644--- a/apps/web/src/lib/api/endpoints/god.ts+++ b/apps/web/src/lib/api/endpoints/god.ts@@ -20,6 +20,7 @@ export interface InstanceAuthSettings {requireEmailVerification: boolean;magicLink: boolean;emailPassword: boolean;+ trustProviderEmails: boolean;hasEmailProvider: boolean;// Whether Google or the OIDC provider can run. Password sign-in may only be turned// off while one of them can.@@ -31,6 +32,7 @@ export interface InstanceAuthSettingsPatch {requireEmailVerification?: boolean;magicLink?: boolean;emailPassword?: boolean;+ trustProviderEmails?: boolean;}// The instance mail provider used for authentication email (password reset, addressdiff --git a/bun.lock b/bun.lockindex 6f30e898..a26ca101 100644--- a/bun.lock+++ b/bun.lock@@ -108,7 +108,7 @@"@tiptap/suggestion": "^3.30.0","@uiw/react-color": "^2.10.3","@xyflow/react": "^12.11.3",- "better-auth": "^1.6.27",+ "better-auth": "1.6.27","class-variance-authority": "^0.7.1","cmdk": "^1.1.1","cn": "^0.2.5",@@ -186,7 +186,7 @@"@repo/crypto": "workspace:*","@repo/db": "workspace:*","@repo/mailer": "workspace:*",- "better-auth": "^1.6.27",+ "better-auth": "1.6.27","drizzle-orm": "^0.45.2",},"devDependencies": {@@ -1180,7 +1180,7 @@"@turbo/windows-arm64": ["@turbo/[email protected]", "", { "os": "win32", "cpu": "arm64" }, "sha512-W2Ub165Qv0iMFljbYKxxbZN+2dVSngnzEjQNEFXtnz5oJVx9XSypmNmUvMtuYMeZ3kdVC1zI7yd/rtuX+SDnbg=="],- "@types/bun": ["@types/[email protected]", "", { "dependencies": { "bun-types": "1.4.1" } }, "sha512-0AVGiTXGajf1rgKom3N+c5L7CBxuoyyv1i44M0nX4UDK0G/fnRAMiri93nHuVPIb429KKtAgj7HatVmmOjeQLA=="],+ "@types/bun": ["@types/[email protected]", "", { "dependencies": { "bun-types": "1.4.2" } }, "sha512-GimotNn7+ZV0uVArItBbriZsR1oNf0+WTzPkdcFrzShI7k2norL0uzEaJT8T33dWr7O/c9ZDuAFQrctKCi72oQ=="],"@types/d3-array": ["@types/[email protected]", "", {}, "sha512-hOLWVbm7uRza0BYXpIIW5pxfrKe0W+D5lrFiAEYR+pb6w3N2SwSMaJbXdUfSEv+dT4MfHBLtn5js0LAWaO6otw=="],@@ -1448,7 +1448,7 @@"buffers": ["[email protected]", "", {}, "sha512-9q/rDEGSb/Qsvv2qvzIzdluL5k7AaJOTrw23z9reQthrbF7is4CtlT0DXyO1oei2DCp4uojjzQ7igaSHp1kAEQ=="],- "bun-types": ["[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-loKuVrAFZKfEv+JvWkHRS9GW5IqLuLRjVXN9p+vZvBN86O5hf/pBZQ5hSoyipsrMmWObZBDvWnlmKvjKTM0PdA=="],+ "bun-types": ["[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-bxV1FgK7yBIzjRe5zBozIM4Bem11ZJcCXSrjWRG3YWLt8yFDePu4cLjpebO8OvPeIE9trbyPF4fuj3Cia4Fj3w=="],"bytes": ["[email protected]", "", {}, "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg=="],@@ -2962,6 +2962,10 @@"@reduxjs/toolkit/reselect": ["[email protected]", "", {}, "sha512-K/BG6eIky/SBpzfHZv/dd+9JBFiS4SWV7FIujVyJRux6e45+73RaUHXLmIR1f7WOMaQ0U1km6qwklRQxpJJY0w=="],+ "@repo/agent-tools/@types/bun": ["@types/[email protected]", "", { "dependencies": { "bun-types": "1.4.1" } }, "sha512-0AVGiTXGajf1rgKom3N+c5L7CBxuoyyv1i44M0nX4UDK0G/fnRAMiri93nHuVPIb429KKtAgj7HatVmmOjeQLA=="],++ "@repo/net/@types/bun": ["@types/[email protected]", "", { "dependencies": { "bun-types": "1.4.1" } }, "sha512-0AVGiTXGajf1rgKom3N+c5L7CBxuoyyv1i44M0nX4UDK0G/fnRAMiri93nHuVPIb429KKtAgj7HatVmmOjeQLA=="],+"@scalar/agent-chat/@scalar/helpers": ["@scalar/[email protected]", "", {}, "sha512-IAfnpIZnXY6ni+zyFMwWHBa5b/7yr4mCSvoTGR84oS9q4Quy2wjgafnr7CyfL65ney3iilBZHigZYLYqdqCu3Q=="],"@scalar/api-client/@scalar/helpers": ["@scalar/[email protected]", "", {}, "sha512-IAfnpIZnXY6ni+zyFMwWHBa5b/7yr4mCSvoTGR84oS9q4Quy2wjgafnr7CyfL65ney3iilBZHigZYLYqdqCu3Q=="],@@ -3048,6 +3052,8 @@"ajv-formats/ajv": ["[email protected]", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA=="],+ "api/@types/bun": ["@types/[email protected]", "", { "dependencies": { "bun-types": "1.4.1" } }, "sha512-0AVGiTXGajf1rgKom3N+c5L7CBxuoyyv1i44M0nX4UDK0G/fnRAMiri93nHuVPIb429KKtAgj7HatVmmOjeQLA=="],+"archiver-utils/readable-stream": ["[email protected]", "", { "dependencies": { "core-util-is": "~1.0.0", "inherits": "~2.0.3", "isarray": "~1.0.0", "process-nextick-args": "~2.0.0", "safe-buffer": "~5.1.1", "string_decoder": "~1.1.1", "util-deprecate": "~1.0.1" } }, "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA=="],"better-call/@better-auth/utils": ["@better-auth/[email protected]", "", { "dependencies": { "@noble/hashes": "^2.0.1" } }, "sha512-BL8W4EfIZFwlu0r54m3v1ztjDhu6dDe/amLTm0xybmbZaNgYUqhD3SjpAsnq0q8YD6/ki4iwIgxJNLP/N3TxiA=="],@@ -3156,6 +3162,8 @@"which-builtin-type/isarray": ["[email protected]", "", {}, "sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw=="],+ "worker/@types/bun": ["@types/[email protected]", "", { "dependencies": { "bun-types": "1.4.1" } }, "sha512-0AVGiTXGajf1rgKom3N+c5L7CBxuoyyv1i44M0nX4UDK0G/fnRAMiri93nHuVPIb429KKtAgj7HatVmmOjeQLA=="],+"zip-stream/archiver-utils": ["[email protected]", "", { "dependencies": { "glob": "^7.2.3", "graceful-fs": "^4.2.0", "lazystream": "^1.0.0", "lodash.defaults": "^4.2.0", "lodash.difference": "^4.5.0", "lodash.flatten": "^4.4.0", "lodash.isplainobject": "^4.0.6", "lodash.union": "^4.6.0", "normalize-path": "^3.0.0", "readable-stream": "^3.6.0" } }, "sha512-KVgf4XQVrTjhyWmx6cte4RxonPLR9onExufI1jhvw/MQ4BB6IsZD5gT8Lq+u/+pRkWna/6JoHpiQioaqFP5Rzw=="],"@ai-sdk/vue/@ai-sdk/provider-utils/@ai-sdk/provider": ["@ai-sdk/[email protected]", "", { "dependencies": { "json-schema": "^0.4.0" } }, "sha512-HrEmNt/BH/hkQ7zpi2o6N3k1ZR1QTb7z85WYhYygiTxOQuaml4CMtHCWRbric5WPU+RNsYI7r1EpyVQMKO1pYw=="],@@ -3210,6 +3218,10 @@"@modelcontextprotocol/sdk/ajv/json-schema-traverse": ["[email protected]", "", {}, "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug=="],+ "@repo/agent-tools/@types/bun/bun-types": ["[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-loKuVrAFZKfEv+JvWkHRS9GW5IqLuLRjVXN9p+vZvBN86O5hf/pBZQ5hSoyipsrMmWObZBDvWnlmKvjKTM0PdA=="],++ "@repo/net/@types/bun/bun-types": ["[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-loKuVrAFZKfEv+JvWkHRS9GW5IqLuLRjVXN9p+vZvBN86O5hf/pBZQ5hSoyipsrMmWObZBDvWnlmKvjKTM0PdA=="],+"@scalar/icons/@types/node/undici-types": ["[email protected]", "", {}, "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w=="],"@types/nodemailer/@types/node/undici-types": ["[email protected]", "", {}, "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w=="],@@ -3222,6 +3234,8 @@"ajv-formats/ajv/json-schema-traverse": ["[email protected]", "", {}, "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug=="],+ "api/@types/bun/bun-types": ["[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-loKuVrAFZKfEv+JvWkHRS9GW5IqLuLRjVXN9p+vZvBN86O5hf/pBZQ5hSoyipsrMmWObZBDvWnlmKvjKTM0PdA=="],+"archiver-utils/readable-stream/string_decoder": ["[email protected]", "", { "dependencies": { "safe-buffer": "~5.1.0" } }, "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg=="],"bot/@types/bun/bun-types": ["[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-4N0ig0fEomHt5R0KCFWjovxow98rIoRwKolrYdCcknNwMekCXRnWEUvgu5soYV8QXtVsrUD8B95MBOZGPvr6KQ=="],@@ -3354,6 +3368,8 @@"unzipper/readable-stream/string_decoder": ["[email protected]", "", { "dependencies": { "safe-buffer": "~5.1.0" } }, "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg=="],+ "worker/@types/bun/bun-types": ["[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-loKuVrAFZKfEv+JvWkHRS9GW5IqLuLRjVXN9p+vZvBN86O5hf/pBZQ5hSoyipsrMmWObZBDvWnlmKvjKTM0PdA=="],+"@itsaplan/runner/@types/bun/bun-types/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-EANqOCF9QFyra+4pfxUcX9STKJpCLjMbObVzljIJomAWSnuSIEAvyzEU53GaajbXJEgdh0iEcPL+DGvpUd4k1Q=="],"@typescript-eslint/typescript-estree/minimatch/brace-expansion/balanced-match": ["[email protected]", "", {}, "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA=="],diff --git a/docs/self-hosting.md b/docs/self-hosting.mdindex e2c77570..ccfa1cd8 100644--- a/docs/self-hosting.md+++ b/docs/self-hosting.md@@ -51,6 +51,14 @@ The first sign-in creates the account, and the registration mode under **Authentdecides whether it may: `open` creates it, `invite only` needs a pending project invite,`closed` refuses it. 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+have confirmed its own, so it is refused when the OIDC client leaves `email_verified` off+the token, or when the instance has no mail provider and so no confirmed accounts.+**Authentication → Trust addresses from sign-in providers** drops both conditions. Turn it+on only where you control who can register at the provider: anyone who registers an address+there takes over the account that holds it here.+Once a provider works, you can turn off **Authentication → Email and password**. The sign-inand sign-up forms, password reset and sign-in links are then hidden and refused, and theprovider is the only way in. Passkeys keep working, because a passkey can only be added to andiff --git a/packages/auth/package.json b/packages/auth/package.jsonindex cdad7db9..af72b3a2 100644--- a/packages/auth/package.json+++ b/packages/auth/package.json@@ -7,7 +7,7 @@".": "./src/index.ts"},"scripts": {- "auth:generate": "dotenv -e ../../.env -- bunx @better-auth/cli generate --config ./src/index.ts --output ../db/src/schema/auth.ts --yes",+ "auth:generate": "dotenv -e ../../.env -- bunx @better-auth/[email protected] generate --config ./src/index.ts --output ../db/src/schema/auth.ts --yes","lint": "eslint .","typecheck": "tsc --noEmit"},@@ -17,7 +17,7 @@"@repo/crypto": "workspace:*","@repo/db": "workspace:*","@repo/mailer": "workspace:*",- "better-auth": "^1.6.27",+ "better-auth": "1.6.27","drizzle-orm": "^0.45.2"},"devDependencies": {diff --git a/packages/auth/src/index.ts b/packages/auth/src/index.tsindex 16e90383..c759c92d 100644--- a/packages/auth/src/index.ts+++ b/packages/auth/src/index.ts@@ -138,6 +138,22 @@ async function refreshOidcOptions(): Promise<boolean> {}}+// The two conditions better-auth checks before linking an address to an account that+// already has it are read from different places: `trustedProviders` per request,+// through the resolver below, and `requireLocalEmailVerified` off the options object+// at the moment of the decision. The resolver runs first, in the same request, and+// leaves the setting here for the getter to read.+let trustProviderEmails = false;++// The trusted providers for one request. The settings are read on the OAuth callback+// only — the resolver runs on every request to the auth API, and a session check has+// no linking decision to make.+async function resolveTrustedProviders(request?: Request): Promise<string[]> {+ if (!request || !new URL(request.url).pathname.includes('/callback/')) return [];+ trustProviderEmails = (await getAuthSettings()).trustProviderEmails;+ return trustProviderEmails ? ['google', OIDC_PROVIDER_ID] : [];+}+// The endpoints of the email/password form, including the two the magic link uses.// Turning password authentication off refuses all of them, so a link issued before// the switch was flipped cannot still be redeemed. Passkey sign-in is not here: a@@ -292,12 +308,6 @@ export const auth = betterAuth({// Google sign-in. The provider is always mounted; whether it may run is decided per// request in the hook below, the same way the magic link is handled. The factory// runs once, at startup, and returns the shared options object described above.- //- // Account linking is left at better-auth's defaults: a Google address that already- // has an account signs into it and gains a linked google account row, but only when- // that account's email is confirmed (accountLinking.requireLocalEmailVerified- // defaults to true). Google itself always reports a verified address, and after a- // successful link better-auth marks the local user confirmed too.socialProviders: {google: async () => {await refreshGoogleOptions();@@ -305,6 +315,22 @@ export const auth = betterAuth({},},+ // A provider address that already has an account signs into it and gains a linked+ // account row, rather than being refused as a duplicate. By default that happens+ // only when the provider reported the address as verified and the local account+ // confirmed its own — Google always reports a verified address, an OIDC provider+ // need not, and an instance with no mail provider has no confirmed accounts at+ // all. The instance setting drops both conditions; after a successful link+ // better-auth marks the local user confirmed too.+ account: {+ accountLinking: {+ trustedProviders: resolveTrustedProviders,+ get requireLocalEmailVerified() {+ return !trustProviderEmails;+ },+ },+ },+// Extra column on the user table. Not client-settable (input: false) — the role// is decided by the create hook below.user: {diff --git a/packages/auth/src/instance.ts b/packages/auth/src/instance.tsindex 4444c5cc..c1b6426e 100644--- a/packages/auth/src/instance.ts+++ b/packages/auth/src/instance.ts@@ -45,6 +45,12 @@ export interface AuthSettings {// passkeys, which are added to an account that already exists) as the way in, so// the api refuses to turn it off while no OAuth provider is configured.emailPassword: boolean;+ // Sign a person in through an OAuth provider into the existing account with the+ // same address, whatever the provider says about that address and whether or not+ // it was ever confirmed here. Off by default: an account nobody confirmed may have+ // been registered with a password by someone other than the owner of the address,+ // and trusting the provider hands it to whoever the provider says owns it.+ trustProviderEmails: boolean;}function defaultAuthSettings(): AuthSettings {@@ -53,6 +59,7 @@ function defaultAuthSettings(): AuthSettings {requireEmailVerification: false,magicLink: false,emailPassword: true,+ trustProviderEmails: false,};}