From f2d58d2f792c69c35900c3e9365d10749b8d2710 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Wed, 16 Sep 2026 10:36:04 +0800 Subject: [PATCH] feat(notifications): deliver online/offline alerts over SMTP Fixes #459 --- packages/core/src/notifications/config.ts | 123 +++++- packages/core/src/notifications/manager.ts | 100 +++-- packages/core/src/notifications/smtp.ts | 383 ++++++++++++++++++ packages/core/src/webui/backup.ts | 2 +- .../core/tests/notifications-config.test.ts | 92 ++++- .../core/tests/notifications-manager.test.ts | 98 +++++ .../core/tests/notifications-smtp.test.ts | 289 +++++++++++++ .../components/config/notification-opt-in.tsx | 9 +- .../settings/notification-channel-dialog.tsx | 372 ++++++++++++++--- .../settings/notifications-panel.tsx | 28 +- packages/webui/src/types.ts | 15 + .../notification-channel-dialog.test.tsx | 91 +++++ .../webui/tests/notification-channel.test.ts | 107 +++++ 13 files changed, 1600 insertions(+), 109 deletions(-) create mode 100644 packages/core/src/notifications/smtp.ts create mode 100644 packages/core/tests/notifications-smtp.test.ts create mode 100644 packages/webui/tests/notification-channel-dialog.test.tsx create mode 100644 packages/webui/tests/notification-channel.test.ts diff --git a/packages/core/src/notifications/config.ts b/packages/core/src/notifications/config.ts index 8753851b..6b8cec89 100644 --- a/packages/core/src/notifications/config.ts +++ b/packages/core/src/notifications/config.ts @@ -11,6 +11,7 @@ import { boolOr, clampInt, isObject } from '@snowluma/common/coerce'; import { createLogger } from '@snowluma/common/logger'; import fs from 'fs'; import path from 'path'; +import { extractAddress, parseRecipients } from './smtp'; const log = createLogger('Notifications.Config'); @@ -39,14 +40,37 @@ const HEADER_NAME_RE = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/; /** event ∈ {offline, online}; rendered verbatim into `{event}`. */ export type NotificationEvent = 'offline' | 'online'; +export type NotificationChannelType = 'webhook' | 'email'; + export interface NotificationChannel { id: string; name: string; + type: NotificationChannelType; + /** http(s) webhook target. Empty on email channels. */ url: string; bodyTemplate: string; enabled: boolean; - /** Extra outbound request headers (Authorization, etc.). */ + /** Extra outbound request headers (Authorization, etc.). Webhook only. */ headers?: Record; + smtpHost?: string; + smtpPort?: number; + smtpSecure?: boolean; + smtpUser?: string; + smtpPass?: string; + from?: string; + to?: string; + subjectTemplate?: string; +} + +export function isEmailChannel(ch: NotificationChannel): ch is NotificationChannel & { + smtpHost: string; + smtpPort: number; + smtpSecure: boolean; + from: string; + to: string; + subjectTemplate: string; +} { + return ch.type === 'email'; } export interface NotificationsConfig { @@ -63,6 +87,23 @@ export const DEFAULT_BODY_TEMPLATE = `{ "desp": "您的账号状态发生了改变。\\n\\n**昵称**:{nickname}\\n**QQ号**:{uin}\\n**当前状态**:{event}\\n**时间**:{time}" }`; +export const DEFAULT_SUBJECT_TEMPLATE = '账号{event}:{nickname} ({uin})'; + +export const DEFAULT_EMAIL_BODY_TEMPLATE = `账号状态发生了改变。 + +昵称:{nickname} +QQ号:{uin} +当前状态:{event} +时间:{time}`; + +const SMTP_HOST_MAX = 253; +const SMTP_USER_MAX = 256; +const SMTP_PASS_MAX = 256; +const EMAIL_FIELD_MAX = 1024; +const SUBJECT_TEMPLATE_MAX = 256; +const SMTP_PORT_MIN = 1; +const SMTP_PORT_MAX = 65535; + export function defaultNotificationsConfig(): NotificationsConfig { return { version: NOTIFICATIONS_CONFIG_VERSION, @@ -124,8 +165,6 @@ function isHttpUrl(value: string): boolean { } } -/** A channel is usable only with a valid id AND an http(s) target — anything - * else is unusable, so the whole entry is dropped (total normalize). */ function normalizeHeaders(value: unknown): Record | undefined { if (!isObject(value)) return undefined; const out: Record = {}; @@ -147,17 +186,93 @@ function normalizeHeaders(value: unknown): Record | undefined { return Object.keys(out).length > 0 ? out : undefined; } +function normalizeSmtpHost(value: unknown): string | null { + if (typeof value !== 'string') return null; + const v = value.trim(); + if (!v || v.length > SMTP_HOST_MAX) return null; + if (/\s/.test(v) || v.includes('/') || v.includes('://')) return null; + return v; +} + +function normalizeFrom(value: unknown): string | null { + if (typeof value !== 'string') return null; + const v = value.trim().slice(0, EMAIL_FIELD_MAX); + return extractAddress(v) ? v : null; +} + +function normalizeTo(value: unknown): string | null { + if (typeof value !== 'string') return null; + const addrs = parseRecipients(value.trim().slice(0, EMAIL_FIELD_MAX)); + return addrs.length > 0 ? addrs.join(', ') : null; +} + +function normalizeChannelType(value: unknown): NotificationChannelType | null { + if (value === 'email') return 'email'; + if (value === 'webhook' || value === undefined || value === '') return 'webhook'; + return null; +} + +function normalizeEmailChannel( + raw: Record, + id: string, + name: string, +): NotificationChannel | null { + const smtpHost = normalizeSmtpHost(raw.smtpHost); + const from = normalizeFrom(raw.from); + const to = normalizeTo(raw.to); + if (!smtpHost || !from || !to) return null; + + const portRaw = raw.smtpPort; + const portProvided = portRaw !== undefined && portRaw !== null && portRaw !== ''; + const secureProvided = typeof raw.smtpSecure === 'boolean'; + const port = portProvided + ? clampInt(portRaw, SMTP_PORT_MIN, SMTP_PORT_MAX, 0) + : 0; + if (portProvided && port === 0) return null; + + const smtpSecure = secureProvided ? Boolean(raw.smtpSecure) : port === 465 || port === 0; + const smtpPort = port === 0 ? (smtpSecure ? 465 : 587) : port; + + const smtpUser = typeof raw.smtpUser === 'string' ? raw.smtpUser.trim().slice(0, SMTP_USER_MAX) : ''; + const smtpPass = typeof raw.smtpPass === 'string' ? raw.smtpPass.slice(0, SMTP_PASS_MAX) : ''; + + return { + id, + name, + type: 'email', + url: '', + bodyTemplate: strOr(raw.bodyTemplate, DEFAULT_EMAIL_BODY_TEMPLATE, BODY_TEMPLATE_MAX), + enabled: boolOr(raw.enabled, true), + smtpHost, + smtpPort, + smtpSecure, + ...(smtpUser ? { smtpUser } : {}), + ...(smtpPass ? { smtpPass } : {}), + from, + to, + subjectTemplate: strOr(raw.subjectTemplate, DEFAULT_SUBJECT_TEMPLATE, SUBJECT_TEMPLATE_MAX) || DEFAULT_SUBJECT_TEMPLATE, + }; +} + +/** A channel is usable only with a valid id AND a deliverable target — + * http(s) URL for webhooks, SMTP host + from/to for email. Anything else + * is dropped (total normalize). */ function normalizeChannel(raw: unknown): NotificationChannel | null { if (!isObject(raw)) return null; const id = normalizeChannelId(raw.id); if (!id) return null; + const type = normalizeChannelType(raw.type); + if (!type) return null; + const name = strOr(raw.name, id, CHANNEL_NAME_MAX).trim() || id; + if (type === 'email') return normalizeEmailChannel(raw, id, name); + const url = typeof raw.url === 'string' ? raw.url.trim() : ''; if (!isHttpUrl(url)) return null; - const name = strOr(raw.name, id, CHANNEL_NAME_MAX).trim() || id; const headers = normalizeHeaders(raw.headers); return { id, name, + type: 'webhook', url, bodyTemplate: strOr(raw.bodyTemplate, DEFAULT_BODY_TEMPLATE, BODY_TEMPLATE_MAX), enabled: boolOr(raw.enabled, true), diff --git a/packages/core/src/notifications/manager.ts b/packages/core/src/notifications/manager.ts index c75c457a..d07d6ba9 100644 --- a/packages/core/src/notifications/manager.ts +++ b/packages/core/src/notifications/manager.ts @@ -2,16 +2,17 @@ // // Subscribes to BridgeManager session online/offline edges, runs a per-UIN // debounce state machine (see debounce.ts), and on a fired transition renders -// each opted-in + enabled channel's body template and POSTs it — recording the +// each opted-in + enabled channel's template and delivers it — recording the // outcome in a bounded in-memory history (lost on restart, by design). // -// Side-effecting collaborators (config load, per-UIN channel ids, the outbound -// POST, the clock) are injected so the class is fully unit-testable; the real -// wiring lives in `createNotificationManager()` at the bottom. +// Side-effecting collaborators (config load, per-UIN channel ids, webhook POST, +// SMTP send, the clock) are injected so the class is fully unit-testable; the +// real wiring lives in `createNotificationManager()` at the bottom. import { createLogger } from '@snowluma/common/logger'; import { loadOneBotConfig } from '@snowluma/onebot/config'; import type { BridgeManager } from '../bridge/manager'; import { + isEmailChannel, loadNotificationsConfig, renderTemplate, type NotificationChannel, @@ -19,6 +20,7 @@ import { type NotificationsConfig, } from './config'; import { DebounceMachine, type DebounceDecision } from './debounce'; +import { formatSmtpError, parseRecipients, sendSmtpMail } from './smtp'; const log = createLogger('Notifications'); @@ -43,13 +45,27 @@ export interface PostResult { error?: string; } +export interface MailPayload { + host: string; + port: number; + secure: boolean; + user?: string; + pass?: string; + from: string; + to: string; + subject: string; + text: string; +} + export interface NotificationManagerDeps { /** Global channel store (channels + debounceSeconds). */ loadConfig: () => NotificationsConfig; /** The channel ids a UIN has opted into. */ loadChannelIds: (uin: string) => string[]; - /** Outbound delivery — never throws; failures come back as `{ ok: false }`. */ + /** Webhook delivery — never throws; failures come back as `{ ok: false }`. */ post: (url: string, body: string, headers?: Record) => Promise; + /** SMTP delivery — optional so webhook-only tests stay lean. */ + sendMail?: (mail: MailPayload) => Promise; now: () => number; historyLimit?: number; } @@ -140,7 +156,7 @@ export class NotificationManager { } } - /** Render + POST a transition to every opted-in, enabled channel and record + /** Render + deliver a transition to every opted-in, enabled channel and record * the outcome. Never throws (a bad channel can't break the others). */ async notify(uin: string, event: NotificationEvent): Promise { let channels: NotificationChannel[]; @@ -162,14 +178,7 @@ export class NotificationManager { }; for (const ch of channels) { - const body = renderTemplate(ch.bodyTemplate, vars); - let result: PostResult; - try { - result = await this.deps.post(ch.url, body, ch.headers); - } catch (err) { - // The injected post is contracted not to throw, but guard anyway. - result = { ok: false, error: errMsg(err) }; - } + const result = await this.deliver(ch, vars); this.record({ time: this.deps.now(), uin, @@ -185,9 +194,33 @@ export class NotificationManager { } } + private async deliver(ch: NotificationChannel, vars: Record): Promise { + try { + if (isEmailChannel(ch)) { + const send = this.deps.sendMail; + if (!send) return { ok: false, error: 'email delivery is not configured' }; + return await send({ + host: ch.smtpHost, + port: ch.smtpPort, + secure: ch.smtpSecure, + user: ch.smtpUser, + pass: ch.smtpPass, + from: ch.from, + to: ch.to, + subject: renderTemplate(ch.subjectTemplate, vars), + text: renderTemplate(ch.bodyTemplate, vars), + }); + } + return await this.deps.post(ch.url, renderTemplate(ch.bodyTemplate, vars), ch.headers); + } catch (err) { + // Injected collaborators are contracted not to throw, but guard anyway. + return { ok: false, error: errMsg(err) }; + } + } + /** Send a one-off test to a single channel by id — ignores `enabled` and the * per-UIN opt-in (you test a channel before wiring it up), with sample - * variables. Reuses the real render+POST path; NOT recorded to history. + * variables. Reuses the real render+deliver path; NOT recorded to history. * `found:false` means the channel id is unknown. */ async testSend(channelId: string): Promise { let channel: NotificationChannel | undefined; @@ -197,17 +230,13 @@ export class NotificationManager { return { ok: false, found: false, error: errMsg(err) }; } if (!channel) return { ok: false, found: false }; - const body = renderTemplate(channel.bodyTemplate, { + const vars = { uin: '10000', nickname: '测试账号', - event: 'offline', + event: 'offline' as const, time: new Date(this.deps.now()).toISOString(), - }); - try { - return { ...(await this.deps.post(channel.url, body, channel.headers)), found: true }; - } catch (err) { - return { ok: false, found: true, error: errMsg(err) }; - } + }; + return { ...(await this.deliver(channel, vars)), found: true }; } private record(rec: DeliveryRecord): void { @@ -249,12 +278,37 @@ export function createDefaultPost(timeoutMs = DEFAULT_POST_TIMEOUT_MS): Notifica }; } +const DEFAULT_SMTP_TIMEOUT_MS = 15_000; + +/** Default SMTP send. Never throws. */ +export function createDefaultSendMail(timeoutMs = DEFAULT_SMTP_TIMEOUT_MS): NonNullable { + return async (mail) => { + try { + await sendSmtpMail({ + host: mail.host, + port: mail.port, + secure: mail.secure, + user: mail.user, + pass: mail.pass, + from: mail.from, + to: parseRecipients(mail.to), + subject: mail.subject, + body: mail.text, + }, { timeoutMs }); + return { ok: true }; + } catch (err) { + return { ok: false, error: formatSmtpError(err, mail.host, mail.port) }; + } + }; +} + /** The real, fully-wired singleton. */ export function createNotificationManager(): NotificationManager { return new NotificationManager({ loadConfig: loadNotificationsConfig, loadChannelIds: (uin) => loadOneBotConfig(uin).notifications?.channelIds ?? [], post: createDefaultPost(), + sendMail: createDefaultSendMail(), now: () => Date.now(), }); } diff --git a/packages/core/src/notifications/smtp.ts b/packages/core/src/notifications/smtp.ts new file mode 100644 index 00000000..4780ead9 --- /dev/null +++ b/packages/core/src/notifications/smtp.ts @@ -0,0 +1,383 @@ +// Minimal SMTP client for notification-channel email. Runtime ships with no +// npm dependencies, so this speaks the protocol over node:net / node:tls +// (EHLO, optional STARTTLS, AUTH PLAIN/LOGIN, DATA). No extra features. + +import net from 'node:net'; +import tls from 'node:tls'; + +const CRLF = '\r\n'; +const DEFAULT_TIMEOUT_MS = 15_000; + +export class SmtpError extends Error { + readonly responseCode?: number; + readonly code?: string; + + constructor(message: string, opts?: { responseCode?: number; code?: string }) { + super(message); + this.name = 'SmtpError'; + this.responseCode = opts?.responseCode; + this.code = opts?.code; + } +} + +export interface SmtpMail { + host: string; + port: number; + secure: boolean; + user?: string; + pass?: string; + from: string; + to: string[]; + subject: string; + body: string; +} + +export interface SendSmtpOptions { + timeoutMs?: number; + /** Defaults true. Tests against a self-signed mock pass false. */ + rejectUnauthorized?: boolean; +} + +export function looksLikeEmail(value: string): boolean { + return /^[^\s<>@]+@[^\s<>@]+$/.test(value); +} + +/** Address from `Name ` or a bare addr; null if neither is usable. */ +export function extractAddress(value: string): string | null { + const trimmed = value.trim(); + if (!trimmed) return null; + const angled = /<([^<>]+)>/.exec(trimmed); + const addr = (angled ? angled[1] : trimmed).trim(); + return looksLikeEmail(addr) ? addr : null; +} + +/** Split a comma / semicolon / newline list and keep unique addresses. */ +export function parseRecipients(value: string): string[] { + const seen = new Set(); + const out: string[] = []; + for (const part of value.split(/[,;\n]+/)) { + const addr = extractAddress(part); + if (!addr) continue; + const key = addr.toLowerCase(); + if (seen.has(key)) continue; + seen.add(key); + out.push(addr); + } + return out; +} + +function encodeHeader(value: string): string { + if (/^[\x20-\x7E]*$/.test(value) && !/[\r\n]/.test(value)) return value; + return `=?UTF-8?B?${Buffer.from(value, 'utf8').toString('base64')}?=`; +} + +function rfc5322Date(d: Date): string { + return d.toUTCString().replace(/GMT$/, '+0000'); +} + +function wrap76(b64: string): string { + return b64.replace(/.{1,76}/g, (line) => `${line}\r\n`).trimEnd(); +} + +function isHtmlBody(body: string): boolean { + return /^\s*`; + const headers = [ + `From: ${mail.from.trim() || (fromAddr ? `<${fromAddr}>` : '')}`, + `To: ${toHeader}`, + `Subject: ${encodeHeader(mail.subject)}`, + `Date: ${rfc5322Date(now)}`, + `Message-ID: ${id}`, + 'MIME-Version: 1.0', + `Content-Type: ${html ? 'text/html' : 'text/plain'}; charset=UTF-8`, + 'Content-Transfer-Encoding: base64', + ]; + const body = wrap76(Buffer.from(mail.body, 'utf8').toString('base64')); + return `${headers.join(CRLF)}${CRLF}${CRLF}${body}${CRLF}`; +} + +interface SmtpReply { + code: number; + lines: string[]; + text: string; +} + +function consumeReply(buf: string): { reply: SmtpReply; rest: string } | null { + let offset = 0; + const lines: string[] = []; + let code = 0; + while (offset < buf.length) { + const nl = buf.indexOf('\n', offset); + if (nl === -1) return null; + const line = buf.slice(offset, nl).replace(/\r$/, ''); + offset = nl + 1; + const m = /^(\d{3})([ -])(.*)$/.exec(line); + if (!m) continue; + code = Number(m[1]); + lines.push(m[3]); + if (m[2] === ' ') { + return { reply: { code, lines, text: lines.join('\n') }, rest: buf.slice(offset) }; + } + } + return null; +} + +type SmtpSock = net.Socket | tls.TLSSocket; + +function parseCapabilities(reply: SmtpReply): { starttls: boolean; auth: Set } { + const auth = new Set(); + let starttls = false; + for (const line of reply.lines) { + const u = line.toUpperCase(); + if (u === 'STARTTLS' || u.startsWith('STARTTLS ')) starttls = true; + if (u.startsWith('AUTH ')) { + for (const mech of u.slice(5).split(/\s+/)) { + if (mech) auth.add(mech); + } + } + } + return { starttls, auth }; +} + +function connectSocket( + host: string, + port: number, + secure: boolean, + timeoutMs: number, + rejectUnauthorized: boolean, +): Promise { + return new Promise((resolve, reject) => { + const sock: SmtpSock = secure + ? tls.connect({ + host, + port, + servername: net.isIP(host) === 0 ? host : undefined, + rejectUnauthorized, + }) + : net.connect({ host, port }); + const fail = (err: Error) => { + sock.destroy(); + reject(err); + }; + sock.setTimeout(timeoutMs); + sock.once('timeout', () => fail(new SmtpError('SMTP connection timed out', { code: 'ETIMEDOUT' }))); + sock.once('error', fail); + sock.once(secure ? 'secureConnect' : 'connect', () => { + sock.removeAllListeners('timeout'); + sock.removeAllListeners('error'); + resolve(sock); + }); + }); +} + +function upgradeTls( + socket: net.Socket, + host: string, + timeoutMs: number, + rejectUnauthorized: boolean, +): Promise { + return new Promise((resolve, reject) => { + const tlsSocket = tls.connect({ + socket, + servername: net.isIP(host) === 0 ? host : undefined, + rejectUnauthorized, + }, () => resolve(tlsSocket)); + tlsSocket.setTimeout(timeoutMs); + tlsSocket.once('timeout', () => { + tlsSocket.destroy(); + reject(new SmtpError('SMTP STARTTLS timed out', { code: 'ETIMEDOUT' })); + }); + tlsSocket.once('error', reject); + }); +} + +class SmtpSession { + private buf = ''; + + constructor(private socket: SmtpSock) {} + + destroy(): void { + this.socket.destroy(); + } + + attachTimeout(timeoutMs: number, onTimeout: () => void): void { + this.socket.setTimeout(timeoutMs); + this.socket.once('timeout', onTimeout); + } + + async read(): Promise { + const ready = consumeReply(this.buf); + if (ready) { + this.buf = ready.rest; + return ready.reply; + } + return new Promise((resolve, reject) => { + const onData = (chunk: Buffer) => { + this.buf += chunk.toString('utf8'); + const got = consumeReply(this.buf); + if (!got) return; + this.buf = got.rest; + cleanup(); + resolve(got.reply); + }; + const onError = (err: Error) => { + cleanup(); + reject(err); + }; + const onClose = () => { + cleanup(); + reject(new SmtpError('SMTP connection closed')); + }; + const cleanup = () => { + this.socket.removeListener('data', onData); + this.socket.removeListener('error', onError); + this.socket.removeListener('close', onClose); + }; + this.socket.on('data', onData); + this.socket.once('error', onError); + this.socket.once('close', onClose); + }); + } + + write(data: string): void { + this.socket.write(data); + } + + async command(line: string, ok: (code: number) => boolean, label?: string): Promise { + this.write(line + CRLF); + const reply = await this.read(); + if (!ok(reply.code)) { + const name = label ?? line.split(' ')[0] ?? 'SMTP'; + throw new SmtpError(`${name} failed: ${reply.code} ${reply.text}`.trim(), { + responseCode: reply.code, + }); + } + return reply; + } + + replaceSocket(next: SmtpSock): void { + this.socket = next; + this.buf = ''; + } +} + +export function formatSmtpError(err: unknown, host: string, port: number): string { + if (err instanceof SmtpError) { + if (err.code === 'ECONNREFUSED' || err.code === 'ENOTFOUND' || err.code === 'ETIMEDOUT') { + return `无法连接 SMTP:${host}:${port}`; + } + if (err.responseCode === 535) return 'SMTP 认证失败'; + return err.message; + } + if (err instanceof Error) { + const code = (err as NodeJS.ErrnoException).code; + if (code === 'ECONNREFUSED' || code === 'ENOTFOUND' || code === 'ETIMEDOUT') { + return `无法连接 SMTP:${host}:${port}`; + } + if (/self-signed|unable to verify/i.test(err.message)) { + return `SMTP 证书不受信任:${host}`; + } + return err.message || '邮件发送失败'; + } + return '邮件发送失败'; +} + +export async function sendSmtpMail(mail: SmtpMail, opts: SendSmtpOptions = {}): Promise { + const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS; + const rejectUnauthorized = opts.rejectUnauthorized ?? true; + const fromAddr = extractAddress(mail.from); + if (!fromAddr) throw new SmtpError('invalid from address'); + if (mail.to.length === 0) throw new SmtpError('no recipients'); + + let sock = await connectSocket(mail.host, mail.port, mail.secure, timeoutMs, rejectUnauthorized); + const session = new SmtpSession(sock); + let finished = false; + const failTimeout = () => { + if (finished) return; + session.destroy(); + }; + session.attachTimeout(timeoutMs, failTimeout); + + try { + const greeting = await session.read(); + if (greeting.code !== 220) { + throw new SmtpError(`SMTP greeting failed: ${greeting.code} ${greeting.text}`.trim(), { + responseCode: greeting.code, + }); + } + + const ehlo = async () => session.command('EHLO [127.0.0.1]', (c) => c === 250); + let caps = parseCapabilities(await ehlo()); + + if (!mail.secure && caps.starttls) { + await session.command('STARTTLS', (c) => c === 220); + const upgraded = await upgradeTls(sock as net.Socket, mail.host, timeoutMs, rejectUnauthorized); + session.replaceSocket(upgraded); + session.attachTimeout(timeoutMs, failTimeout); + sock = upgraded; + caps = parseCapabilities(await ehlo()); + } + + const user = mail.user?.trim() ?? ''; + if (user) { + await authenticate(session, caps.auth, user, mail.pass ?? ''); + } + + await session.command(`MAIL FROM:<${fromAddr}>`, (c) => c === 250); + for (const rcpt of mail.to) { + await session.command(`RCPT TO:<${rcpt}>`, (c) => c === 250 || c === 251); + } + await session.command('DATA', (c) => c === 354); + session.write(dotStuff(buildMimeMessage(mail))); + await session.command('.', (c) => c === 250, 'DATA'); + try { + await session.command('QUIT', (c) => c === 221); + } catch { + // Some relays drop the socket after 250; delivery already succeeded. + } + finished = true; + } catch (err) { + finished = true; + throw err; + } finally { + session.destroy(); + } +} + +async function authenticate( + session: SmtpSession, + mechs: Set, + user: string, + pass: string, +): Promise { + const hasPlain = mechs.has('PLAIN'); + const hasLogin = mechs.has('LOGIN'); + if (hasPlain || !hasLogin) { + try { + const token = Buffer.from(`\0${user}\0${pass}`, 'utf8').toString('base64'); + await session.command(`AUTH PLAIN ${token}`, (c) => c === 235, 'AUTH'); + return; + } catch (err) { + if (hasPlain && !hasLogin) throw err; + if (err instanceof SmtpError && err.responseCode === 535) throw err; + } + } + await loginAuth(session, user, pass); +} + +async function loginAuth(session: SmtpSession, user: string, pass: string): Promise { + await session.command('AUTH LOGIN', (c) => c === 334, 'AUTH'); + await session.command(Buffer.from(user, 'utf8').toString('base64'), (c) => c === 334, 'AUTH'); + await session.command(Buffer.from(pass, 'utf8').toString('base64'), (c) => c === 235, 'AUTH'); +} diff --git a/packages/core/src/webui/backup.ts b/packages/core/src/webui/backup.ts index 8131602b..11c06037 100644 --- a/packages/core/src/webui/backup.ts +++ b/packages/core/src/webui/backup.ts @@ -5,7 +5,7 @@ // // Credentials are gated by a toggle on both export and import. The credential // set is: webui.json (password hash), key.pem (TLS private key), -// notifications.json (webhook URLs may embed secrets), AND every OneBot config +// notifications.json (webhook URLs / SMTP passwords), AND every OneBot config // (onebot.json + per-account onebot_.json) — those carry access tokens, so // a no-credentials backup must NOT include them. // cert.pem is public so it always travels. diff --git a/packages/core/tests/notifications-config.test.ts b/packages/core/tests/notifications-config.test.ts index 13d88cd5..fa401659 100644 --- a/packages/core/tests/notifications-config.test.ts +++ b/packages/core/tests/notifications-config.test.ts @@ -5,6 +5,8 @@ import path from 'path'; import { DEFAULT_BODY_TEMPLATE, DEFAULT_DEBOUNCE_SECONDS, + DEFAULT_EMAIL_BODY_TEMPLATE, + DEFAULT_SUBJECT_TEMPLATE, defaultNotificationsConfig, normalizeNotificationsConfig, renderTemplate, @@ -100,6 +102,7 @@ describe('normalizeNotificationsConfig — total normalize', () => { { id: 'dingtalk', name: 'DingTalk', + type: 'webhook', url: 'https://oapi.dingtalk.com/robot/send', bodyTemplate: '{event}', enabled: true, @@ -132,10 +135,11 @@ describe('normalizeNotificationsConfig — total normalize', () => { expect(channels[0].url).toBe('https://a.com'); }); - it('defaults enabled=true, name→id, and bodyTemplate→default', () => { + it('defaults enabled=true, name→id, type=webhook, and bodyTemplate→default', () => { const { channels } = normalizeNotificationsConfig({ channels: [{ id: 'c1', url: 'https://a.com' }] }); expect(channels[0].enabled).toBe(true); expect(channels[0].name).toBe('c1'); + expect(channels[0].type).toBe('webhook'); expect(channels[0].bodyTemplate).toBe(DEFAULT_BODY_TEMPLATE); expect(channels[0].headers).toBeUndefined(); }); @@ -168,6 +172,92 @@ describe('normalizeNotificationsConfig — total normalize', () => { }); expect(channels[0].headers).toBeUndefined(); }); + + it('keeps an email channel without a webhook url and fills SMTP defaults', () => { + const { channels } = normalizeNotificationsConfig({ + channels: [{ + id: 'ops-mail', + type: 'email', + smtpHost: 'smtp.qq.com', + from: 'SnowLuma ', + to: 'a@example.com; b@example.com, a@example.com', + }], + }); + expect(channels).toEqual([{ + id: 'ops-mail', + name: 'ops-mail', + type: 'email', + url: '', + bodyTemplate: DEFAULT_EMAIL_BODY_TEMPLATE, + enabled: true, + smtpHost: 'smtp.qq.com', + smtpPort: 465, + smtpSecure: true, + from: 'SnowLuma ', + to: 'a@example.com, b@example.com', + subjectTemplate: DEFAULT_SUBJECT_TEMPLATE, + }]); + }); + + it('defaults port 587 when smtpSecure is explicitly false', () => { + const { channels } = normalizeNotificationsConfig({ + channels: [{ + id: 'relay', + type: 'email', + smtpHost: 'relay.internal', + smtpSecure: false, + from: 'bot@internal', + to: 'ops@internal', + }], + }); + expect(channels[0]).toMatchObject({ smtpPort: 587, smtpSecure: false }); + }); + + it('treats port 587 without smtpSecure as STARTTLS (secure=false)', () => { + const { channels } = normalizeNotificationsConfig({ + channels: [{ + id: 'gmail', + type: 'email', + smtpHost: 'smtp.gmail.com', + smtpPort: 587, + from: 'bot@gmail.com', + to: 'ops@gmail.com', + }], + }); + expect(channels[0]).toMatchObject({ smtpPort: 587, smtpSecure: false }); + }); + + it('drops email channels missing host / from / to, and unknown types', () => { + const { channels } = normalizeNotificationsConfig({ + channels: [ + { id: 'no-host', type: 'email', from: 'a@b.com', to: 'c@d.com' }, + { id: 'no-from', type: 'email', smtpHost: 'smtp.example.com', to: 'c@d.com' }, + { id: 'bad-to', type: 'email', smtpHost: 'smtp.example.com', from: 'a@b.com', to: 'not-an-email' }, + { id: 'sms', type: 'sms', url: 'https://a.com' }, + { id: 'ok', type: 'email', smtpHost: 'smtp.example.com', from: 'a@b.com', to: 'c@d.com', smtpUser: 'a@b.com', smtpPass: 'p' }, + ], + }); + expect(channels.map((c) => c.id)).toEqual(['ok']); + expect(channels[0]).toMatchObject({ smtpUser: 'a@b.com', smtpPass: 'p' }); + }); + + it('does not keep webhook-only fields on an email channel', () => { + const { channels } = normalizeNotificationsConfig({ + channels: [{ + id: 'mail', + type: 'email', + url: 'https://should.be.ignored', + headers: { Authorization: 'Bearer x' }, + smtpHost: 'smtp.example.com', + from: 'a@b.com', + to: 'c@d.com', + evil: 'x', + }], + }); + expect(channels[0].url).toBe(''); + expect(channels[0].headers).toBeUndefined(); + expect(channels[0]).not.toHaveProperty('evil'); + }); }); describe('loadNotificationsConfig / saveNotificationsConfig (fs-backed)', () => { diff --git a/packages/core/tests/notifications-manager.test.ts b/packages/core/tests/notifications-manager.test.ts index 1a2b9ded..95eb7263 100644 --- a/packages/core/tests/notifications-manager.test.ts +++ b/packages/core/tests/notifications-manager.test.ts @@ -2,6 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { NotificationManager, selectChannels, + type MailPayload, type NotificationManagerDeps, type PostResult, } from '../src/notifications/manager'; @@ -11,6 +12,7 @@ function ch(over: Partial = {}): NotificationChannel { return { id: 'c1', name: 'C1', + type: 'webhook', url: 'https://hook.example/c1', bodyTemplate: '{event}:{uin}:{nickname}', enabled: true, @@ -18,6 +20,26 @@ function ch(over: Partial = {}): NotificationChannel { }; } +function emailCh(over: Partial = {}): NotificationChannel { + return { + id: 'mail', + name: 'Mail', + type: 'email', + url: '', + bodyTemplate: '{event}:{uin}:{nickname}', + enabled: true, + smtpHost: 'smtp.example.com', + smtpPort: 465, + smtpSecure: true, + smtpUser: 'bot@example.com', + smtpPass: 'secret', + from: 'bot@example.com', + to: 'ops@example.com', + subjectTemplate: '{event} {uin}', + ...over, + }; +} + describe('selectChannels (pure)', () => { it('keeps only enabled channels the UIN opted into, in config order', () => { const channels = [ch({ id: 'a' }), ch({ id: 'b', enabled: false }), ch({ id: 'c' })]; @@ -166,6 +188,82 @@ describe('NotificationManager.testSend', () => { }); }); +describe('NotificationManager — email channels', () => { + it('sends mail instead of POSTing, with rendered subject and body', async () => { + const posts: unknown[] = []; + const mails: MailPayload[] = []; + const mgr = new NotificationManager({ + loadConfig: () => ({ version: 1, debounceSeconds: 30, channels: [emailCh()] }), + loadChannelIds: () => ['mail'], + post: async (url, body) => { + posts.push({ url, body }); + return { ok: true, status: 200 }; + }, + sendMail: async (mail) => { + mails.push(mail); + return { ok: true }; + }, + now: () => 1000, + }); + await mgr.notify('123', 'offline'); + expect(posts).toEqual([]); + expect(mails).toEqual([{ + host: 'smtp.example.com', + port: 465, + secure: true, + user: 'bot@example.com', + pass: 'secret', + from: 'bot@example.com', + to: 'ops@example.com', + subject: 'offline 123', + text: 'offline:123:123', + }]); + }); + + it('records a failed sendMail without calling post', async () => { + const mgr = new NotificationManager({ + loadConfig: () => ({ version: 1, debounceSeconds: 30, channels: [emailCh()] }), + loadChannelIds: () => ['mail'], + post: async () => { + throw new Error('webhook must not run'); + }, + sendMail: async () => ({ ok: false, error: 'SMTP 认证失败' }), + now: () => 1000, + }); + await mgr.notify('123', 'offline'); + expect(mgr.getRecent()[0]).toMatchObject({ ok: false, error: 'SMTP 认证失败', channelId: 'mail' }); + }); + + it('fails closed when sendMail is not wired', async () => { + const mgr = new NotificationManager({ + loadConfig: () => ({ version: 1, debounceSeconds: 30, channels: [emailCh()] }), + loadChannelIds: () => ['mail'], + post: async () => ({ ok: true, status: 200 }), + now: () => 1000, + }); + await mgr.notify('123', 'offline'); + expect(mgr.getRecent()[0]).toMatchObject({ ok: false, error: 'email delivery is not configured' }); + }); + + it('testSend uses sendMail and still skips history', async () => { + const mails: MailPayload[] = []; + const mgr = new NotificationManager({ + loadConfig: () => ({ version: 1, debounceSeconds: 30, channels: [emailCh({ enabled: false })] }), + loadChannelIds: () => [], + post: async () => ({ ok: true, status: 200 }), + sendMail: async (mail) => { + mails.push(mail); + return { ok: true }; + }, + now: () => 1000, + }); + expect(await mgr.testSend('mail')).toMatchObject({ found: true, ok: true }); + expect(mails[0]?.subject).toBe('offline 10000'); + expect(mails[0]?.text).toBe('offline:10000:测试账号'); + expect(mgr.getRecent()).toEqual([]); + }); +}); + describe('NotificationManager — debounce integration (fake timers)', () => { beforeEach(() => vi.useFakeTimers()); afterEach(() => vi.useRealTimers()); diff --git a/packages/core/tests/notifications-smtp.test.ts b/packages/core/tests/notifications-smtp.test.ts new file mode 100644 index 00000000..e82eeccb --- /dev/null +++ b/packages/core/tests/notifications-smtp.test.ts @@ -0,0 +1,289 @@ +import { afterEach, describe, expect, it } from 'vitest'; +import net from 'node:net'; +import tls from 'node:tls'; +import { + buildMimeMessage, + extractAddress, + formatSmtpError, + parseRecipients, + sendSmtpMail, + SmtpError, +} from '../src/notifications/smtp'; + +// Same throwaway pair as webui-tls.test.ts (CN=snowluma-test). +const CERT = `-----BEGIN CERTIFICATE----- +MIIDETCCAfmgAwIBAgIUNiu66PmcO6Do6cUaB92UKD8j3qYwDQYJKoZIhvcNAQEL +BQAwGDEWMBQGA1UEAwwNc25vd2x1bWEtdGVzdDAeFw0yNjA2MTgwNjIwMTZaFw0z +NjA2MTUwNjIwMTZaMBgxFjAUBgNVBAMMDXNub3dsdW1hLXRlc3QwggEiMA0GCSqG +SIb3DQEBAQUAA4IBDwAwggEKAoIBAQCm0sVJhqlG75gOFJVsUJOfR+oqvb9eSq4t +k5QItuwXr85E2mrzuKFnSzVVbi3VqqyN8t4otL11mGll2ANSjusmWN4hzpaOBBdX +bP4UNX/YA7oHId+QKbVicxJgxDE18aPTwaWullyw23LsMsij8T4nLk4eHiOkeRfi +uLinG1COe3gUGkCK4uyyMT4Vz+y+5Oj9dvoXYL/A/KmcNtq7JrX7F7qYnYsJKLZZ +aZeFyIGSE8ihb0k53iyJ3agWY+rMUD+p5J7pgIZzBd5dcZuI+KwixVKZgapG5n5R +ghrnN2ZAQFz13yTRXYmDYy42m4Ue73hMmmt1xVXyf+WVhvrD6pphAgMBAAGjUzBR +MB0GA1UdDgQWBBRW/HP12nj9fYMYNxa3jyqmnUigvTAfBgNVHSMEGDAWgBRW/HP1 +2nj9fYMYNxa3jyqmnUigvTAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBCwUA +A4IBAQCijzVQ/jHNoqu6stvkkigUv2lTKrd1EHcTZLfzwQkmNv/hfY2EMobO/Qxs +FhmITreKFALJ/dUwTt0UTO00LV9whEgr2of4x8wwjZ9wRstY6uyRYBP85QC8+8mZ +zWlcf611HugrmpOWjWfEVmmxdI1m26YWTn52nZFPnJqDWg2+RlLJWl55lVotbXEZ +Fvas4Vcf2KOk0QwBQKvpt0BISeTIQhbT4GnducxSxyoXGeBQOjQNYb/vTpMn4F9U +IAxSsfs9WVoHKXOabK8GV89BCxWoRk4UaSahTq/2Vnbgt86tWibt3lA4y49+XhA2 +6z7n9HgJAUKqhsDrYvZmM7/VZ2d5 +-----END CERTIFICATE----- +`; +const KEY = `-----BEGIN PRIVATE KEY----- +MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCm0sVJhqlG75gO +FJVsUJOfR+oqvb9eSq4tk5QItuwXr85E2mrzuKFnSzVVbi3VqqyN8t4otL11mGll +2ANSjusmWN4hzpaOBBdXbP4UNX/YA7oHId+QKbVicxJgxDE18aPTwaWullyw23Ls +Msij8T4nLk4eHiOkeRfiuLinG1COe3gUGkCK4uyyMT4Vz+y+5Oj9dvoXYL/A/Kmc +Ntq7JrX7F7qYnYsJKLZZaZeFyIGSE8ihb0k53iyJ3agWY+rMUD+p5J7pgIZzBd5d +cZuI+KwixVKZgapG5n5RghrnN2ZAQFz13yTRXYmDYy42m4Ue73hMmmt1xVXyf+WV +hvrD6pphAgMBAAECggEAJ13+u4qhIMHCnrQBzPU42PImEt8DLXOvJcc5PFM6ZJ6S +rRHkAk60HAWV+OqOu2jS3o6NGYsJWJpWaPewVQev+zUmelDfm3TgsztfvBIh8K50 +dGFsef81tB1WnWo++K1kzUBZ4ljOV9f5hz62tWVlFubo/Vd8bsA6wEB6Jskd2fls +ZOO0hJCb/M6IIwe3cWw4sb/YFTTLMUnVHM0aJfnQ/QH+uraRwecJMv118d0YBYVG +DsNmYqrv9TYNBh4P9mKv6/0x8zaKsJZVLAMwHztILHItOXBfxCbSDivGWVUGiDq2 +NxEuBOgxzOelxEYzUzf7B6sjHoEeIL5wIKQbwUbmfwKBgQDZRLhucrMZPw7ous1t +igkO32p1ku7FRxm0/JAskc66oX61KLIYbZFM9N7nTXAEs8ZGhzUkdSgxNcdHWIdK +RI+6pd2FhhcKU1feEohlOHvZTXXEMhm61phWnN391GZXfwMKSpscqsu9kIix2jtw +4YrzKLx82EDDHcLfBh9AtArKywKBgQDEj+7UJp5wuqz9hj+gogXeq4Buv9be1u4u +HCJZMZzLCwVjvoqYw0n1afXP3057v8hQPGsBaxzQpOg7i1lYGGfuZ9T6T8fFrtqw +m/LJLHhMQxeyCEQi1/EoNewvVGSwBJkLOuOs8T2WmMXmOgdHbEYdzkKtT71jst6y +TeJ15hVuAwKBgBMK4t9LTkc4L6ZWOQsQvhp/mmUTq7m+sZIbUMeXP/c7kE9wcauS +btm/3ImJT/gZiZdE4nN/kTY+8GhgafsoZzCEuRWq2vocs+bS2QGGIdS55Uh826R0 +ioWM2igVJaMljq6oO1AX6COFN3XfGraaDgOh3mNS0NpJEXtangKdxRRhAoGAP9SF +t/r6hJz6RDHuQ5mZ0l9bC5vciOy+19ZnCRPlWMIxc9ySYV05jSplmqVndSQoRnX4 +QbOo3dBPYda0orj6Nx8cuFRkCTvo5GUgCFgakJlQ/o1UowQA2g/4rL35HHfBwzXS +bXzBhUADM+owJu9wLYmneWRlmhSh4MEOAz8+QkUCgYAw0fA1Im2/ftrA2Z2IENTi +U4cLXqeUeGJfXjIBklUmXhc4qrd/9V9eEHjackI/JI7Qhp/QfPWMXLudlSrppnNJ ++s3dVevEKosiZbf4qtTtlmR/IifuTKjK5O94KlBT+evxNsL4Hv0b0oTsVNnEfOOl +OUsvSYNSnfvl87tyLIxYLA== +-----END PRIVATE KEY----- +`; + +interface MockOptions { + secure?: boolean; + starttls?: boolean; + mechs?: string; + failAuth?: boolean; +} + +interface MockSmtp { + port: number; + commands: string[]; + data: string; + close: () => Promise; +} + +const closers: Array<() => Promise> = []; +afterEach(async () => { + while (closers.length > 0) { + const close = closers.pop(); + if (close) await close(); + } +}); + +function attachSession( + socket: net.Socket | tls.TLSSocket, + opts: MockOptions, + sink: MockSmtp, + greet = true, +): void { + let buf = ''; + let mode: 'cmd' | 'data' = 'cmd'; + let loginStep = 0; + const write = (s: string) => socket.write(s); + if (greet) write('220 mock ESMTP\r\n'); + socket.on('data', (chunk) => { + buf += chunk.toString('utf8'); + if (mode === 'data') { + const end = buf.indexOf('\r\n.\r\n'); + if (end === -1) return; + sink.data = buf.slice(0, end); + buf = buf.slice(end + 5); + mode = 'cmd'; + write('250 OK\r\n'); + return; + } + while (true) { + const nl = buf.indexOf('\n'); + if (nl === -1) break; + const line = buf.slice(0, nl).replace(/\r$/, ''); + buf = buf.slice(nl + 1); + if (loginStep > 0 && /^[A-Za-z0-9+/=]+$/.test(line)) { + sink.commands.push('(b64)'); + } else if (line.startsWith('AUTH PLAIN ')) { + sink.commands.push('AUTH PLAIN'); + } else { + sink.commands.push(line); + } + if (line.toUpperCase().startsWith('EHLO')) { + const extra = opts.starttls ? '250-STARTTLS\r\n' : ''; + write(`250-mock\r\n${extra}250 AUTH ${opts.mechs ?? 'PLAIN LOGIN'}\r\n`); + } else if (line.toUpperCase() === 'STARTTLS' && opts.starttls && socket instanceof net.Socket) { + write('220 Go ahead\r\n'); + socket.removeAllListeners('data'); + const tlsSock = new tls.TLSSocket(socket, { isServer: true, cert: CERT, key: KEY }); + attachSession(tlsSock, { ...opts, starttls: false }, sink, false); + return; + } else if (line.toUpperCase() === 'AUTH LOGIN') { + loginStep = 1; + write('334 VXNlcm5hbWU6\r\n'); + } else if (line.toUpperCase().startsWith('AUTH PLAIN')) { + write(opts.failAuth ? '535 5.7.8 auth failed\r\n' : '235 2.7.0 OK\r\n'); + } else if (loginStep === 1 && /^[A-Za-z0-9+/=]+$/.test(line)) { + loginStep = 2; + write('334 UGFzc3dvcmQ6\r\n'); + } else if (loginStep === 2 && /^[A-Za-z0-9+/=]+$/.test(line)) { + loginStep = 0; + write(opts.failAuth ? '535 5.7.8 auth failed\r\n' : '235 2.7.0 OK\r\n'); + } else if (line.toUpperCase().startsWith('MAIL FROM:')) { + write('250 OK\r\n'); + } else if (line.toUpperCase().startsWith('RCPT TO:')) { + write('250 OK\r\n'); + } else if (line.toUpperCase() === 'DATA') { + mode = 'data'; + write('354 End data with .\r\n'); + } else if (line.toUpperCase() === 'QUIT') { + write('221 bye\r\n'); + socket.end(); + } else { + write('250 OK\r\n'); + } + } + }); +} + +function listenMock(opts: MockOptions = {}): Promise { + return new Promise((resolve, reject) => { + const sink: MockSmtp = { port: 0, commands: [], data: '', close: async () => undefined }; + const onConn = (socket: net.Socket | tls.TLSSocket) => attachSession(socket, opts, sink); + const server = opts.secure + ? tls.createServer({ cert: CERT, key: KEY }, onConn) + : net.createServer(onConn); + server.once('error', reject); + server.listen(0, '127.0.0.1', () => { + const addr = server.address(); + if (!addr || typeof addr === 'string') { + reject(new Error('no port')); + return; + } + sink.port = addr.port; + sink.close = () => new Promise((res) => server.close(() => res())); + closers.push(sink.close); + resolve(sink); + }); + }); +} + +describe('address helpers', () => { + it('extracts a bare or angled address and rejects junk', () => { + expect(extractAddress('bot@qq.com')).toBe('bot@qq.com'); + expect(extractAddress('SnowLuma ')).toBe('bot@qq.com'); + expect(extractAddress('not-an-email')).toBeNull(); + expect(extractAddress('')).toBeNull(); + }); + + it('parses unique recipients from mixed separators', () => { + expect(parseRecipients('a@x.com; b@x.com, a@x.com\nc@x.com')).toEqual([ + 'a@x.com', + 'b@x.com', + 'c@x.com', + ]); + expect(parseRecipients('nope, also nope')).toEqual([]); + }); +}); + +describe('buildMimeMessage', () => { + const base = { + host: 'smtp.example.com', + port: 465, + secure: true, + from: 'SnowLuma ', + to: ['ops@example.com'], + subject: '账号offline:Alice (1)', + body: 'hello', + }; + + it('encodes a non-ASCII subject and a plain body as base64', () => { + const raw = buildMimeMessage(base, new Date('2026-09-16T01:00:00Z')); + expect(raw).toContain('Content-Type: text/plain; charset=UTF-8'); + expect(raw).toContain('Subject: =?UTF-8?B?'); + expect(raw).toContain(Buffer.from('hello', 'utf8').toString('base64')); + expect(raw).toContain('From: SnowLuma '); + }); + + it('marks a body that starts with < as HTML', () => { + const raw = buildMimeMessage({ ...base, body: '

