⭐️⭐️⭐️ 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: add email provider test (#260)
I'm Groot 🌳296158b8962e
diff --git a/apps/api/src/modules/god/__tests__/integration/god-email.test.ts b/apps/api/src/modules/god/__tests__/integration/god-email.test.tsnew file mode 100644index 00000000..73960faf--- /dev/null+++ b/apps/api/src/modules/god/__tests__/integration/god-email.test.ts@@ -0,0 +1,87 @@+import { beforeEach, describe, expect, it } from 'bun:test';+import { getEmailConfig, resolveEmailConfig, setEmailSettings } from '@repo/auth';+import { resetDb } from '#tests/helpers/db';+import { addUser, setup } from '../helpers';++describe('god email settings', () => {+ beforeEach(resetDb);++ it('refuses a test from a plain user', async () => {+ await setup();+ const user = await addUser({ email: '[email protected]' });++ const res = await user.api.god['email-settings'].test.post();++ expect(res.status).toBe(403);+ });++ it('refuses a test until a provider is configured', async () => {+ const { god } = await setup();++ const res = await god.api.god['email-settings'].test.post();++ expect(res.status).toBe(400);+ expect(res.error!.value).toMatchObject({ error: 'Configure an email provider first' });+ });++ it('tests draft provider settings without persisting them', async () => {+ const { god } = await setup();++ const res = await god.api.god['email-settings'].test.post({+ smtp: {+ enabled: true,+ host: '127.0.0.1',+ port: 1,+ encryption: 'none',+ username: '',+ timeout: 1,+ },+ resend: { enabled: false },+ from: '[email protected]',+ });++ // Port 1 is deliberately unreachable. Reaching the transport proves the draft+ // was used instead of being rejected as an unconfigured saved provider.+ expect(res.status).toBe(502);+ expect(await getEmailConfig()).toBeNull();+ });++ it('reuses a saved secret while resolving a draft without changing storage', async () => {+ await setup();+ await setEmailSettings({+ smtp: {+ enabled: true,+ host: 'smtp.saved.example',+ port: 587,+ encryption: 'tls',+ username: '[email protected]',+ password: 'stored-secret',+ timeout: 10,+ },+ resend: { enabled: false },+ from: '[email protected]',+ });++ const draft = await resolveEmailConfig({+ smtp: {+ enabled: true,+ host: 'smtp.draft.example',+ port: 465,+ encryption: 'ssl',+ username: '[email protected]',+ timeout: 5,+ },+ from: '[email protected]',+ });++ expect(draft.smtp).toMatchObject({+ host: 'smtp.draft.example',+ username: '[email protected]',+ password: 'stored-secret',+ });+ expect(await getEmailConfig()).toMatchObject({+ smtp: { host: 'smtp.saved.example', password: 'stored-secret' },+ from: '[email protected]',+ });+ });+});diff --git a/apps/api/src/modules/god/__tests__/unit/email-test.test.ts b/apps/api/src/modules/god/__tests__/unit/email-test.test.tsnew file mode 100644index 00000000..4ea95ae9--- /dev/null+++ b/apps/api/src/modules/god/__tests__/unit/email-test.test.ts@@ -0,0 +1,34 @@+import { describe, expect, it } from 'bun:test';+import { emailTestError } from '../../email-test';++describe('emailTestError', () => {+ it('maps transport timeouts without exposing their details', () => {+ expect(emailTestError('Connection timeout to smtp.internal:587')).toBe(+ 'The email provider timed out',+ );+ });++ it('maps provider rate limits', () => {+ expect(emailTestError('HTTP 429: rate limit exceeded')).toBe(+ 'The email provider rate limit or quota was reached',+ );+ });++ it('maps authentication failures', () => {+ expect(emailTestError('SMTP 535: invalid login')).toBe(+ 'The email provider rejected the credentials',+ );+ });++ it('maps an unverified sender domain', () => {+ expect(emailTestError('Resend HTTP 403: The example.com domain is not verified')).toBe(+ 'The email provider rejected the From address',+ );+ });++ it('does not mistake an arbitrary host name for a sender-domain failure', () => {+ expect(emailTestError('getaddrinfo ENOTFOUND smtp.domain.example')).toBe(+ 'The email provider rejected the test message',+ );+ });+});diff --git a/apps/api/src/modules/god/email-test.ts b/apps/api/src/modules/god/email-test.tsnew file mode 100644index 00000000..f2967381--- /dev/null+++ b/apps/api/src/modules/god/email-test.ts@@ -0,0 +1,32 @@+// Provider errors can contain host names and transport details that should stay+// in the server log. Map only recognizable categories to actionable, stable API+// messages and use a generic fallback for everything else.+export function emailTestError(error: string | undefined): string {+ const value = error?.toLowerCase() ?? '';+ if (value.includes('timeout') || value.includes('aborted')) {+ return 'The email provider timed out';+ }+ if (value.includes('429') || value.includes('rate limit') || value.includes('quota')) {+ return 'The email provider rate limit or quota was reached';+ }+ if (+ value.includes('sender') ||+ value.includes('from address') ||+ value.includes('domain is not verified') ||+ value.includes('verify a domain') ||+ value.includes('domain verification')+ ) {+ return 'The email provider rejected the From address';+ }+ if (+ value.includes('auth') ||+ value.includes('credential') ||+ value.includes('invalid login') ||+ value.includes('401') ||+ value.includes('403') ||+ value.includes('535')+ ) {+ return 'The email provider rejected the credentials';+ }+ return 'The email provider rejected the test message';+}diff --git a/apps/api/src/modules/god/index.ts b/apps/api/src/modules/god/index.tsindex 83c7c090..12e0a254 100644--- a/apps/api/src/modules/god/index.ts+++ b/apps/api/src/modules/god/index.ts@@ -5,6 +5,7 @@ import {getAuthSettings,setAuthSettings,getEmailSettings,+ resolveEmailConfig,setEmailSettings,hasConfiguredEmailProvider,getGoogleSettings,@@ -17,6 +18,7 @@ import {setScimSettings,rotateScimToken,} from '@repo/auth';+import { emailBody, hasEmailProvider, sendEmail } from '@repo/mailer';import { authContext } from '#shared/auth-context';import { requireGod } from '#shared/access';import { HttpError } from '#shared/lib';@@ -38,6 +40,7 @@ import {AuthSettingsResponse,EmailSettingsBody,EmailSettingsResponse,+ EmailTestResponse,GoogleSettingsBody,GoogleSettingsResponse,InstanceProjectDetailResponse,@@ -61,6 +64,7 @@ import {scimGroupParams,userParams,} from './model';+import { emailTestError } from './email-test';import { getInstanceBotSettings, setInstanceBotSettings } from '#modules/telegram/service';import { SCIM_BASE_URL } from '#modules/scim/resource';import {@@ -174,6 +178,44 @@ export const godRoutes = new Elysia({ name: 'god', detail: { tags: ['God'] } })},})+ .post(+ '/god/email-settings/test',+ async ({ user, body: patch }) => {+ const current = requireGod(user);+ if (!current.email) throw new HttpError(400, 'The instance owner has no email address');+ const config = await resolveEmailConfig(patch ?? {});+ if (!hasEmailProvider(config)) {+ throw new HttpError(400, 'Configure an email provider first');+ }++ const body = emailBody(+ "This test confirms that It's a Plan can send email through the configured provider.",+ );+ const result = await sendEmail(+ { ...config, smtp: { ...config.smtp, timeout: config.smtp.timeout ?? 15 } },+ {+ to: current.email,+ subject: "It's a Plan email test",+ ...body,+ },+ );+ if (!result.ok) {+ console.error('[god] test email failed:', result.error);+ throw new HttpError(502, emailTestError(result.error));+ }+ return { recipient: current.email };+ },+ {+ body: t.Optional(EmailSettingsBody),+ response: { 200: EmailTestResponse, ...commonErrors, ...errors(502) },+ detail: {+ summary: 'Send a test email',+ description:+ 'Send a test message through the supplied provider settings without saving them.',+ },+ },+ )+.get('/god/google-settings',async () => ({ ...(await getGoogleSettings()), redirectUri: GOOGLE_REDIRECT_URI }),diff --git a/apps/api/src/modules/god/model.ts b/apps/api/src/modules/god/model.tsindex e597d3b9..2ca895ca 100644--- a/apps/api/src/modules/god/model.ts+++ b/apps/api/src/modules/god/model.ts@@ -84,6 +84,8 @@ export const EmailSettingsBody = t.Object({allowProjects: t.Optional(t.Boolean()),});+export const EmailTestResponse = t.Object({ recipient: t.String() });+export const GoogleSettingsResponse = t.Object({enabled: t.Boolean(),clientId: t.String(),diff --git a/apps/web/messages/ar/god.json b/apps/web/messages/ar/god.jsonindex e5539f9f..6ff21e60 100644--- a/apps/web/messages/ar/god.json+++ b/apps/web/messages/ar/god.json@@ -204,7 +204,12 @@"optional": "اختياري","apiKey": "مفتاح واجهة برمجة","projectNotifications": "إشعارات المشاريع",- "projectNotificationsHint": "خلّي المشاريع تبعت إشعاراتها من خلال المزوّد ده بدل ما كل مشروع يظبط مزوّد لوحده. وبرضه كل مشروع هو اللي يقرر يستخدمه ولا لأ."+ "projectNotificationsHint": "خلّي المشاريع تبعت إشعاراتها من خلال المزوّد ده بدل ما كل مشروع يظبط مزوّد لوحده. وبرضه كل مشروع هو اللي يقرر يستخدمه ولا لأ.",+ "test": "إرسال رسالة اختبار",+ "testing": "جارٍ الإرسال…",+ "testHint": "أرسل رسالة حقيقية بالإعدادات الحالية من دون حفظها.",+ "testConfigureFirst": "فعّل مزوّدًا وأضف بيانات الاعتماد المطلوبة أولًا.",+ "testSent": "تم إرسال رسالة اختبار إلى {email}"},"authProvider": {"saved": "تم حفظ مزوّد المصادقة",diff --git a/apps/web/messages/en/god.json b/apps/web/messages/en/god.jsonindex aa4dcebc..ad4e3c4c 100644--- a/apps/web/messages/en/god.json+++ b/apps/web/messages/en/god.json@@ -204,7 +204,12 @@"optional": "Optional","apiKey": "API key","projectNotifications": "Project notifications",- "projectNotificationsHint": "Let projects deliver their notifications through this provider instead of configuring one of their own. Each project still chooses whether to use it."+ "projectNotificationsHint": "Let projects deliver their notifications through this provider instead of configuring one of their own. Each project still chooses whether to use it.",+ "test": "Send test email",+ "testing": "Sending…",+ "testHint": "Send a real message with the current settings without saving them.",+ "testConfigureFirst": "Enable a provider and add its required credentials first.",+ "testSent": "Test email sent to {email}"},"authProvider": {"saved": "Auth provider saved",diff --git a/apps/web/messages/ru/god.json b/apps/web/messages/ru/god.jsonindex a18a6b84..59f0478f 100644--- a/apps/web/messages/ru/god.json+++ b/apps/web/messages/ru/god.json@@ -204,7 +204,12 @@"optional": "Необязательно","apiKey": "API-ключ","projectNotifications": "Уведомления проектов",- "projectNotificationsHint": "Разрешить проектам отправлять уведомления через этого провайдера вместо собственного. Каждый проект сам решает, пользоваться ли им."+ "projectNotificationsHint": "Разрешить проектам отправлять уведомления через этого провайдера вместо собственного. Каждый проект сам решает, пользоваться ли им.",+ "test": "Отправить тестовое письмо",+ "testing": "Отправка…",+ "testHint": "Отправить настоящее письмо с текущими настройками, не сохраняя их.",+ "testConfigureFirst": "Включите провайдера и добавьте обязательные учётные данные.",+ "testSent": "Тестовое письмо отправлено на {email}"},"authProvider": {"saved": "Провайдер входа сохранён",diff --git a/apps/web/messages/uk/god.json b/apps/web/messages/uk/god.jsonindex 98c94d4f..cc5daf26 100644--- a/apps/web/messages/uk/god.json+++ b/apps/web/messages/uk/god.json@@ -204,7 +204,12 @@"optional": "Необовʼязково","apiKey": "API-ключ","projectNotifications": "Сповіщення проєктів",- "projectNotificationsHint": "Дозволити проєктам надсилати сповіщення через цього провайдера замість власного. Кожен проєкт сам вирішує, чи користуватись ним."+ "projectNotificationsHint": "Дозволити проєктам надсилати сповіщення через цього провайдера замість власного. Кожен проєкт сам вирішує, чи користуватись ним.",+ "test": "Надіслати тестовий лист",+ "testing": "Надсилання…",+ "testHint": "Надіслати справжній лист із поточними налаштуваннями, не зберігаючи їх.",+ "testConfigureFirst": "Увімкніть провайдера та додайте обов’язкові облікові дані.",+ "testSent": "Тестовий лист надіслано на {email}"},"authProvider": {"saved": "Провайдера входу збережено",diff --git a/apps/web/messages/zh-CN/god.json b/apps/web/messages/zh-CN/god.jsonindex 49496adb..c6d55686 100644--- a/apps/web/messages/zh-CN/god.json+++ b/apps/web/messages/zh-CN/god.json@@ -204,7 +204,12 @@"optional": "可选","apiKey": "API 密钥","projectNotifications": "项目通知",- "projectNotificationsHint": "允许项目使用此服务商发送通知。每个项目可以自行选择是否使用。"+ "projectNotificationsHint": "允许项目使用此服务商发送通知。每个项目可以自行选择是否使用。",+ "test": "发送测试邮件",+ "testing": "正在发送…",+ "testHint": "使用当前设置发送真实邮件,无需先保存。",+ "testConfigureFirst": "请先启用服务商并填写所需凭据。",+ "testSent": "测试邮件已发送至 {email}"},"authProvider": {"saved": "身份验证提供商已保存",diff --git a/apps/web/src/features/god/components/email/GodEmailProviderSection.tsx b/apps/web/src/features/god/components/email/GodEmailProviderSection.tsxnew file mode 100644index 00000000..b1f223bf--- /dev/null+++ b/apps/web/src/features/god/components/email/GodEmailProviderSection.tsx@@ -0,0 +1,139 @@+import { useTranslations } from 'next-intl';+import type { NotificationEncryption } from '@/lib/api';+import { Input } from '@/components/ui/input';+import { Label } from '@/components/ui/label';+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from '@/components/ui/select';+import SettingsSection from '@/components/common/page/SettingsSection';+import SettingsCard from '@/components/common/page/SettingsCard';+import EnabledSwitch from '@/components/common/inputs/EnabledSwitch';+import ProviderToggle from '@/components/common/inputs/ProviderToggle';+import SecretInput from '@/components/common/inputs/SecretInput';+import type { GodEmailForm } from '../../hooks/useGodEmailForm';+import GodEmailTestButton from './GodEmailTestButton';++const ENCRYPTION_OPTIONS: NotificationEncryption[] = ['none', 'ssl', 'tls'];++export default function GodEmailProviderSection({ form }: { form: GodEmailForm }) {+ const t = useTranslations('god.email');+ const { settings } = form;++ return (+ <SettingsSection+ title={t('provider')}+ description={t('providerHint')}+ action={+ <EnabledSwitch checked={form.enabled} onChange={form.setEnabled} disabled={form.saving} />+ }+ >+ <SettingsCard className="space-y-6 p-4">+ <ProviderToggle value={form.provider} onChange={form.setProvider} disabled={form.saving} />++ <div className="space-y-1.5 sm:max-w-md">+ <Label htmlFor="email-from">{t('from')}</Label>+ <Input+ id="email-from"+ value={form.from}+ onChange={(e) => form.setFrom(e.target.value)}+ placeholder={"It's a Plan <[email protected]>"}+ />+ <p className="text-xs text-muted-foreground">{t('fromHint')}</p>+ </div>++ {form.provider === 'smtp' ? (+ <div className="grid gap-4 sm:grid-cols-3">+ <div className="space-y-1.5">+ <Label htmlFor="smtp-host">{t('host')}</Label>+ <Input+ id="smtp-host"+ value={form.host}+ onChange={(e) => form.setHost(e.target.value)}+ placeholder="smtp.example.com"+ />+ </div>+ <div className="space-y-1.5">+ <Label htmlFor="smtp-port">{t('port')}</Label>+ <Input+ id="smtp-port"+ type="number"+ min={1}+ value={form.port}+ onChange={(e) => form.setPort(e.target.value)}+ placeholder="587"+ />+ </div>+ <div className="space-y-1.5">+ <Label htmlFor="smtp-encryption">{t('encryption')}</Label>+ <Select+ value={form.encryption}+ onValueChange={(v) => form.setEncryption(v as NotificationEncryption)}+ >+ <SelectTrigger id="smtp-encryption" className="w-full">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {ENCRYPTION_OPTIONS.map((option) => (+ <SelectItem key={option} value={option}>+ {t(`encryptionOptions.${option}`)}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ <div className="space-y-1.5">+ <Label htmlFor="smtp-username">{t('username')}</Label>+ <Input+ id="smtp-username"+ value={form.username}+ onChange={(e) => form.setUsername(e.target.value)}+ placeholder="[email protected]"+ autoComplete="off"+ />+ </div>+ <div className="space-y-1.5">+ <Label htmlFor="smtp-password">{t('password')}</Label>+ <SecretInput+ id="smtp-password"+ value={form.password}+ onChange={form.setPassword}+ hasStored={settings.smtp.hasPassword}+ editable+ placeholder={t('passwordPlaceholder')}+ />+ </div>+ <div className="space-y-1.5">+ <Label htmlFor="smtp-timeout">{t('timeout')}</Label>+ <Input+ id="smtp-timeout"+ type="number"+ min={1}+ value={form.timeout}+ onChange={(e) => form.setTimeout(e.target.value)}+ placeholder={t('optional')}+ />+ </div>+ </div>+ ) : (+ <div className="space-y-1.5 sm:max-w-md">+ <Label htmlFor="resend-api-key">{t('apiKey')}</Label>+ <SecretInput+ id="resend-api-key"+ value={form.apiKey}+ onChange={form.setApiKey}+ hasStored={settings.resend.hasApiKey}+ editable+ placeholder="re_…"+ />+ </div>+ )}++ <GodEmailTestButton form={form} />+ </SettingsCard>+ </SettingsSection>+ );+}diff --git a/apps/web/src/features/god/components/email/GodEmailSettings.tsx b/apps/web/src/features/god/components/email/GodEmailSettings.tsxindex 553307c1..61b657b0 100644--- a/apps/web/src/features/god/components/email/GodEmailSettings.tsx+++ b/apps/web/src/features/god/components/email/GodEmailSettings.tsx@@ -1,22 +1,8 @@import { useTranslations } from 'next-intl';-import type { NotificationEncryption } from '@/lib/api';-import { Input } from '@/components/ui/input';-import { Label } from '@/components/ui/label';-import {- Select,- SelectContent,- SelectItem,- SelectTrigger,- SelectValue,-} from '@/components/ui/select';import SettingsSection from '@/components/common/page/SettingsSection';-import SettingsCard from '@/components/common/page/SettingsCard';import EnabledSwitch from '@/components/common/inputs/EnabledSwitch';-import ProviderToggle from '@/components/common/inputs/ProviderToggle';-import SecretInput from '@/components/common/inputs/SecretInput';import type { GodEmailForm } from '../../hooks/useGodEmailForm';--const ENCRYPTION_OPTIONS: NotificationEncryption[] = ['none', 'ssl', 'tls'];+import GodEmailProviderSection from './GodEmailProviderSection';// The instance mail provider, one of SMTP or Resend. Everything the instance sends// (password resets, address confirmation, sign-in links) goes through it, which is@@ -26,7 +12,7 @@ export default function GodEmailSettings({ form }: { form: GodEmailForm }) {return (<div className="space-y-8">- <ProviderSection form={form} />+ <GodEmailProviderSection form={form} /><SettingsSectiontitle={t('projectNotifications')}description={t('projectNotificationsHint')}@@ -41,119 +27,3 @@ export default function GodEmailSettings({ form }: { form: GodEmailForm }) {</div>);}--function ProviderSection({ form }: { form: GodEmailForm }) {- const t = useTranslations('god.email');- const { settings } = form;- return (- <SettingsSection- title={t('provider')}- description={t('providerHint')}- action={- <EnabledSwitch checked={form.enabled} onChange={form.setEnabled} disabled={form.saving} />- }- >- <SettingsCard className="space-y-6 p-4">- <ProviderToggle value={form.provider} onChange={form.setProvider} disabled={form.saving} />-- <div className="space-y-1.5 sm:max-w-md">- <Label htmlFor="email-from">{t('from')}</Label>- <Input- id="email-from"- value={form.from}- onChange={(e) => form.setFrom(e.target.value)}- placeholder={"It's a Plan <[email protected]>"}- />- <p className="text-xs text-muted-foreground">{t('fromHint')}</p>- </div>-- {form.provider === 'smtp' ? (- <div className="grid gap-4 sm:grid-cols-3">- <div className="space-y-1.5">- <Label htmlFor="smtp-host">{t('host')}</Label>- <Input- id="smtp-host"- value={form.host}- onChange={(e) => form.setHost(e.target.value)}- placeholder="smtp.example.com"- />- </div>- <div className="space-y-1.5">- <Label htmlFor="smtp-port">{t('port')}</Label>- <Input- id="smtp-port"- type="number"- min={1}- value={form.port}- onChange={(e) => form.setPort(e.target.value)}- placeholder="587"- />- </div>- <div className="space-y-1.5">- <Label htmlFor="smtp-encryption">{t('encryption')}</Label>- <Select- value={form.encryption}- onValueChange={(v) => form.setEncryption(v as NotificationEncryption)}- >- <SelectTrigger id="smtp-encryption" className="w-full">- <SelectValue />- </SelectTrigger>- <SelectContent>- {ENCRYPTION_OPTIONS.map((o) => (- <SelectItem key={o} value={o}>- {t(`encryptionOptions.${o}`)}- </SelectItem>- ))}- </SelectContent>- </Select>- </div>- <div className="space-y-1.5">- <Label htmlFor="smtp-username">{t('username')}</Label>- <Input- id="smtp-username"- value={form.username}- onChange={(e) => form.setUsername(e.target.value)}- placeholder="[email protected]"- autoComplete="off"- />- </div>- <div className="space-y-1.5">- <Label htmlFor="smtp-password">{t('password')}</Label>- <SecretInput- id="smtp-password"- value={form.password}- onChange={form.setPassword}- hasStored={settings.smtp.hasPassword}- editable- placeholder={t('passwordPlaceholder')}- />- </div>- <div className="space-y-1.5">- <Label htmlFor="smtp-timeout">{t('timeout')}</Label>- <Input- id="smtp-timeout"- type="number"- min={1}- value={form.timeout}- onChange={(e) => form.setTimeout(e.target.value)}- placeholder={t('optional')}- />- </div>- </div>- ) : (- <div className="space-y-1.5 sm:max-w-md">- <Label htmlFor="resend-api-key">{t('apiKey')}</Label>- <SecretInput- id="resend-api-key"- value={form.apiKey}- onChange={form.setApiKey}- hasStored={settings.resend.hasApiKey}- editable- placeholder="re_…"- />- </div>- )}- </SettingsCard>- </SettingsSection>- );-}diff --git a/apps/web/src/features/god/components/email/GodEmailTestButton.tsx b/apps/web/src/features/god/components/email/GodEmailTestButton.tsxnew file mode 100644index 00000000..99c479b2--- /dev/null+++ b/apps/web/src/features/god/components/email/GodEmailTestButton.tsx@@ -0,0 +1,33 @@+import { toast } from 'sonner';+import { useTranslations } from 'next-intl';+import { Button } from '@/components/ui/button';+import type { GodEmailForm } from '../../hooks/useGodEmailForm';++export default function GodEmailTestButton({ form }: { form: GodEmailForm }) {+ const t = useTranslations('god.email');++ async function send() {+ try {+ const recipient = await form.test();+ toast.success(t('testSent', { email: recipient }));+ } catch {+ // The global mutation handler shows the API error.+ }+ }++ return (+ <div className="flex flex-wrap items-center justify-between gap-3 border-t pt-4">+ <p className="text-xs text-muted-foreground">+ {form.testable ? t('testHint') : t('testConfigureFirst')}+ </p>+ <Button+ type="button"+ variant="outline"+ onClick={send}+ disabled={!form.testable || form.saving || form.testing}+ >+ {form.testing ? t('testing') : t('test')}+ </Button>+ </div>+ );+}diff --git a/apps/web/src/features/god/hooks/useGodEmailForm.ts b/apps/web/src/features/god/hooks/useGodEmailForm.tsindex 475f8ddf..994cdabc 100644--- a/apps/web/src/features/god/hooks/useGodEmailForm.ts+++ b/apps/web/src/features/god/hooks/useGodEmailForm.ts@@ -1,10 +1,17 @@'use client';import { useState } from 'react';-import type { NotificationEncryption, InstanceEmailSettings } from '@/lib/api';+import type {+ NotificationEncryption,+ InstanceEmailSettings,+ InstanceEmailSettingsPatch,+} from '@/lib/api';import type { EmailProvider } from '@/components/common/inputs/ProviderToggle';import { toPositiveInt } from '@/lib/utils';-import { useUpdateInstanceEmailSettings } from '../services/god.service';+import {+ useTestInstanceEmailSettings,+ useUpdateInstanceEmailSettings,+} from '../services/god.service';export interface GodEmailForm {provider: EmailProvider;@@ -32,7 +39,10 @@ export interface GodEmailForm {settings: InstanceEmailSettings;dirty: boolean;saving: boolean;+ testable: boolean;+ testing: boolean;save: () => Promise<void>;+ test: () => Promise<string>;}// Form state for the instance mail provider (SMTP or Resend). Shared between the@@ -44,6 +54,7 @@ export interface GodEmailForm {// back on.export function useGodEmailForm(settings: InstanceEmailSettings): GodEmailForm {const update = useUpdateInstanceEmailSettings();+ const testEmail = useTestInstanceEmailSettings();const initialProvider: EmailProvider = settings.resend.enabled ? 'resend' : 'smtp';const initialEnabled = settings.smtp.enabled || settings.resend.enabled;@@ -75,9 +86,16 @@ export function useGodEmailForm(settings: InstanceEmailSettings): GodEmailForm {from !== settings.from ||allowProjects !== settings.allowProjects ||(provider === 'smtp' ? smtpDirty : apiKey.length > 0);+ const testable =+ enabled &&+ (provider === 'smtp'+ ? host.trim().length > 0 &&+ (username.trim().length === 0 || password.length > 0 || settings.smtp.hasPassword) &&+ (from.trim().length > 0 || username.trim().length > 0)+ : (apiKey.length > 0 || settings.resend.hasApiKey) && from.trim().length > 0);- async function save() {- await update.mutateAsync({+ function currentPatch(): InstanceEmailSettingsPatch {+ return {from: from.trim(),allowProjects,smtp: {@@ -93,11 +111,20 @@ export function useGodEmailForm(settings: InstanceEmailSettings): GodEmailForm {enabled: provider === 'resend' && enabled,...(apiKey.length > 0 ? { apiKey } : {}),},- });+ };+ }++ async function save() {+ await update.mutateAsync(currentPatch());setPassword('');setApiKey('');}+ async function test() {+ const result = await testEmail.mutateAsync(currentPatch());+ return result.recipient;+ }+return {provider,setProvider,@@ -124,6 +151,9 @@ export function useGodEmailForm(settings: InstanceEmailSettings): GodEmailForm {settings,dirty,saving: update.isPending,+ testable,+ testing: testEmail.isPending,save,+ test,};}diff --git a/apps/web/src/features/god/services/god.service.ts b/apps/web/src/features/god/services/god.service.tsindex 9ec8811a..84fe1313 100644--- a/apps/web/src/features/god/services/god.service.ts+++ b/apps/web/src/features/god/services/god.service.ts@@ -59,6 +59,12 @@ export function useUpdateInstanceEmailSettings() {});}+export function useTestInstanceEmailSettings() {+ return useMutation({+ mutationFn: (patch: InstanceEmailSettingsPatch) => api.testInstanceEmailSettings(patch),+ });+}+export function useInstanceGoogleSettingsQuery() {return useQuery({queryKey: qk.instanceGoogleSettings,diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.tsindex 058e9420..ebbae3b1 100644--- a/apps/web/src/lib/api.ts+++ b/apps/web/src/lib/api.ts@@ -1158,6 +1158,10 @@ export interface InstanceEmailSettingsPatch {allowProjects?: boolean;}+export interface InstanceEmailTestResult {+ recipient: string;+}+// The Google OAuth credentials used for social sign-in. The client secret is never// returned, only a `hasClientSecret` flag. redirectUri is derived from the API origin// and has to be registered in the Google Cloud console.@@ -3560,6 +3564,11 @@ export const api = {method: 'PUT',body: JSON.stringify(patch),}),+ testInstanceEmailSettings: (patch: InstanceEmailSettingsPatch) =>+ request<InstanceEmailTestResult>('/god/email-settings/test', {+ method: 'POST',+ body: JSON.stringify(patch),+ }),getInstanceTelegramSettings: () => request<InstanceTelegramSettings>('/god/telegram-settings'),updateInstanceTelegramSettings: (patch: InstanceTelegramSettingsPatch) =>request<InstanceTelegramSettings>('/god/telegram-settings', {diff --git a/packages/auth/src/index.ts b/packages/auth/src/index.tsindex 1574a693..36ddf318 100644--- a/packages/auth/src/index.ts+++ b/packages/auth/src/index.ts@@ -586,6 +586,7 @@ export {getEmailSettings,setEmailSettings,getEmailConfig,+ resolveEmailConfig,getProjectEmailConfig,hasConfiguredEmailProvider,getGoogleSettings,diff --git a/packages/auth/src/instance.ts b/packages/auth/src/instance.tsindex a51d1768..8e16a0a5 100644--- a/packages/auth/src/instance.ts+++ b/packages/auth/src/instance.ts@@ -222,9 +222,14 @@ export async function getProjectEmailConfig(): Promise<InstanceEmailConfig | nulreturn hasEmailProvider(config) ? config : null;}-export async function setEmailSettings(patch: InstanceEmailPatch): Promise<InstanceEmailDto> {+// Resolve a prospective configuration without persisting it. The email test route uses+// this so an owner can validate edited values first, while omitted secrets still reuse+// the encrypted value already on the instance.+export async function resolveEmailConfig(+ patch: InstanceEmailPatch = {},+): Promise<InstanceEmailConfig> {const current = (await getEmailConfig()) ?? defaultEmailConfig();- const next: InstanceEmailConfig = {+ return {smtp: patch.smtp? { ...patch.smtp, password: mergeSecret(current.smtp.password, patch.smtp.password) }: current.smtp,@@ -237,6 +242,10 @@ export async function setEmailSettings(patch: InstanceEmailPatch): Promise<Instafrom: patch.from ?? current.from,allowProjects: patch.allowProjects ?? current.allowProjects,};+}++export async function setEmailSettings(patch: InstanceEmailPatch): Promise<InstanceEmailDto> {+ const next = await resolveEmailConfig(patch);const redacted = toEmailDto(next);await writeSecret(EMAIL_SECRET_KEY, next, redacted);return redacted;diff --git a/packages/mailer/src/index.ts b/packages/mailer/src/index.tsindex d4658915..672341ce 100644--- a/packages/mailer/src/index.ts+++ b/packages/mailer/src/index.ts@@ -72,6 +72,7 @@ async function sendSmtp(auth: smtp.username ? { user: smtp.username, pass: smtp.password } : undefined,connectionTimeout: timeoutMs,greetingTimeout: timeoutMs,+ socketTimeout: timeoutMs,});try {await transporter.sendMail({