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.

feat: the instance mail provider can send through Microsoft 365 with OAuth (#572)

Pasqual Tronconee59b7815582d
diff --git a/apps/api/src/modules/god/__tests__/integration/god-email-oauth.test.ts b/apps/api/src/modules/god/__tests__/integration/god-email-oauth.test.ts
new file mode 100644
index 00000000..8df0feb4
--- /dev/null
+++ b/apps/api/src/modules/god/__tests__/integration/god-email-oauth.test.ts
@@ -0,0 +1,294 @@
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from 'bun:test';
+import { resolveEmailConfig } from '@repo/auth';
+import { sendEmail, type EmailConfig } from '@repo/mailer';
+import { resetDb } from '#tests/helpers/db';
+import { setup } from '../helpers';
+
+// A Microsoft 365 mailbox with MFA only accepts an app registration's OAuth token over
+// SMTP (XOAUTH2). The token is asked of Microsoft with the client credentials, reused
+// while it lasts, and presented to the server in place of a password.
+const realFetch = globalThis.fetch;
+let tokenRequests: { url: string; body: URLSearchParams }[] = [];
+let tokenResponse: () => Response = () =>
+ Response.json({ access_token: 'token-1', expires_in: 3600 });
+
+beforeEach(() => {
+ tokenRequests = [];
+ authLines = [];
+ tokenResponse = () => Response.json({ access_token: 'token-1', expires_in: 3600 });
+ globalThis.fetch = (async (input: string | URL | Request, init?: RequestInit) => {
+ const url = String(input instanceof Request ? input.url : input);
+ if (!url.startsWith('https://login.microsoftonline.com/')) return realFetch(input, init);
+ tokenRequests.push({ url, body: new URLSearchParams(String(init?.body)) });
+ return tokenResponse();
+ }) as typeof fetch;
+});
+
+afterEach(() => {
+ globalThis.fetch = realFetch;
+});
+
+// Just enough SMTP to accept one message, recording the AUTH line it receives.
+let smtpServer: Bun.TCPSocketListener<{ data: boolean }>;
+let authLines: string[] = [];
+
+beforeAll(() => {
+ smtpServer = Bun.listen<{ data: boolean }>({
+ hostname: '127.0.0.1',
+ port: 0,
+ socket: {
+ open(socket) {
+ socket.data = { data: false };
+ socket.write('220 fake ESMTP\r\n');
+ },
+ data(socket, chunk) {
+ for (const line of chunk.toString().split('\r\n').filter(Boolean)) {
+ if (socket.data.data) {
+ if (line === '.') {
+ socket.data.data = false;
+ socket.write('250 queued\r\n');
+ }
+ continue;
+ }
+ const command = line.split(' ')[0]!.toUpperCase();
+ if (command === 'EHLO') socket.write('250-fake\r\n250 AUTH XOAUTH2\r\n');
+ else if (command === 'AUTH') {
+ authLines.push(line);
+ socket.write('235 accepted\r\n');
+ } else if (command === 'DATA') {
+ socket.data.data = true;
+ socket.write('354 go ahead\r\n');
+ } else if (command === 'QUIT') {
+ socket.write('221 bye\r\n');
+ socket.end();
+ } else socket.write('250 ok\r\n');
+ }
+ },
+ },
+ });
+});
+
+afterAll(() => smtpServer.stop(true));
+
+function microsoftConfig(clientId: string, port: number): EmailConfig {
+ return {
+ smtp: {
+ enabled: true,
+ host: '127.0.0.1',
+ port,
+ encryption: 'none',
+ username: '[email protected]',
+ password: '',
+ timeout: 5,
+ auth: 'microsoft365',
+ oauth: { tenantId: 'tenant-1', clientId, clientSecret: 'app-secret' },
+ },
+ resend: { enabled: false, apiKey: '' },
+ };
+}
+
+const message = { to: '[email protected]', subject: 'Hi', text: 'Hi', html: '<p>Hi</p>' };
+
+describe('SMTP through Microsoft 365 OAuth', () => {
+ it('presents the app token to the server instead of a password', async () => {
+ const result = await sendEmail(microsoftConfig('client-send', smtpServer.port), message);
+
+ expect(result).toEqual({ ok: true });
+ expect(tokenRequests).toHaveLength(1);
+ expect(tokenRequests[0]!.url).toBe(
+ 'https://login.microsoftonline.com/tenant-1/oauth2/v2.0/token',
+ );
+ expect(Object.fromEntries(tokenRequests[0]!.body)).toEqual({
+ grant_type: 'client_credentials',
+ client_id: 'client-send',
+ client_secret: 'app-secret',
+ scope: 'https://outlook.office365.com/.default',
+ });
+ const [, mechanism, payload] = authLines[0]!.split(' ');
+ expect(mechanism).toBe('XOAUTH2');
+ expect(Buffer.from(payload!, 'base64').toString()).toBe(
+ '[email protected]\x01auth=Bearer token-1\x01\x01',
+ );
+ });
+
+ it('reuses the token while it lasts', async () => {
+ await sendEmail(microsoftConfig('client-cache', smtpServer.port), message);
+ await sendEmail(microsoftConfig('client-cache', smtpServer.port), message);
+
+ expect(tokenRequests).toHaveLength(1);
+ expect(authLines).toHaveLength(2);
+ });
+
+ it('gives up without retrying when Microsoft refuses the credentials', async () => {
+ tokenResponse = () =>
+ Response.json(
+ { error: 'invalid_client', error_description: 'Invalid client secret' },
+ { status: 401 },
+ );
+
+ const result = await sendEmail(microsoftConfig('client-refused', smtpServer.port), message);
+
+ expect(result.ok).toBe(false);
+ expect(result.retryable).toBe(false);
+ expect(result.error).toContain('refused the credentials');
+ expect(result.error).toContain('Invalid client secret');
+ expect(authLines).toHaveLength(0);
+ });
+
+ it('retries later when Microsoft cannot answer', async () => {
+ tokenResponse = () => Response.json({ error: 'temporarily_unavailable' }, { status: 503 });
+
+ const result = await sendEmail(microsoftConfig('client-unavailable', smtpServer.port), message);
+
+ expect(result.ok).toBe(false);
+ expect(result.retryable).toBe(true);
+ expect(result.error).toContain('microsoft token request failed (503)');
+ expect(tokenRequests).toHaveLength(1);
+ });
+
+ it('asks for a new token once the last one is about to expire', async () => {
+ // 30 s is inside the minute of margin, so the token is never reused.
+ tokenResponse = () => Response.json({ access_token: 'token-short', expires_in: 30 });
+
+ await sendEmail(microsoftConfig('client-expiring', smtpServer.port), message);
+ await sendEmail(microsoftConfig('client-expiring', smtpServer.port), message);
+
+ expect(tokenRequests).toHaveLength(2);
+ });
+
+ it('refuses to send without the app credentials', async () => {
+ const config = microsoftConfig('client-none', smtpServer.port);
+ delete config.smtp.oauth;
+
+ const result = await sendEmail(config, message);
+
+ expect(result).toMatchObject({ ok: false, retryable: false });
+ expect(result.error).toContain('app credentials are missing');
+ expect(authLines).toHaveLength(0);
+ });
+});
+
+describe('god email settings with Microsoft 365', () => {
+ beforeEach(resetDb);
+
+ function draft(clientId: string, overrides: { auth?: string; tenantId?: string } = {}) {
+ return {
+ smtp: {
+ enabled: true,
+ host: '127.0.0.1',
+ port: smtpServer.port,
+ encryption: 'none' as const,
+ username: '[email protected]',
+ timeout: 5,
+ auth: (overrides.auth ?? 'microsoft365') as 'microsoft365',
+ oauth: {
+ tenantId: overrides.tenantId ?? 'tenant-1',
+ clientId,
+ clientSecret: 'app-secret',
+ },
+ },
+ resend: { enabled: false },
+ };
+ }
+
+ it('sends the test email through Microsoft 365', async () => {
+ const { god } = await setup();
+
+ const res = await god.api.god['email-settings'].test.post(draft('client-test'));
+
+ expect(res.status).toBe(200);
+ expect(res.data).toEqual({ recipient: '[email protected]' });
+ expect(tokenRequests).toHaveLength(1);
+ expect(authLines[0]).toStartWith('AUTH XOAUTH2 ');
+ });
+
+ it('says the credentials were refused when Microsoft refuses the app', async () => {
+ const { god } = await setup();
+ tokenResponse = () =>
+ Response.json(
+ { error: 'invalid_client', error_description: 'Invalid client secret' },
+ { status: 401 },
+ );
+
+ const res = await god.api.god['email-settings'].test.post(draft('client-refused-test'));
+
+ expect(res.status).toBe(502);
+ expect(res.error!.value).toMatchObject({
+ error: 'The email provider rejected the credentials',
+ });
+ expect(tokenRequests).toHaveLength(1);
+ expect(authLines).toHaveLength(0);
+ });
+
+ it('refuses an unknown authentication mode', async () => {
+ const { god } = await setup();
+
+ const res = await god.api.god['email-settings'].put(draft('client-1', { auth: 'kerberos' }));
+
+ expect(res.status).toBe(400);
+ });
+
+ it('takes a tenant id of up to 128 characters', async () => {
+ const { god } = await setup();
+
+ const atLimit = await god.api.god['email-settings'].put(
+ draft('client-1', { tenantId: 'a'.repeat(128) }),
+ );
+ const over = await god.api.god['email-settings'].put(
+ draft('client-1', { tenantId: 'a'.repeat(129) }),
+ );
+
+ expect(atLimit.status).toBe(200);
+ expect(over.status).toBe(400);
+ });
+
+ it('stores the app credentials, never returns the secret, and keeps it on a later save', async () => {
+ const { god } = await setup();
+ const smtp = {
+ enabled: true,
+ host: 'smtp.office365.com',
+ port: 587,
+ encryption: 'tls' as const,
+ username: '[email protected]',
+ timeout: 15,
+ auth: 'microsoft365' as const,
+ };
+
+ const saved = await god.api.god['email-settings'].put({
+ smtp: {
+ ...smtp,
+ oauth: { tenantId: 'tenant-1', clientId: 'client-1', clientSecret: 'app-secret' },
+ },
+ });
+ expect(saved.status).toBe(200);
+ expect(saved.data!.smtp).toMatchObject({
+ auth: 'microsoft365',
+ oauth: { tenantId: 'tenant-1', clientId: 'client-1', hasClientSecret: true },
+ });
+ expect(JSON.stringify(saved.data)).not.toContain('app-secret');
+
+ await god.api.god['email-settings'].put({
+ smtp: { ...smtp, oauth: { tenantId: 'tenant-1', clientId: 'client-1' } },
+ });
+
+ const stored = await resolveEmailConfig();
+ expect(stored.smtp.oauth).toEqual({
+ tenantId: 'tenant-1',
+ clientId: 'client-1',
+ clientSecret: 'app-secret',
+ });
+ });
+
+ it('keeps the mode on a save that leaves it out', async () => {
+ const { god } = await setup();
+ await god.api.god['email-settings'].put(draft('client-1'));
+ const { auth: _auth, ...smtpWithoutMode } = draft('client-1').smtp;
+
+ await god.api.god['email-settings'].put({ smtp: smtpWithoutMode });
+
+ const res = await god.api.god['email-settings'].get();
+ expect(res.data!.smtp.auth).toBe('microsoft365');
+ });
+});
diff --git a/apps/api/src/modules/god/model.ts b/apps/api/src/modules/god/model.ts
index 0ee1aa33..4f79ea02 100644
--- a/apps/api/src/modules/god/model.ts
+++ b/apps/api/src/modules/god/model.ts
@@ -5,6 +5,7 @@ import { PermissionMatrixSchema } from '#shared/permissions';
import { USER_KINDS } from './service';
const encryption = t.UnionEnum(['none', 'ssl', 'tls']);
+const smtpAuth = t.UnionEnum(['password', 'microsoft365']);
const EMAIL_DOMAIN_PATTERN = '^([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\\.)+[a-z0-9-]{2,63}$';
@@ -79,6 +80,8 @@ export const EmailSettingsResponse = t.Object({
username: t.String(),
hasPassword: t.Boolean(),
timeout: t.Nullable(t.Number()),
+ auth: smtpAuth,
+ oauth: t.Object({ tenantId: t.String(), clientId: t.String(), hasClientSecret: t.Boolean() }),
}),
resend: t.Object({ enabled: t.Boolean(), hasApiKey: t.Boolean() }),
from: t.String(),
@@ -97,6 +100,14 @@ export const EmailSettingsBody = t.Object({
username: t.String(),
password: t.Optional(t.String()),
timeout: t.Nullable(t.Integer({ minimum: 1 })),
+ auth: t.Optional(smtpAuth),
+ oauth: t.Optional(
+ t.Object({
+ tenantId: t.String({ maxLength: 128 }),
+ clientId: t.String({ maxLength: 128 }),
+ clientSecret: t.Optional(t.String({ maxLength: 1024 })),
+ }),
+ ),
}),
),
resend: t.Optional(t.Object({ enabled: t.Boolean(), apiKey: t.Optional(t.String()) })),
diff --git a/apps/web/messages/ar/god.json b/apps/web/messages/ar/god.json
index 48f4bcda..3dfae758 100644
--- a/apps/web/messages/ar/god.json
+++ b/apps/web/messages/ar/god.json
@@ -277,7 +277,18 @@
"testing": "جارٍ الإرسال…",
"testHint": "أرسل رسالة حقيقية بالإعدادات الحالية من دون حفظها.",
"testConfigureFirst": "فعّل مزوّدًا وأضف بيانات الاعتماد المطلوبة أولًا.",
- "testSent": "تم إرسال رسالة اختبار إلى {email}"
+ "testSent": "تم إرسال رسالة اختبار إلى {email}",
+ "smtpAuth": "المصادقة",
+ "smtpAuthOptions": {
+ "password": "كلمة المرور",
+ "microsoft365": "Microsoft 365 (OAuth)"
+ },
+ "mailbox": "صندوق البريد",
+ "tenantId": "معرّف المستأجر (tenant)",
+ "clientId": "معرّف العميل",
+ "clientSecret": "سرّ العميل",
+ "clientSecretPlaceholder": "سرّ تسجيل التطبيق",
+ "microsoft365Hint": "يسجّل الدخول كتسجيل تطبيق في Entra ID بدلًا من كلمة مرور صندوق البريد، فيمكن أن يبقى التحقق متعدد العوامل مفعّلًا. يحتاج التطبيق إلى إذن التطبيق SMTP.SendAsApp من Office 365 Exchange Online بموافقة المسؤول، وإلى الوصول إلى هذا الصندوق في Exchange، وتفعيل SMTP AUTH للصندوق."
},
"authProvider": {
"saved": "تم حفظ مزوّد المصادقة",
diff --git a/apps/web/messages/en/god.json b/apps/web/messages/en/god.json
index f91c02af..be92ec14 100644
--- a/apps/web/messages/en/god.json
+++ b/apps/web/messages/en/god.json
@@ -277,7 +277,18 @@
"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}"
+ "testSent": "Test email sent to {email}",
+ "smtpAuth": "Authentication",
+ "smtpAuthOptions": {
+ "password": "Password",
+ "microsoft365": "Microsoft 365 (OAuth)"
+ },
+ "mailbox": "Mailbox",
+ "tenantId": "Tenant ID",
+ "clientId": "Client ID",
+ "clientSecret": "Client secret",
+ "clientSecretPlaceholder": "App registration secret",
+ "microsoft365Hint": "Signs in as an app registration in Entra ID instead of with the mailbox password, so the mailbox can keep MFA on. The app needs the Office 365 Exchange Online application permission SMTP.SendAsApp with admin consent, access to this mailbox in Exchange, and SMTP AUTH turned on for the mailbox."
},
"authProvider": {
"saved": "Auth provider saved",
diff --git a/apps/web/messages/es-ES/god.json b/apps/web/messages/es-ES/god.json
index 8f493351..84d36800 100644
--- a/apps/web/messages/es-ES/god.json
+++ b/apps/web/messages/es-ES/god.json
@@ -277,7 +277,18 @@
"testing": "Enviando…",
"testHint": "Envía un mensaje real con los ajustes actuales sin guardarlos.",
"testConfigureFirst": "Activa primero un proveedor y añade sus credenciales obligatorias.",
- "testSent": "Correo de prueba enviado a {email}"
+ "testSent": "Correo de prueba enviado a {email}",
+ "smtpAuth": "Autenticación",
+ "smtpAuthOptions": {
+ "password": "Contraseña",
+ "microsoft365": "Microsoft 365 (OAuth)"
+ },
+ "mailbox": "Buzón",
+ "tenantId": "ID de inquilino (tenant)",
+ "clientId": "ID de cliente",
+ "clientSecret": "Secreto de cliente",
+ "clientSecretPlaceholder": "Secreto del registro de aplicación",
+ "microsoft365Hint": "Inicia sesión como un registro de aplicación de Entra ID en lugar de con la contraseña del buzón, así el buzón puede mantener el MFA. La aplicación necesita el permiso de aplicación SMTP.SendAsApp de Office 365 Exchange Online con consentimiento de administrador, acceso a este buzón en Exchange y SMTP AUTH activado en el buzón."
},
"authProvider": {
"saved": "El proveedor de autenticación se ha guardado",
diff --git a/apps/web/messages/fr/god.json b/apps/web/messages/fr/god.json
index 5fc20b6e..0eb960b9 100644
--- a/apps/web/messages/fr/god.json
+++ b/apps/web/messages/fr/god.json
@@ -277,7 +277,18 @@
"testing": "Envoi…",
"testHint": "Envoyer un vrai message avec les paramètres actuels, sans les enregistrer.",
"testConfigureFirst": "Activez d'abord un fournisseur et renseignez ses identifiants obligatoires.",
- "testSent": "E-mail de test envoyé à {email}"
+ "testSent": "E-mail de test envoyé à {email}",
+ "smtpAuth": "Authentification",
+ "smtpAuthOptions": {
+ "password": "Mot de passe",
+ "microsoft365": "Microsoft 365 (OAuth)"
+ },
+ "mailbox": "Boîte aux lettres",
+ "tenantId": "ID du locataire (tenant)",
+ "clientId": "ID client",
+ "clientSecret": "Secret client",
+ "clientSecretPlaceholder": "Secret de l’inscription d’application",
+ "microsoft365Hint": "Se connecte en tant qu’inscription d’application Entra ID au lieu du mot de passe de la boîte, qui peut ainsi garder la MFA. L’application a besoin de l’autorisation d’application SMTP.SendAsApp d’Office 365 Exchange Online avec consentement administrateur, d’un accès à cette boîte dans Exchange et de SMTP AUTH activé sur la boîte."
},
"authProvider": {
"saved": "Fournisseur d'authentification enregistré",
diff --git a/apps/web/messages/id/god.json b/apps/web/messages/id/god.json
index c767a42c..0db69d62 100644
--- a/apps/web/messages/id/god.json
+++ b/apps/web/messages/id/god.json
@@ -277,7 +277,18 @@
"testing": "Mengirim…",
"testHint": "Kirim pesan nyata dengan pengaturan saat ini tanpa menyimpannya.",
"testConfigureFirst": "Aktifkan penyedia dan tambahkan kredensial yang diperlukan terlebih dahulu.",
- "testSent": "Email uji dikirim ke {email}"
+ "testSent": "Email uji dikirim ke {email}",
+ "smtpAuth": "Autentikasi",
+ "smtpAuthOptions": {
+ "password": "Kata sandi",
+ "microsoft365": "Microsoft 365 (OAuth)"
+ },
+ "mailbox": "Kotak surat",
+ "tenantId": "ID tenant",
+ "clientId": "ID klien",
+ "clientSecret": "Rahasia klien",
+ "clientSecretPlaceholder": "Rahasia pendaftaran aplikasi",
+ "microsoft365Hint": "Masuk sebagai pendaftaran aplikasi Entra ID, bukan dengan kata sandi kotak surat, sehingga kotak surat tetap bisa memakai MFA. Aplikasi memerlukan izin aplikasi SMTP.SendAsApp dari Office 365 Exchange Online dengan persetujuan admin, akses ke kotak surat ini di Exchange, dan SMTP AUTH aktif untuk kotak surat."
},
"authProvider": {
"saved": "Penyedia autentikasi disimpan",
diff --git a/apps/web/messages/ko/god.json b/apps/web/messages/ko/god.json
index 5e53e606..5f4f6cc1 100644
--- a/apps/web/messages/ko/god.json
+++ b/apps/web/messages/ko/god.json
@@ -277,7 +277,18 @@
"testing": "전송 중…",
"testHint": "현재 설정을 저장하지 않고 실제 테스트 이메일을 전송합니다.",
"testConfigureFirst": "먼저 공급자를 활성화하고 필요한 인증 정보를 입력하세요.",
- "testSent": "테스트 이메일을 {email}(으)로 전송했습니다"
+ "testSent": "테스트 이메일을 {email}(으)로 전송했습니다",
+ "smtpAuth": "인증",
+ "smtpAuthOptions": {
+ "password": "비밀번호",
+ "microsoft365": "Microsoft 365 (OAuth)"
+ },
+ "mailbox": "메일함",
+ "tenantId": "테넌트 ID",
+ "clientId": "클라이언트 ID",
+ "clientSecret": "클라이언트 시크릿",
+ "clientSecretPlaceholder": "앱 등록 시크릿",
+ "microsoft365Hint": "메일함 비밀번호 대신 Entra ID의 앱 등록으로 로그인하므로 메일함에 MFA를 유지할 수 있습니다. 앱에는 관리자 동의를 받은 Office 365 Exchange Online 애플리케이션 권한 SMTP.SendAsApp, Exchange에서 이 메일함에 대한 접근 권한, 메일함에서 활성화된 SMTP AUTH가 필요합니다."
},
"authProvider": {
"saved": "인증 공급자 설정이 저장되었습니다",
diff --git a/apps/web/messages/pt-BR/god.json b/apps/web/messages/pt-BR/god.json
index 0286fb46..6c065a26 100644
--- a/apps/web/messages/pt-BR/god.json
+++ b/apps/web/messages/pt-BR/god.json
@@ -277,7 +277,18 @@
"testing": "Enviando…",
"testHint": "Envie uma mensagem real com as configurações atuais sem salvá-las.",
"testConfigureFirst": "Ative um provedor e adicione suas credenciais obrigatórias primeiro.",
- "testSent": "E-mail de teste enviado para {email}"
+ "testSent": "E-mail de teste enviado para {email}",
+ "smtpAuth": "Autenticação",
+ "smtpAuthOptions": {
+ "password": "Senha",
+ "microsoft365": "Microsoft 365 (OAuth)"
+ },
+ "mailbox": "Caixa de correio",
+ "tenantId": "ID do locatário (tenant)",
+ "clientId": "ID do cliente",
+ "clientSecret": "Segredo do cliente",
+ "clientSecretPlaceholder": "Segredo do registro de aplicativo",
+ "microsoft365Hint": "Entra como um registro de aplicativo do Entra ID em vez da senha da caixa de correio, que pode manter o MFA. O aplicativo precisa da permissão de aplicativo SMTP.SendAsApp do Office 365 Exchange Online com consentimento de administrador, acesso a esta caixa no Exchange e SMTP AUTH ativado na caixa."
},
"authProvider": {
"saved": "Provedor de autenticação salvo",
diff --git a/apps/web/messages/ru/god.json b/apps/web/messages/ru/god.json
index 23e3f9e4..2bb33642 100644
--- a/apps/web/messages/ru/god.json
+++ b/apps/web/messages/ru/god.json
@@ -277,7 +277,18 @@
"testing": "Отправка…",
"testHint": "Отправить настоящее письмо с текущими настройками, не сохраняя их.",
"testConfigureFirst": "Включите провайдера и добавьте обязательные учётные данные.",
- "testSent": "Тестовое письмо отправлено на {email}"
+ "testSent": "Тестовое письмо отправлено на {email}",
+ "smtpAuth": "Аутентификация",
+ "smtpAuthOptions": {
+ "password": "Пароль",
+ "microsoft365": "Microsoft 365 (OAuth)"
+ },
+ "mailbox": "Почтовый ящик",
+ "tenantId": "ID клиента Entra (tenant)",
+ "clientId": "ID приложения (client)",
+ "clientSecret": "Секрет приложения",
+ "clientSecretPlaceholder": "Секрет регистрации приложения",
+ "microsoft365Hint": "Входит как регистрация приложения в Entra ID вместо пароля ящика, поэтому у ящика может оставаться MFA. Приложению нужно разрешение приложения SMTP.SendAsApp из Office 365 Exchange Online с согласием администратора, доступ к этому ящику в Exchange и включённый SMTP AUTH для ящика."
},
"authProvider": {
"saved": "Провайдер входа сохранён",
diff --git a/apps/web/messages/uk/god.json b/apps/web/messages/uk/god.json
index 51aa208f..725def93 100644
--- a/apps/web/messages/uk/god.json
+++ b/apps/web/messages/uk/god.json
@@ -277,7 +277,18 @@
"testing": "Надсилання…",
"testHint": "Надіслати справжній лист із поточними налаштуваннями, не зберігаючи їх.",
"testConfigureFirst": "Увімкніть провайдера та додайте обов’язкові облікові дані.",
- "testSent": "Тестовий лист надіслано на {email}"
+ "testSent": "Тестовий лист надіслано на {email}",
+ "smtpAuth": "Автентифікація",
+ "smtpAuthOptions": {
+ "password": "Пароль",
+ "microsoft365": "Microsoft 365 (OAuth)"
+ },
+ "mailbox": "Поштова скринька",
+ "tenantId": "ID клієнта Entra (tenant)",
+ "clientId": "ID застосунку (client)",
+ "clientSecret": "Секрет застосунку",
+ "clientSecretPlaceholder": "Секрет реєстрації застосунку",
+ "microsoft365Hint": "Входить як реєстрація застосунку в Entra ID замість пароля скриньки, тож скринька може залишити MFA. Застосунку потрібен дозвіл застосунку SMTP.SendAsApp з Office 365 Exchange Online зі згодою адміністратора, доступ до цієї скриньки в Exchange і ввімкнений SMTP AUTH для скриньки."
},
"authProvider": {
"saved": "Провайдера входу збережено",
diff --git a/apps/web/messages/zh-CN/god.json b/apps/web/messages/zh-CN/god.json
index bf863849..2953c262 100644
--- a/apps/web/messages/zh-CN/god.json
+++ b/apps/web/messages/zh-CN/god.json
@@ -277,7 +277,18 @@
"testing": "正在发送…",
"testHint": "使用当前设置发送真实邮件,无需先保存。",
"testConfigureFirst": "请先启用服务商并填写所需凭据。",
- "testSent": "测试邮件已发送至 {email}"
+ "testSent": "测试邮件已发送至 {email}",
+ "smtpAuth": "身份验证",
+ "smtpAuthOptions": {
+ "password": "密码",
+ "microsoft365": "Microsoft 365(OAuth)"
+ },
+ "mailbox": "邮箱",
+ "tenantId": "租户 ID",
+ "clientId": "客户端 ID",
+ "clientSecret": "客户端密钥",
+ "clientSecretPlaceholder": "应用注册的密钥",
+ "microsoft365Hint": "以 Entra ID 应用注册的身份登录,而不是使用邮箱密码,因此邮箱可以保持开启 MFA。该应用需要 Office 365 Exchange Online 的应用程序权限 SMTP.SendAsApp 并经过管理员同意,在 Exchange 中拥有此邮箱的访问权限,并为该邮箱开启 SMTP AUTH。"
},
"authProvider": {
"saved": "身份验证提供商已保存",
diff --git a/apps/web/src/features/god/components/email/GodEmailProviderSection.tsx b/apps/web/src/features/god/components/email/GodEmailProviderSection.tsx
index 5acd481a..7d296b3f 100644
--- a/apps/web/src/features/god/components/email/GodEmailProviderSection.tsx
+++ b/apps/web/src/features/god/components/email/GodEmailProviderSection.tsx
@@ -1,5 +1,6 @@
import { useTranslations } from 'next-intl';
import type { NotificationEncryption } from '@/lib/api/endpoints/notificationSettings';
+import type { SmtpAuth } from '@/lib/api/endpoints/god';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
@@ -18,6 +19,7 @@ import type { GodEmailForm } from '../../hooks/useGodEmailForm';
import GodEmailTestButton from './GodEmailTestButton';
const ENCRYPTION_OPTIONS: NotificationEncryption[] = ['none', 'ssl', 'tls'];
+const AUTH_OPTIONS: SmtpAuth[] = ['password', 'microsoft365'];
export default function GodEmailProviderSection({ form }: { form: GodEmailForm }) {
const t = useTranslations('god.email');
@@ -86,7 +88,24 @@ export default function GodEmailProviderSection({ form }: { form: GodEmailForm }
</Select>
</div>
<div className="space-y-1.5">
- <Label htmlFor="smtp-username">{t('username')}</Label>
+ <Label htmlFor="smtp-auth">{t('smtpAuth')}</Label>
+ <Select value={form.smtpAuth} onValueChange={(v) => form.setSmtpAuth(v as SmtpAuth)}>
+ <SelectTrigger id="smtp-auth" className="w-full">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {AUTH_OPTIONS.map((option) => (
+ <SelectItem key={option} value={option}>
+ {t(`smtpAuthOptions.${option}`)}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ <div className="space-y-1.5">
+ <Label htmlFor="smtp-username">
+ {t(form.smtpAuth === 'microsoft365' ? 'mailbox' : 'username')}
+ </Label>
<Input
id="smtp-username"
value={form.username}
@@ -95,16 +114,52 @@ export default function GodEmailProviderSection({ form }: { form: GodEmailForm }
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}
- placeholder={t('passwordPlaceholder')}
- />
- </div>
+ {form.smtpAuth === 'microsoft365' ? (
+ <>
+ <div className="space-y-1.5">
+ <Label htmlFor="smtp-tenant">{t('tenantId')}</Label>
+ <Input
+ id="smtp-tenant"
+ value={form.tenantId}
+ onChange={(e) => form.setTenantId(e.target.value)}
+ autoComplete="off"
+ />
+ </div>
+ <div className="space-y-1.5">
+ <Label htmlFor="smtp-client">{t('clientId')}</Label>
+ <Input
+ id="smtp-client"
+ value={form.clientId}
+ onChange={(e) => form.setClientId(e.target.value)}
+ autoComplete="off"
+ />
+ </div>
+ <div className="space-y-1.5">
+ <Label htmlFor="smtp-client-secret">{t('clientSecret')}</Label>
+ <SecretInput
+ id="smtp-client-secret"
+ value={form.clientSecret}
+ onChange={form.setClientSecret}
+ hasStored={settings.smtp.oauth.hasClientSecret}
+ placeholder={t('clientSecretPlaceholder')}
+ />
+ </div>
+ <p className="text-xs text-muted-foreground sm:col-span-3">
+ {t('microsoft365Hint')}
+ </p>
+ </>
+ ) : (
+ <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}
+ placeholder={t('passwordPlaceholder')}
+ />
+ </div>
+ )}
<div className="space-y-1.5">
<Label htmlFor="smtp-timeout">{t('timeout')}</Label>
<Input
diff --git a/apps/web/src/features/god/hooks/useGodEmailForm.test.tsx b/apps/web/src/features/god/hooks/useGodEmailForm.test.tsx
new file mode 100644
index 00000000..00af8a22
--- /dev/null
+++ b/apps/web/src/features/god/hooks/useGodEmailForm.test.tsx
@@ -0,0 +1,136 @@
+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 { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { JSDOM } from 'jsdom';
+import type { InstanceEmailSettings, InstanceEmailSettingsPatch } from '@/lib/api/endpoints/god';
+import type { GodEmailForm } from './useGodEmailForm';
+
+// A Microsoft 365 mailbox with MFA is reached with an app registration, not a password:
+// choosing that mode points an empty server at Microsoft, asks for the app's ids and
+// secret instead of the password, and sends them with the provider.
+let saved: InstanceEmailSettingsPatch[] = [];
+
+const settings: InstanceEmailSettings = {
+ smtp: {
+ enabled: false,
+ host: '',
+ port: null,
+ encryption: 'none',
+ username: '',
+ hasPassword: false,
+ timeout: null,
+ auth: 'password',
+ oauth: { tenantId: '', clientId: '', hasClientSecret: false },
+ },
+ resend: { enabled: false, hasApiKey: false },
+ from: '',
+ allowProjects: false,
+};
+
+let dom: JSDOM;
+let root: Root;
+let form: GodEmailForm;
+let client: QueryClient;
+const replaced = ['window', 'document', 'fetch', 'IS_REACT_ACT_ENVIRONMENT'] as const;
+let originals: Map<string, PropertyDescriptor | undefined>;
+
+beforeEach(async () => {
+ originals = new Map(replaced.map((n) => [n, Object.getOwnPropertyDescriptor(globalThis, n)]));
+ dom = new JSDOM('<!doctype html><div id="root"></div>');
+ Object.defineProperties(globalThis, {
+ window: { configurable: true, value: dom.window },
+ document: { configurable: true, value: dom.window.document },
+ // The settings endpoint: a save is recorded and answered with the stored settings.
+ fetch: {
+ configurable: true,
+ value: async (_input: RequestInfo | URL, init?: RequestInit) => {
+ if (init?.method === 'PUT') saved.push(JSON.parse(String(init.body)));
+ return Response.json(settings);
+ },
+ },
+ IS_REACT_ACT_ENVIRONMENT: { configurable: true, value: true },
+ });
+ Object.defineProperty(window, '__ITSAPLAN_ENV__', {
+ value: { apiUrl: 'https://api.test', privacyUrl: '', termsUrl: '' },
+ });
+ saved = [];
+ client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ const { createRoot } = await import('react-dom/client');
+ root = createRoot(dom.window.document.querySelector('#root')!);
+ const { useGodEmailForm } = await import('./useGodEmailForm');
+ function Probe() {
+ form = useGodEmailForm(settings);
+ return null;
+ }
+ await act(async () =>
+ root.render(
+ <QueryClientProvider client={client}>
+ <Probe />
+ </QueryClientProvider>,
+ ),
+ );
+});
+
+afterEach(async () => {
+ await act(async () => root.unmount());
+ client.clear();
+ dom.window.close();
+ for (const [name, descriptor] of originals) {
+ if (descriptor) Object.defineProperty(globalThis, name, descriptor);
+ else Reflect.deleteProperty(globalThis, name);
+ }
+});
+
+const step = (fn: () => void) => act(async () => fn());
+
+describe('useGodEmailForm with Microsoft 365', () => {
+ it('points an empty server at Microsoft 365 when the mode is chosen', async () => {
+ await step(() => form.setSmtpAuth('microsoft365'));
+
+ assert.equal(form.host, 'smtp.office365.com');
+ assert.equal(form.port, '587');
+ assert.equal(form.encryption, 'tls');
+ });
+
+ it('asks for the mailbox and the app credentials instead of a password', async () => {
+ await step(() => {
+ form.setEnabled(true);
+ form.setSmtpAuth('microsoft365');
+ });
+ assert.equal(form.testable, false);
+
+ await step(() => {
+ form.setUsername('[email protected]');
+ form.setTenantId('tenant-1');
+ form.setClientId('client-1');
+ form.setClientSecret('app-secret');
+ });
+ assert.equal(form.testable, true);
+ });
+
+ it('sends the app credentials with the provider', async () => {
+ await step(() => {
+ form.setEnabled(true);
+ form.setSmtpAuth('microsoft365');
+ form.setUsername('[email protected]');
+ form.setTenantId('tenant-1');
+ form.setClientId('client-1');
+ form.setClientSecret('app-secret');
+ });
+
+ await act(async () => form.save());
+
+ assert.deepEqual(saved[0]!.smtp, {
+ enabled: true,
+ host: 'smtp.office365.com',
+ port: 587,
+ encryption: 'tls',
+ username: '[email protected]',
+ timeout: null,
+ auth: 'microsoft365',
+ oauth: { tenantId: 'tenant-1', clientId: 'client-1', clientSecret: 'app-secret' },
+ });
+ });
+});
diff --git a/apps/web/src/features/god/hooks/useGodEmailForm.ts b/apps/web/src/features/god/hooks/useGodEmailForm.ts
index a0635f9f..1aac683f 100644
--- a/apps/web/src/features/god/hooks/useGodEmailForm.ts
+++ b/apps/web/src/features/god/hooks/useGodEmailForm.ts
@@ -1,7 +1,11 @@
'use client';
import { useState } from 'react';
-import type { InstanceEmailSettings, InstanceEmailSettingsPatch } from '@/lib/api/endpoints/god';
+import type {
+ InstanceEmailSettings,
+ InstanceEmailSettingsPatch,
+ SmtpAuth,
+} from '@/lib/api/endpoints/god';
import type { NotificationEncryption } from '@/lib/api/endpoints/notificationSettings';
import type { EmailProvider } from '@/components/common/inputs/ProviderToggle';
import { toPositiveInt } from '@/lib/utils';
@@ -27,6 +31,14 @@ export interface GodEmailForm {
setUsername: (v: string) => void;
password: string;
setPassword: (v: string) => void;
+ smtpAuth: SmtpAuth;
+ setSmtpAuth: (v: SmtpAuth) => void;
+ tenantId: string;
+ setTenantId: (v: string) => void;
+ clientId: string;
+ setClientId: (v: string) => void;
+ clientSecret: string;
+ setClientSecret: (v: string) => void;
timeout: string;
setTimeout: (v: string) => void;
apiKey: string;
@@ -66,6 +78,10 @@ export function useGodEmailForm(settings: InstanceEmailSettings): GodEmailForm {
const [encryption, setEncryption] = useState<NotificationEncryption>(settings.smtp.encryption);
const [username, setUsername] = useState(settings.smtp.username);
const [password, setPassword] = useState('');
+ const [smtpAuth, setSmtpAuthState] = useState<SmtpAuth>(settings.smtp.auth);
+ const [tenantId, setTenantId] = useState(settings.smtp.oauth.tenantId);
+ const [clientId, setClientId] = useState(settings.smtp.oauth.clientId);
+ const [clientSecret, setClientSecret] = useState('');
const [timeout, setTimeout] = useState(initialTimeout);
const [apiKey, setApiKey] = useState('');
const [allowProjects, setAllowProjects] = useState(settings.allowProjects);
@@ -76,7 +92,18 @@ export function useGodEmailForm(settings: InstanceEmailSettings): GodEmailForm {
encryption !== settings.smtp.encryption ||
username !== settings.smtp.username ||
timeout !== initialTimeout ||
- password.length > 0;
+ password.length > 0 ||
+ smtpAuth !== settings.smtp.auth ||
+ tenantId !== settings.smtp.oauth.tenantId ||
+ clientId !== settings.smtp.oauth.clientId ||
+ clientSecret.length > 0;
+ const smtpCredentialsReady =
+ smtpAuth === 'microsoft365'
+ ? username.trim().length > 0 &&
+ tenantId.trim().length > 0 &&
+ clientId.trim().length > 0 &&
+ (clientSecret.length > 0 || settings.smtp.oauth.hasClientSecret)
+ : username.trim().length === 0 || password.length > 0 || settings.smtp.hasPassword;
const dirty =
provider !== initialProvider ||
enabled !== initialEnabled ||
@@ -87,7 +114,7 @@ export function useGodEmailForm(settings: InstanceEmailSettings): GodEmailForm {
enabled &&
(provider === 'smtp'
? host.trim().length > 0 &&
- (username.trim().length === 0 || password.length > 0 || settings.smtp.hasPassword) &&
+ smtpCredentialsReady &&
(from.trim().length > 0 || username.trim().length > 0)
: (apiKey.length > 0 || settings.resend.hasApiKey) && from.trim().length > 0);
@@ -103,6 +130,12 @@ export function useGodEmailForm(settings: InstanceEmailSettings): GodEmailForm {
username: username.trim(),
...(password.length > 0 ? { password } : {}),
timeout: toPositiveInt(timeout),
+ auth: smtpAuth,
+ oauth: {
+ tenantId: tenantId.trim(),
+ clientId: clientId.trim(),
+ ...(clientSecret.length > 0 ? { clientSecret } : {}),
+ },
},
resend: {
enabled: provider === 'resend' && enabled,
@@ -111,9 +144,21 @@ export function useGodEmailForm(settings: InstanceEmailSettings): GodEmailForm {
};
}
+ // Microsoft 365 only accepts OAuth on its own endpoint, so an empty server is filled
+ // with it rather than left for the owner to look up.
+ function setSmtpAuth(next: SmtpAuth) {
+ setSmtpAuthState(next);
+ if (next === 'microsoft365' && host.trim().length === 0) {
+ setHost('smtp.office365.com');
+ setPort('587');
+ setEncryption('tls');
+ }
+ }
+
async function save() {
await update.mutateAsync(currentPatch());
setPassword('');
+ setClientSecret('');
setApiKey('');
}
@@ -139,6 +184,14 @@ export function useGodEmailForm(settings: InstanceEmailSettings): GodEmailForm {
setUsername,
password,
setPassword,
+ smtpAuth,
+ setSmtpAuth,
+ tenantId,
+ setTenantId,
+ clientId,
+ setClientId,
+ clientSecret,
+ setClientSecret,
timeout,
setTimeout,
apiKey,
diff --git a/apps/web/src/lib/api/endpoints/god.ts b/apps/web/src/lib/api/endpoints/god.ts
index 6255d39d..33952d64 100644
--- a/apps/web/src/lib/api/endpoints/god.ts
+++ b/apps/web/src/lib/api/endpoints/god.ts
@@ -44,6 +44,10 @@ export interface InstanceAuthSettingsPatch {
allowedEmailDomains?: string[];
}
+// 'microsoft365' signs in to smtp.office365.com as an app registration (OAuth) instead
+// of with the mailbox password, which Microsoft refuses once the mailbox has MFA.
+export type SmtpAuth = 'password' | 'microsoft365';
+
// The instance mail provider used for authentication email (password reset, address
// verification, magic links). Separate from a team's notification provider.
// Secrets are never returned, only a `hasX` flag.
@@ -56,6 +60,8 @@ export interface InstanceEmailSettings {
username: string;
hasPassword: boolean;
timeout: number | null;
+ auth: SmtpAuth;
+ oauth: { tenantId: string; clientId: string; hasClientSecret: boolean };
};
resend: { enabled: boolean; hasApiKey: boolean };
from: string;
@@ -72,6 +78,8 @@ export interface InstanceEmailSettingsPatch {
username: string;
password?: string;
timeout: number | null;
+ auth?: SmtpAuth;
+ oauth?: { tenantId: string; clientId: string; clientSecret?: string };
};
resend?: { enabled: boolean; apiKey?: string };
from?: string;
diff --git a/docs/self-hosting.md b/docs/self-hosting.md
index 88668748..1bd2070c 100644
--- a/docs/self-hosting.md
+++ b/docs/self-hosting.md
@@ -76,6 +76,26 @@ The OAuth redirect URIs that god mode shows include the path. An api on a differ
registrable domain than the web app (`api.other.com`) does not work: the session cookie
cannot be shared across sites.
+## Mail
+
+The instance sends password resets, address confirmations, sign-in links and invites through
+the mail provider set in god mode under **Integrations → Email provider**: SMTP or Resend.
+
+A Microsoft 365 mailbox refuses a password over SMTP once it has MFA. Set **Authentication**
+to **Microsoft 365 (OAuth)** instead: the instance signs in as an Entra ID app registration
+and sends as the mailbox over XOAUTH2. An empty server is filled with
+`smtp.office365.com:587` and STARTTLS. On the Microsoft side:
+
+1. Register an app in Entra ID, add a client secret, and grant it the Office 365 Exchange
+ Online application permission `SMTP.SendAsApp`, with admin consent.
+2. In Exchange Online PowerShell, register the app's service principal and give it access
+ to the mailbox: `New-ServicePrincipal -AppId <client id> -ObjectId <enterprise app object id>`,
+ then `Add-MailboxPermission -Identity <mailbox> -User <service principal id> -AccessRights FullAccess`.
+3. Turn on SMTP AUTH for that mailbox (`Set-CASMailbox <mailbox> -SmtpClientAuthenticationDisabled $false`).
+
+Then paste the tenant ID, the client ID and the secret into the page and send a test. A
+refused token is reported as rejected credentials and is not retried.
+
## Single sign-on
Any provider with an OpenID Connect discovery document works: Keycloak, Authentik, KanIDM,
diff --git a/packages/auth/src/instance.ts b/packages/auth/src/instance.ts
index 9152d1d7..b48933ff 100644
--- a/packages/auth/src/instance.ts
+++ b/packages/auth/src/instance.ts
@@ -14,7 +14,7 @@ import {
type InstanceEmailConfig,
} from '@repo/db';
import { and, eq, gte, like, lt, sql } from 'drizzle-orm';
-import { hasEmailProvider, type SmtpConfig } from '@repo/mailer';
+import { hasEmailProvider, type SmtpAuth, type SmtpConfig } from '@repo/mailer';
import type { GenericEndpointContext } from 'better-auth';
// Authentication settings: who may register, whether email has to be confirmed,
@@ -173,6 +173,8 @@ export interface InstanceEmailDto {
username: string;
hasPassword: boolean;
timeout: number | null;
+ auth: SmtpAuth;
+ oauth: { tenantId: string; clientId: string; hasClientSecret: boolean };
};
resend: { enabled: boolean; hasApiKey: boolean };
from: string;
@@ -191,6 +193,8 @@ export interface InstanceEmailPatch {
username: string;
password?: string;
timeout: number | null;
+ auth?: SmtpAuth;
+ oauth?: { tenantId: string; clientId: string; clientSecret?: string };
};
resend?: { enabled: boolean; apiKey?: string };
from?: string;
@@ -207,6 +211,12 @@ function toEmailDto(config: InstanceEmailConfig): InstanceEmailDto {
username: config.smtp.username,
hasPassword: config.smtp.password.length > 0,
timeout: config.smtp.timeout,
+ auth: config.smtp.auth ?? 'password',
+ oauth: {
+ tenantId: config.smtp.oauth?.tenantId ?? '',
+ clientId: config.smtp.oauth?.clientId ?? '',
+ hasClientSecret: (config.smtp.oauth?.clientSecret ?? '').length > 0,
+ },
},
resend: { enabled: config.resend.enabled, hasApiKey: config.resend.apiKey.length > 0 },
from: config.from,
@@ -218,6 +228,25 @@ export async function getEmailSettings(): Promise<InstanceEmailDto> {
return toEmailDto((await getInstanceEmailConfig()) ?? defaultInstanceEmailConfig());
}
+function resolveSmtp(
+ current: SmtpConfig,
+ patch: NonNullable<InstanceEmailPatch['smtp']>,
+): SmtpConfig {
+ const { oauth, ...rest } = patch;
+ return {
+ ...rest,
+ password: mergeSecret(current.password, patch.password),
+ auth: patch.auth ?? current.auth ?? 'password',
+ oauth: oauth
+ ? {
+ tenantId: oauth.tenantId,
+ clientId: oauth.clientId,
+ clientSecret: mergeSecret(current.oauth?.clientSecret ?? '', oauth.clientSecret),
+ }
+ : current.oauth,
+ };
+}
+
// 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.
@@ -226,9 +255,7 @@ export async function resolveEmailConfig(
): Promise<InstanceEmailConfig> {
const current = (await getInstanceEmailConfig()) ?? defaultInstanceEmailConfig();
return {
- smtp: patch.smtp
- ? { ...patch.smtp, password: mergeSecret(current.smtp.password, patch.smtp.password) }
- : current.smtp,
+ smtp: patch.smtp ? resolveSmtp(current.smtp, patch.smtp) : current.smtp,
resend: patch.resend
? {
enabled: patch.resend.enabled,
diff --git a/packages/mailer/src/index.ts b/packages/mailer/src/index.ts
index 672341ce..a83b8adf 100644
--- a/packages/mailer/src/index.ts
+++ b/packages/mailer/src/index.ts
@@ -5,7 +5,18 @@ import nodemailer from 'nodemailer';
// instance). Only the transport lives here. Where the credentials come from, how
// they are stored, and what the message says belong to the caller.
-const RESEND_TIMEOUT_MS = 15_000;
+const HTTP_TIMEOUT_MS = 15_000;
+
+// Microsoft 365 refuses a password once the mailbox has MFA, and is retiring password
+// SMTP altogether. 'microsoft365' signs in as an app registration (client credentials,
+// permission SMTP.SendAsApp) and presents the token over XOAUTH2 as `username`.
+export type SmtpAuth = 'password' | 'microsoft365';
+
+export interface MicrosoftOAuthConfig {
+ tenantId: string;
+ clientId: string;
+ clientSecret: string;
+}
export interface SmtpConfig {
enabled: boolean;
@@ -15,6 +26,9 @@ export interface SmtpConfig {
username: string;
password: string;
timeout: number | null;
+ // Absent on configs stored before it existed: those are password ones.
+ auth?: SmtpAuth;
+ oauth?: MicrosoftOAuthConfig;
}
export interface ResendConfig {
@@ -57,6 +71,81 @@ function fromAddress(config: EmailConfig, provider: 'smtp' | 'resend'): string |
return null;
}
+class TokenError extends Error {
+ constructor(
+ message: string,
+ readonly retryable: boolean,
+ ) {
+ super(message);
+ }
+}
+
+// A token lasts about an hour; reusing it spares Microsoft a sign-in per message.
+const tokenCache = new Map<string, { token: string; expiresAt: number }>();
+const TOKEN_MARGIN_MS = 60_000;
+
+async function microsoftAccessToken(oauth: MicrosoftOAuthConfig): Promise<string> {
+ const key = `${oauth.tenantId}|${oauth.clientId}|${oauth.clientSecret}`;
+ const cached = tokenCache.get(key);
+ if (cached && cached.expiresAt - TOKEN_MARGIN_MS > Date.now()) return cached.token;
+
+ let res: Response;
+ try {
+ res = await fetch(
+ `https://login.microsoftonline.com/${encodeURIComponent(oauth.tenantId)}/oauth2/v2.0/token`,
+ {
+ method: 'POST',
+ headers: { 'content-type': 'application/x-www-form-urlencoded' },
+ signal: AbortSignal.timeout(HTTP_TIMEOUT_MS),
+ body: new URLSearchParams({
+ grant_type: 'client_credentials',
+ client_id: oauth.clientId,
+ client_secret: oauth.clientSecret,
+ scope: 'https://outlook.office365.com/.default',
+ }),
+ },
+ );
+ } catch (err) {
+ throw new TokenError(
+ err instanceof Error ? err.message : 'microsoft token request failed',
+ true,
+ );
+ }
+ const body = (await res.json().catch(() => ({}))) as {
+ access_token?: string;
+ expires_in?: number;
+ error_description?: string;
+ };
+ if (!res.ok || !body.access_token) {
+ const retryable = res.status >= 500 || res.status === 429;
+ // A 4xx is a wrong tenant, client or secret, or a missing grant: retrying will not fix it.
+ const reason = retryable
+ ? 'microsoft token request failed'
+ : 'microsoft refused the credentials';
+ throw new TokenError(
+ `${reason} (${res.status}): ${body.error_description ?? 'no description'}`,
+ retryable,
+ );
+ }
+ tokenCache.set(key, {
+ token: body.access_token,
+ expiresAt: Date.now() + (body.expires_in ?? 3600) * 1000,
+ });
+ return body.access_token;
+}
+
+async function smtpAuth(smtp: SmtpConfig) {
+ if (smtp.auth === 'microsoft365') {
+ if (!smtp.oauth) throw new TokenError('microsoft 365 app credentials are missing', false);
+ return {
+ type: 'OAuth2' as const,
+ user: smtp.username,
+ accessToken: await microsoftAccessToken(smtp.oauth),
+ };
+ }
+ return smtp.username ? { user: smtp.username, pass: smtp.password } : undefined;
+}
+
async function sendSmtp(
smtp: SmtpConfig,
message: EmailMessage,
@@ -64,12 +153,19 @@ async function sendSmtp(
): Promise<SendResult> {
// The config stores the timeout in seconds, nodemailer takes milliseconds.
const timeoutMs = smtp.timeout ? smtp.timeout * 1000 : undefined;
+ let auth: Awaited<ReturnType<typeof smtpAuth>>;
+ try {
+ auth = await smtpAuth(smtp);
+ } catch (err) {
+ const retryable = err instanceof TokenError ? err.retryable : true;
+ return { ok: false, retryable, error: err instanceof Error ? err.message : 'smtp auth failed' };
+ }
const transporter = nodemailer.createTransport({
host: smtp.host,
port: smtp.port ?? (smtp.encryption === 'ssl' ? 465 : 587),
secure: smtp.encryption === 'ssl',
requireTLS: smtp.encryption === 'tls',
- auth: smtp.username ? { user: smtp.username, pass: smtp.password } : undefined,
+ auth,
connectionTimeout: timeoutMs,
greetingTimeout: timeoutMs,
socketTimeout: timeoutMs,
@@ -105,7 +201,7 @@ async function sendResend(
'content-type': 'application/json',
...(message.idempotencyKey ? { 'idempotency-key': message.idempotencyKey } : {}),
},
- signal: AbortSignal.timeout(RESEND_TIMEOUT_MS),
+ signal: AbortSignal.timeout(HTTP_TIMEOUT_MS),
body: JSON.stringify({
from,
to: [message.to],