hi

' }); + expect(raw).toContain('Content-Type: text/html; charset=UTF-8'); + }); +}); + +describe('formatSmtpError', () => { + it('maps connect failures and 535 without leaking the exception class name only', () => { + expect(formatSmtpError(new SmtpError('x', { code: 'ECONNREFUSED' }), 'smtp.qq.com', 465)) + .toBe('无法连接 SMTP:smtp.qq.com:465'); + expect(formatSmtpError(new SmtpError('AUTH failed: 535', { responseCode: 535 }), 'h', 25)) + .toBe('SMTP 认证失败'); + expect(formatSmtpError(new SmtpError('MAIL FROM failed: 550 denied', { responseCode: 550 }), 'h', 25)) + .toBe('MAIL FROM failed: 550 denied'); + }); +}); + +describe('sendSmtpMail — live mock', () => { + const mail = { + host: '127.0.0.1', + from: 'bot@example.com', + to: ['ops@example.com'], + subject: 'offline', + body: '账号下线', + user: 'bot@example.com', + pass: 'secret', + }; + + it('delivers over AUTH PLAIN on a plaintext socket', async () => { + const mock = await listenMock({ mechs: 'PLAIN' }); + await sendSmtpMail({ ...mail, port: mock.port, secure: false }); + expect(mock.commands).toContain('AUTH PLAIN'); + expect(mock.commands.some((c) => c.startsWith('MAIL FROM:'))).toBe(true); + expect(mock.commands.some((c) => c.startsWith('RCPT TO:'))).toBe(true); + expect(mock.data).toContain('Subject: offline'); + expect(mock.data).toContain(Buffer.from('账号下线', 'utf8').toString('base64')); + expect(mock.commands.join('\n')).not.toContain('secret'); + }); + + it('falls back to AUTH LOGIN when PLAIN is not advertised', async () => { + const mock = await listenMock({ mechs: 'LOGIN' }); + await sendSmtpMail({ ...mail, port: mock.port, secure: false }); + expect(mock.commands).toContain('AUTH LOGIN'); + expect(mock.data).toContain('Subject: offline'); + }); + + it('rejects 535 without sending DATA', async () => { + const mock = await listenMock({ mechs: 'PLAIN', failAuth: true }); + await expect(sendSmtpMail({ ...mail, port: mock.port, secure: false })) + .rejects.toMatchObject({ name: 'SmtpError', responseCode: 535 }); + expect(mock.data).toBe(''); + }); + + it('upgrades via STARTTLS then authenticates', async () => { + const mock = await listenMock({ starttls: true, mechs: 'PLAIN' }); + await sendSmtpMail( + { ...mail, port: mock.port, secure: false }, + { rejectUnauthorized: false }, + ); + expect(mock.commands).toContain('STARTTLS'); + expect(mock.commands).toContain('AUTH PLAIN'); + expect(mock.data).toContain('Subject: offline'); + }); + + it('speaks implicit TLS when secure=true', async () => { + const mock = await listenMock({ secure: true, mechs: 'PLAIN' }); + await sendSmtpMail( + { ...mail, port: mock.port, secure: true }, + { rejectUnauthorized: false }, + ); + expect(mock.commands).toContain('AUTH PLAIN'); + expect(mock.data).toContain('Subject: offline'); + }); +}); diff --git a/packages/webui/src/components/config/notification-opt-in.tsx b/packages/webui/src/components/config/notification-opt-in.tsx index a68e93ba..62952439 100644 --- a/packages/webui/src/components/config/notification-opt-in.tsx +++ b/packages/webui/src/components/config/notification-opt-in.tsx @@ -82,7 +82,10 @@ export function NotificationOptIn({ selectedIds, onChange }: NotificationOptInPr const list = channels ?? []; const q = query.trim().toLowerCase(); if (!q) return list; - return list.filter((c) => (c.name || c.id).toLowerCase().includes(q) || c.url.toLowerCase().includes(q)); + return list.filter((c) => { + const hay = [c.name, c.id, c.url, c.smtpHost, c.to, c.from].filter(Boolean).join(' ').toLowerCase(); + return hay.includes(q); + }); }, [channels, query]); const total = channels?.length ?? 0; @@ -217,7 +220,9 @@ export function NotificationOptIn({ selectedIds, onChange }: NotificationOptInPr (已全局禁用) )} -

{ch.url}

+

+ {ch.type === 'email' ? (ch.to || ch.smtpHost || '邮件') : ch.url} +

@]+@[^\s<>@]+$/.test(value.trim()) + || /<[^<>@\s]+@[^<>@\s]+>/.test(value); +} + +function hasRecipient(value: string): boolean { + return value.split(/[,;\n]+/).some((part) => looksLikeEmail(part)); +} + +export const DEFAULT_WEBHOOK_BODY = `{ + "title": "账号状态通知:{event}", + "desp": "您的账号状态发生了改变。\\n\\n**昵称**:{nickname}\\n**QQ号**:{uin}\\n**当前状态**:{event}\\n**时间**:{time}" +}`; + +export const DEFAULT_EMAIL_BODY = `账号状态发生了改变。 + +昵称:{nickname} +QQ号:{uin} +当前状态:{event} +时间:{time}`; + +export const DEFAULT_EMAIL_SUBJECT = '账号{event}:{nickname} ({uin})'; + +export function applyType(draft: NotificationChannel, type: NotificationChannelType): NotificationChannel { + if (type === notificationChannelType(draft)) return { ...draft, type }; + if (type === 'email') { + const keepBody = draft.bodyTemplate && draft.bodyTemplate !== DEFAULT_WEBHOOK_BODY; + return { + ...draft, + type, + url: '', + headers: undefined, + smtpHost: draft.smtpHost ?? '', + smtpPort: draft.smtpPort ?? 465, + smtpSecure: draft.smtpSecure ?? true, + smtpUser: draft.smtpUser ?? '', + smtpPass: draft.smtpPass ?? '', + from: draft.from ?? '', + to: draft.to ?? '', + subjectTemplate: draft.subjectTemplate || DEFAULT_EMAIL_SUBJECT, + bodyTemplate: keepBody ? draft.bodyTemplate : DEFAULT_EMAIL_BODY, + }; + } + const keepBody = draft.bodyTemplate && draft.bodyTemplate !== DEFAULT_EMAIL_BODY; + return { + id: draft.id, + name: draft.name, + type: 'webhook', + url: draft.url, + bodyTemplate: keepBody ? draft.bodyTemplate : DEFAULT_WEBHOOK_BODY, + enabled: draft.enabled, + }; +} + +export function toChannel(draft: NotificationChannel, headerRows: HeaderRow[]): NotificationChannel { + const id = draft.id.trim(); + const name = draft.name.trim(); + const enabled = draft.enabled; + if (notificationChannelType(draft) === 'email') { + return { + id, + name, + type: 'email', + url: '', + bodyTemplate: draft.bodyTemplate, + enabled, + smtpHost: draft.smtpHost?.trim() ?? '', + smtpPort: draft.smtpPort ?? 465, + smtpSecure: draft.smtpSecure ?? true, + smtpUser: draft.smtpUser?.trim() || undefined, + smtpPass: draft.smtpPass || undefined, + from: draft.from?.trim() ?? '', + to: draft.to?.trim() ?? '', + subjectTemplate: draft.subjectTemplate?.trim() || DEFAULT_EMAIL_SUBJECT, + }; + } + return { + id, + name, + type: 'webhook', + url: draft.url.trim(), + bodyTemplate: draft.bodyTemplate, + enabled, + headers: rowsToHeaders(headerRows), + }; +} + interface NotificationChannelDialogProps { open: boolean; onOpenChange: (open: boolean) => void; @@ -58,20 +151,35 @@ interface NotificationChannelDialogProps { export function NotificationChannelDialog(props: NotificationChannelDialogProps) { const { open, onOpenChange, isEdit, initial, otherIds, onSubmit } = props; // Parent unmounts on close, so each open re-seeds via lazy init. - const [draft, setDraft] = useState(initial); + const [draft, setDraft] = useState(() => ({ + ...initial, + type: notificationChannelType(initial), + })); const [headerRows, setHeaderRows] = useState(() => headersToRows(initial.headers)); + const [showPass, setShowPass] = useState(false); + const reduce = useTheme().appearance.disableMotion; const patch = (p: Partial) => setDraft({ ...draft, ...p }); const patchHeader = (index: number, p: Partial) => { setHeaderRows(headerRows.map((row, i) => (i === index ? { ...row, ...p } : row))); }; + const type = notificationChannelType(draft); const id = draft.id.trim(); const idBlank = id.length === 0; const idBad = !idBlank && (!CHANNEL_ID_RE.test(id) || id.length > 64); const idDup = !idBlank && otherIds.includes(id); const urlBlank = draft.url.trim().length === 0; const urlBad = !urlBlank && !isHttpUrl(draft.url); - const canSave = !idBlank && !idBad && !idDup && !urlBlank && !urlBad; + const hostBlank = !(draft.smtpHost ?? '').trim(); + const fromBlank = !(draft.from ?? '').trim(); + const fromBad = !fromBlank && !looksLikeEmail(draft.from ?? ''); + const toBlank = !(draft.to ?? '').trim(); + const toBad = !toBlank && !hasRecipient(draft.to ?? ''); + const port = draft.smtpPort ?? 465; + const portBad = !Number.isInteger(port) || port < 1 || port > 65535; + const canSave = type === 'email' + ? !idBlank && !idBad && !idDup && !hostBlank && !fromBlank && !fromBad && !toBlank && !toBad && !portBad + : !idBlank && !idBad && !idDup && !urlBlank && !urlBad; const idError = idBlank ? '请填写渠道 ID' @@ -81,15 +189,22 @@ export function NotificationChannelDialog(props: NotificationChannelDialogProps) ? 'ID 与其它渠道重复' : undefined; const urlError = urlBlank ? '请填写 Webhook URL' : urlBad ? '必须是 http(s) 地址' : undefined; + const hostError = hostBlank ? '请填写 SMTP 主机' : undefined; + const fromError = fromBlank ? '请填写发件人' : fromBad ? '必须是邮箱地址' : undefined; + const toError = toBlank ? '请填写收件人' : toBad ? '至少填写一个邮箱' : undefined; + const portError = portBad ? '端口 1–65535' : undefined; return ( onOpenChange(false)} title={isEdit ? '编辑渠道' : '新建渠道'} - description="账号上线 / 下线时向该 Webhook POST 一条渲染后的通知。" + description={type === 'email' + ? '账号上线 / 下线时向该邮箱发送一封渲染后的通知。' + : '账号上线 / 下线时向该 Webhook POST 一条渲染后的通知。'} closeLabel="关闭渠道编辑弹窗" maxWidth={576} + maxHeight="min(86vh, 780px)" footer={( <> + ))} + +
patch({ name: v })} />
- patch({ url: v })} - /> + {type === 'webhook' ? ( + <> + patch({ url: v })} + /> -
-
- - -
-
- {headerRows.map((row, i) => ( -
- patchHeader(i, { name: e.target.value })} - className="font-mono text-xs" - /> - patchHeader(i, { value: e.target.value })} - className="font-mono text-xs" - /> +
+
+
- ))} -
-

- 可选。用于飞书等需要鉴权头的 Webhook;默认仍带 JSON Content-Type。 -

-
+
+ {headerRows.map((row, i) => ( +
+ patchHeader(i, { name: e.target.value })} + className="font-mono text-xs" + /> + patchHeader(i, { value: e.target.value })} + className="font-mono text-xs" + /> + +
+ ))} +
+

+ 可选。用于飞书等需要鉴权头的 Webhook;默认仍带 JSON Content-Type。 +

+
+ + ) : ( + <> +
+ patch({ smtpHost: v })} + /> + { + const n = Math.trunc(Number(v)); + if (!Number.isFinite(n)) { + patch({ smtpPort: 465 }); + return; + } + patch({ + smtpPort: n, + smtpSecure: n === 465 ? true : n === 587 ? false : draft.smtpSecure, + }); + }} + /> +
+ +
+ patch({ smtpUser: v })} + /> +
+ +
+ patch({ smtpPass: e.target.value })} + className="pr-11 font-mono text-xs" + /> + +
+
+
+ +
+
+ +

+ 465 通常开启;587 先明文再 STARTTLS,请关掉此项。 +

+
+ patch({ smtpSecure: v })} + ariaLabel="隐式 TLS" + /> +
+ +
+ patch({ from: v })} + /> + patch({ to: v })} + /> +
+ + patch({ subjectTemplate: v })} + /> + + )}
- +