feat(notifications): deliver online/offline alerts over SMTP

Fixes #459
This commit is contained in:
DrSmoothl committed 2026-09-16 10:36:04 +08:00
1 parent 3cd35a76dd
commit f2d58d2f79
13 files changed
+1600 -109

No files matched your search

+119 -4
View File
@@ -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<string, string>;
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<string, string> | undefined {
if (!isObject(value)) return undefined;
const out: Record<string, string> = {};
@@ -147,17 +186,93 @@ function normalizeHeaders(value: unknown): Record<string, string> | 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<string, unknown>,
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),
+77 -23
View File
@@ -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<string, string>) => Promise<PostResult>;
/** SMTP delivery — optional so webhook-only tests stay lean. */
sendMail?: (mail: MailPayload) => Promise<PostResult>;
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<void> {
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<string, string>): Promise<PostResult> {
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<PostResult & { found: boolean }> {
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<NotificationManagerDeps['sendMail']> {
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(),
});
}
+383
View File
@@ -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 <user@host>` 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<string>();
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*</.test(body);
}
function dotStuff(payload: string): string {
return payload.replace(/^\./gm, '..');
}
/** Build a single-part MIME message (plain or HTML). Exported for tests. */
export function buildMimeMessage(mail: SmtpMail, now = new Date()): string {
const fromAddr = extractAddress(mail.from);
const toHeader = mail.to.join(', ');
const html = isHtmlBody(mail.body);
const id = `<${now.getTime()}.${Math.random().toString(36).slice(2, 10)}@snowluma>`;
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<string> } {
const auth = new Set<string>();
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<SmtpSock> {
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<tls.TLSSocket> {
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<SmtpReply> {
const ready = consumeReply(this.buf);
if (ready) {
this.buf = ready.rest;
return ready.reply;
}
return new Promise<SmtpReply>((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<SmtpReply> {
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<void> {
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<string>,
user: string,
pass: string,
): Promise<void> {
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<void> {
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');
}
+1 -1
View File
@@ -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_<uin>.json) — those carry access tokens, so
// a no-credentials backup must NOT include them.
// cert.pem is public so it always travels.
@@ -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 <[email protected]>',
to: '[email protected]; [email protected], [email protected]',
}],
});
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 <[email protected]>',
to: '[email protected], [email protected]',
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: '[email protected]',
to: '[email protected]',
}],
});
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: '[email protected]', to: '[email protected]' },
{ id: 'no-from', type: 'email', smtpHost: 'smtp.example.com', to: '[email protected]' },
{ id: 'bad-to', type: 'email', smtpHost: 'smtp.example.com', from: '[email protected]', to: 'not-an-email' },
{ id: 'sms', type: 'sms', url: 'https://a.com' },
{ id: 'ok', type: 'email', smtpHost: 'smtp.example.com', from: '[email protected]', to: '[email protected]', smtpUser: '[email protected]', smtpPass: 'p' },
],
});
expect(channels.map((c) => c.id)).toEqual(['ok']);
expect(channels[0]).toMatchObject({ smtpUser: '[email protected]', 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: '[email protected]',
to: '[email protected]',
evil: 'x',
}],
});
expect(channels[0].url).toBe('');
expect(channels[0].headers).toBeUndefined();
expect(channels[0]).not.toHaveProperty('evil');
});
});
describe('loadNotificationsConfig / saveNotificationsConfig (fs-backed)', () => {
@@ -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> = {}): 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> = {}): NotificationChannel {
};
}
function emailCh(over: Partial<NotificationChannel> = {}): NotificationChannel {
return {
id: 'mail',
name: 'Mail',
type: 'email',
url: '',
bodyTemplate: '{event}:{uin}:{nickname}',
enabled: true,
smtpHost: 'smtp.example.com',
smtpPort: 465,
smtpSecure: true,
smtpUser: '[email protected]',
smtpPass: 'secret',
from: '[email protected]',
to: '[email protected]',
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: '[email protected]',
pass: 'secret',
from: '[email protected]',
to: '[email protected]',
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());
@@ -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<void>;
}
const closers: Array<() => Promise<void>> = [];
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 <CR><LF>.<CR><LF>\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<MockSmtp> {
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('[email protected]')).toBe('[email protected]');
expect(extractAddress('SnowLuma <[email protected]>')).toBe('[email protected]');
expect(extractAddress('not-an-email')).toBeNull();
expect(extractAddress('')).toBeNull();
});
it('parses unique recipients from mixed separators', () => {
expect(parseRecipients('[email protected]; [email protected], [email protected]\[email protected]')).toEqual([
'[email protected]',
'[email protected]',
'[email protected]',
]);
expect(parseRecipients('nope, also nope')).toEqual([]);
});
});
describe('buildMimeMessage', () => {
const base = {
host: 'smtp.example.com',
port: 465,
secure: true,
from: 'SnowLuma <[email protected]>',
to: ['[email protected]'],
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 <[email protected]>');
});
it('marks a body that starts with < as HTML', () => {
const raw = buildMimeMessage({ ...base, body: '<p>hi</p>' });
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: '[email protected]',
to: ['[email protected]'],
subject: 'offline',
body: '账号下线',
user: '[email protected]',
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:<[email protected]>'))).toBe(true);
expect(mock.commands.some((c) => c.startsWith('RCPT TO:<[email protected]>'))).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');
});
});
@@ -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
<span className="shrink-0 text-micro text-muted-foreground">(已全局禁用)</span>
)}
</div>
<p className="truncate text-meta text-muted-foreground">{ch.url}</p>
<p className="truncate text-meta text-muted-foreground">
{ch.type === 'email' ? (ch.to || ch.smtpHost || '邮件') : ch.url}
</p>
</div>
<ToggleSwitch
// Globally-disabled channel: lock the switch and force it off
@@ -8,10 +8,16 @@ import { Modal } from '@/components/interior/modal';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { PasswordVisibilityIcon } from '@/components/ui/password-visibility-icon';
import { Textarea } from '@/components/ui/textarea';
import { ToggleSwitch } from '@/components/ui/toggle-switch';
import { useTheme } from '@/contexts/ThemeContext';
import { cn } from '@/lib/utils';
import type { NotificationChannel } from '@/types';
import {
notificationChannelType,
type NotificationChannel,
type NotificationChannelType,
} from '@/types';
interface HeaderRow {
name: string;
@@ -44,6 +50,93 @@ function isHttpUrl(u: string): boolean {
}
}
function looksLikeEmail(value: string): boolean {
return /^[^\s<>@]+@[^\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<NotificationChannel>(initial);
const [draft, setDraft] = useState<NotificationChannel>(() => ({
...initial,
type: notificationChannelType(initial),
}));
const [headerRows, setHeaderRows] = useState<HeaderRow[]>(() => headersToRows(initial.headers));
const [showPass, setShowPass] = useState(false);
const reduce = useTheme().appearance.disableMotion;
const patch = (p: Partial<NotificationChannel>) => setDraft({ ...draft, ...p });
const patchHeader = (index: number, p: Partial<HeaderRow>) => {
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 (
<Modal
open={open}
onClose={() => onOpenChange(false)}
title={isEdit ? '编辑渠道' : '新建渠道'}
description="账号上线 / 下线时向该 Webhook POST 一条渲染后的通知。"
description={type === 'email'
? '账号上线 / 下线时向该邮箱发送一封渲染后的通知。'
: '账号上线 / 下线时向该 Webhook POST 一条渲染后的通知。'}
closeLabel="关闭渠道编辑弹窗"
maxWidth={576}
maxHeight="min(86vh, 780px)"
footer={(
<>
<Button variant="outline" onClick={() => onOpenChange(false)}>
@@ -98,13 +213,7 @@ export function NotificationChannelDialog(props: NotificationChannelDialogProps)
<Button
disabled={!canSave}
onClick={() => {
onSubmit({
...draft,
id,
name: draft.name.trim(),
url: draft.url.trim(),
headers: rowsToHeaders(headerRows),
});
onSubmit(toChannel(draft, headerRows));
onOpenChange(false);
}}
>
@@ -114,6 +223,28 @@ export function NotificationChannelDialog(props: NotificationChannelDialogProps)
)}
>
<div className="flex flex-col gap-3">
<div className="grid grid-cols-2 gap-1 rounded-lg border bg-muted/40 p-1">
{([
['webhook', 'Webhook'],
['email', '邮件'],
] as const).map(([value, label]) => (
<button
key={value}
type="button"
aria-pressed={type === value}
onClick={() => setDraft(applyType(draft, value))}
className={cn(
'rounded-md px-3 py-1.5 text-sm font-medium transition-colors',
type === value
? 'bg-background text-foreground shadow-sm'
: 'text-muted-foreground hover:text-foreground',
)}
>
{label}
</button>
))}
</div>
<div className="grid gap-3 sm:grid-cols-2">
<Field
label="渠道 ID"
@@ -126,77 +257,183 @@ export function NotificationChannelDialog(props: NotificationChannelDialogProps)
/>
<Field
label="显示名"
placeholder="钉钉群机器人"
placeholder={type === 'email' ? '运维邮箱' : '钉钉群机器人'}
value={draft.name}
onChange={(v) => patch({ name: v })}
/>
</div>
<Field
label="Webhook URL"
type="url"
placeholder="https://oapi.dingtalk.com/robot/send?access_token=…"
value={draft.url}
error={urlError}
onChange={(v) => patch({ url: v })}
/>
{type === 'webhook' ? (
<>
<Field
label="Webhook URL"
type="url"
placeholder="https://oapi.dingtalk.com/robot/send?access_token=…"
value={draft.url}
error={urlError}
onChange={(v) => patch({ url: v })}
/>
<div className="flex flex-col gap-1.5">
<div className="flex items-center justify-between gap-2">
<Label>请求头</Label>
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => setHeaderRows([...headerRows, { name: '', value: '' }])}
>
<Plus className="size-3.5" />
添加
</Button>
</div>
<div className="flex flex-col gap-2">
{headerRows.map((row, i) => (
<div key={i} className="flex items-center gap-2">
<Input
value={row.name}
placeholder="Authorization"
spellCheck={false}
onChange={(e) => patchHeader(i, { name: e.target.value })}
className="font-mono text-xs"
/>
<Input
value={row.value}
placeholder="Bearer …"
spellCheck={false}
onChange={(e) => patchHeader(i, { value: e.target.value })}
className="font-mono text-xs"
/>
<div className="flex flex-col gap-1.5">
<div className="flex items-center justify-between gap-2">
<Label>请求头</Label>
<Button
type="button"
variant="ghost"
size="icon-sm"
aria-label="删除请求头"
onClick={() => {
const next = headerRows.filter((_, idx) => idx !== i);
setHeaderRows(next.length > 0 ? next : [{ name: '', value: '' }]);
}}
className="shrink-0 text-muted-foreground hover:text-foreground"
size="sm"
onClick={() => setHeaderRows([...headerRows, { name: '', value: '' }])}
>
<Trash2 className="size-3.5" />
<Plus className="size-3.5" />
添加
</Button>
</div>
))}
</div>
<p className="text-xs leading-relaxed text-muted-foreground">
可选。用于飞书等需要鉴权头的 Webhook;默认仍带 JSON Content-Type。
</p>
</div>
<div className="flex flex-col gap-2">
{headerRows.map((row, i) => (
<div key={i} className="flex items-center gap-2">
<Input
value={row.name}
placeholder="Authorization"
spellCheck={false}
onChange={(e) => patchHeader(i, { name: e.target.value })}
className="font-mono text-xs"
/>
<Input
value={row.value}
placeholder="Bearer …"
spellCheck={false}
onChange={(e) => patchHeader(i, { value: e.target.value })}
className="font-mono text-xs"
/>
<Button
type="button"
variant="ghost"
size="icon-sm"
aria-label="删除请求头"
onClick={() => {
const next = headerRows.filter((_, idx) => idx !== i);
setHeaderRows(next.length > 0 ? next : [{ name: '', value: '' }]);
}}
className="shrink-0 text-muted-foreground hover:text-foreground"
>
<Trash2 className="size-3.5" />
</Button>
</div>
))}
</div>
<p className="text-xs leading-relaxed text-muted-foreground">
可选。用于飞书等需要鉴权头的 Webhook;默认仍带 JSON Content-Type。
</p>
</div>
</>
) : (
<>
<div className="grid gap-3 sm:grid-cols-[1fr_7rem]">
<Field
label="SMTP 主机"
placeholder="smtp.qq.com"
value={draft.smtpHost ?? ''}
error={hostError}
onChange={(v) => patch({ smtpHost: v })}
/>
<Field
label="端口"
type="number"
placeholder="465"
value={String(draft.smtpPort ?? 465)}
error={portError}
onChange={(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,
});
}}
/>
</div>
<div className="grid gap-3 sm:grid-cols-2">
<Field
label="SMTP 用户名"
placeholder="[email protected]"
value={draft.smtpUser ?? ''}
hint="部分内网中继可不填"
onChange={(v) => patch({ smtpUser: v })}
/>
<div className="flex flex-col gap-1.5">
<Label>SMTP 密码</Label>
<div className="relative">
<Input
type={showPass ? 'text' : 'password'}
value={draft.smtpPass ?? ''}
autoComplete="new-password"
spellCheck={false}
placeholder="授权码 / 密码"
onChange={(e) => patch({ smtpPass: e.target.value })}
className="pr-11 font-mono text-xs"
/>
<button
type="button"
onClick={() => setShowPass((v) => !v)}
className="absolute right-1.5 top-1/2 flex size-8 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground"
tabIndex={-1}
aria-label={showPass ? '隐藏密码' : '显示密码'}
>
<PasswordVisibilityIcon visible={showPass} reduceMotion={reduce} />
</button>
</div>
</div>
</div>
<div className="flex items-center justify-between rounded-lg border bg-card/40 p-3">
<div className="min-w-0">
<Label className="text-sm">隐式 TLS</Label>
<p className="mt-1 text-xs leading-relaxed text-muted-foreground">
465 通常开启;587 先明文再 STARTTLS,请关掉此项。
</p>
</div>
<ToggleSwitch
value={draft.smtpSecure ?? true}
onChange={(v) => patch({ smtpSecure: v })}
ariaLabel="隐式 TLS"
/>
</div>
<div className="grid gap-3 sm:grid-cols-2">
<Field
label="发件人"
placeholder="SnowLuma <[email protected]>"
value={draft.from ?? ''}
error={fromError}
onChange={(v) => patch({ from: v })}
/>
<Field
label="收件人"
placeholder="[email protected], [email protected]"
value={draft.to ?? ''}
error={toError}
hint="多个地址用逗号或分号分隔"
onChange={(v) => patch({ to: v })}
/>
</div>
<Field
label="主题模板"
placeholder={DEFAULT_EMAIL_SUBJECT}
value={draft.subjectTemplate ?? DEFAULT_EMAIL_SUBJECT}
onChange={(v) => patch({ subjectTemplate: v })}
/>
</>
)}
<div className="flex flex-col gap-1.5">
<Label>Body 模板</Label>
<Label>{type === 'email' ? '正文模板' : 'Body 模板'}</Label>
<Textarea
value={draft.bodyTemplate}
rows={3}
rows={type === 'email' ? 6 : 3}
spellCheck={false}
onChange={(e) => patch({ bodyTemplate: e.target.value })}
className="font-mono text-xs leading-relaxed"
@@ -204,6 +441,7 @@ export function NotificationChannelDialog(props: NotificationChannelDialogProps)
<p className="text-xs leading-relaxed text-muted-foreground">
变量:<code className="font-mono">{'{uin}'}</code> <code className="font-mono">{'{nickname}'}</code>{' '}
<code className="font-mono">{'{event}'}</code>(offline/online) <code className="font-mono">{'{time}'}</code>
{type === 'email' ? '。正文以 < 开头时按 HTML 发送。' : ''}
</p>
</div>
@@ -226,7 +464,7 @@ interface FieldProps {
value: string;
onChange: (v: string) => void;
placeholder?: string;
type?: 'text' | 'url';
type?: 'text' | 'url' | 'number';
error?: string;
hint?: string;
disabled?: boolean;
@@ -16,20 +16,15 @@ import { useApi } from '@/lib/api';
import { useFlashMessage } from '@/hooks/use-flash-message';
import { useTheme } from '@/contexts/ThemeContext';
import { cn } from '@/lib/utils';
import type { NotificationChannel, NotificationsConfig } from '@/types';
import { NotificationChannelDialog } from './notification-channel-dialog';
const DEFAULT_TEMPLATE = `{
"title": "账号状态通知:{event}",
"desp": "您的账号状态发生了改变。\\n\\n**昵称**:{nickname}\\n**QQ号**:{uin}\\n**当前状态**:{event}\\n**时间**:{time}"
}`;
import { notificationChannelType, type NotificationChannel, type NotificationsConfig } from '@/types';
import { DEFAULT_WEBHOOK_BODY, NotificationChannelDialog } from './notification-channel-dialog';
/** A fresh channel with a non-colliding default id. */
function blankChannel(existing: NotificationChannel[]): NotificationChannel {
const used = new Set(existing.map((c) => c.id));
let n = existing.length + 1;
while (used.has(`channel-${n}`)) n += 1;
return { id: `channel-${n}`, name: '', url: '', bodyTemplate: DEFAULT_TEMPLATE, enabled: true };
return { id: `channel-${n}`, name: '', type: 'webhook', url: '', bodyTemplate: DEFAULT_WEBHOOK_BODY, enabled: true };
}
interface DialogState {
@@ -200,7 +195,7 @@ export function NotificationsPanel() {
<div className="flex items-start gap-2 text-xs leading-relaxed text-muted-foreground">
<Bell className="mt-0.5 size-3.5 shrink-0" />
<p>
账号上线 / 下线时向启用的渠道 POST 一条通知(机械转发,仅去抖防刷屏)。渠道在此全局定义,每个账号在其「配置」页勾选启用哪些。
账号上线 / 下线时向启用的渠道发送通知(Webhook POST 或邮件,仅去抖防刷屏)。渠道在此全局定义,每个账号在其「配置」页勾选启用哪些。
</p>
</div>
<div className="flex flex-col gap-1.5 border-t pt-3">
@@ -307,10 +302,21 @@ function ChannelCard({ channel, testing, onToggle, onTest, onEdit, onDelete }: C
<div className="flex flex-wrap items-center gap-2">
<span className="font-medium">{channel.name || channel.id}</span>
<Badge variant="secondary" className="font-mono font-normal">{channel.id}</Badge>
<Badge variant="outline" className="font-normal">
{notificationChannelType(channel) === 'email' ? '邮件' : 'Webhook'}
</Badge>
{!channel.enabled && <Badge variant="secondary" className="font-normal">已停用</Badge>}
</div>
<div className="mt-0.5 truncate font-mono text-xs text-muted-foreground">{channel.url}</div>
<div className="mt-1 truncate font-mono text-meta text-muted-foreground/80">{channel.bodyTemplate}</div>
<div className="mt-0.5 truncate font-mono text-xs text-muted-foreground">
{notificationChannelType(channel) === 'email'
? [channel.to, channel.smtpHost].filter(Boolean).join(' · ')
: channel.url}
</div>
<div className="mt-1 truncate font-mono text-meta text-muted-foreground/80">
{notificationChannelType(channel) === 'email'
? (channel.subjectTemplate || channel.bodyTemplate)
: channel.bodyTemplate}
</div>
</div>
<div className="flex items-center gap-1.5 sm:justify-end">
+15
View File
@@ -147,13 +147,28 @@ export interface GlobalSettings {
// ─── Notifications (account up/down webhooks) ───────────────────────────────
export type NotificationEventKind = 'offline' | 'online';
export type NotificationChannelType = 'webhook' | 'email';
export interface NotificationChannel {
id: string;
name: string;
type?: NotificationChannelType;
url: string;
bodyTemplate: string;
enabled: boolean;
headers?: Record<string, string>;
smtpHost?: string;
smtpPort?: number;
smtpSecure?: boolean;
smtpUser?: string;
smtpPass?: string;
from?: string;
to?: string;
subjectTemplate?: string;
}
export function notificationChannelType(ch: Pick<NotificationChannel, 'type'>): NotificationChannelType {
return ch.type === 'email' ? 'email' : 'webhook';
}
export interface NotificationsConfig {
@@ -0,0 +1,91 @@
import { renderToStaticMarkup } from 'react-dom/server';
import { describe, expect, it, vi } from 'vitest';
import {
DEFAULT_EMAIL_BODY,
DEFAULT_WEBHOOK_BODY,
NotificationChannelDialog,
} from '../src/components/settings/notification-channel-dialog';
vi.mock('@/contexts/ThemeContext', () => ({
useTheme: () => ({ appearance: { disableMotion: true, reduceMotion: true } }),
}));
vi.mock('@/components/interior/modal', () => ({
Modal: ({
title,
description,
children,
footer,
}: {
title: string;
description?: string;
children?: unknown;
footer?: unknown;
}) => (
<div>
<h1>{title}</h1>
{description ? <p>{description}</p> : null}
{children}
<div>{footer}</div>
</div>
),
}));
describe('NotificationChannelDialog', () => {
it('shows webhook fields for a new webhook channel', () => {
const markup = renderToStaticMarkup(
<NotificationChannelDialog
open
onOpenChange={() => undefined}
isEdit={false}
initial={{
id: 'channel-1',
name: '',
type: 'webhook',
url: '',
bodyTemplate: DEFAULT_WEBHOOK_BODY,
enabled: true,
}}
otherIds={[]}
onSubmit={() => undefined}
/>,
);
expect(markup).toContain('Webhook URL');
expect(markup).toContain('请求头');
expect(markup).not.toContain('SMTP 主机');
expect(markup).toContain('向该 Webhook POST');
});
it('shows SMTP fields for an email channel', () => {
const markup = renderToStaticMarkup(
<NotificationChannelDialog
open
onOpenChange={() => undefined}
isEdit
initial={{
id: 'ops-mail',
name: '运维邮箱',
type: 'email',
url: '',
bodyTemplate: DEFAULT_EMAIL_BODY,
enabled: true,
smtpHost: 'smtp.qq.com',
smtpPort: 465,
smtpSecure: true,
from: '[email protected]',
to: '[email protected]',
}}
otherIds={[]}
onSubmit={() => undefined}
/>,
);
expect(markup).toContain('SMTP 主机');
expect(markup).toContain('smtp.qq.com');
expect(markup).toContain('发件人');
expect(markup).toContain('收件人');
expect(markup).toContain('主题模板');
expect(markup).toContain('隐式 TLS');
expect(markup).not.toContain('Webhook URL');
expect(markup).toContain('向该邮箱发送');
});
});
@@ -0,0 +1,107 @@
import { describe, expect, it } from 'vitest';
import {
applyType,
DEFAULT_EMAIL_BODY,
DEFAULT_EMAIL_SUBJECT,
DEFAULT_WEBHOOK_BODY,
toChannel,
} from '../src/components/settings/notification-channel-dialog';
import { notificationChannelType, type NotificationChannel } from '../src/types';
function webhook(over: Partial<NotificationChannel> = {}): NotificationChannel {
return {
id: 'hook',
name: 'Hook',
type: 'webhook',
url: 'https://example.com/hook',
bodyTemplate: DEFAULT_WEBHOOK_BODY,
enabled: true,
...over,
};
}
describe('notificationChannelType', () => {
it('treats a missing type as webhook', () => {
expect(notificationChannelType({ type: undefined })).toBe('webhook');
expect(notificationChannelType({ type: 'email' })).toBe('email');
});
});
describe('applyType', () => {
it('swaps the default webhook body for the email body when switching', () => {
const next = applyType(webhook(), 'email');
expect(next.type).toBe('email');
expect(next.url).toBe('');
expect(next.bodyTemplate).toBe(DEFAULT_EMAIL_BODY);
expect(next.subjectTemplate).toBe(DEFAULT_EMAIL_SUBJECT);
expect(next.smtpPort).toBe(465);
expect(next.smtpSecure).toBe(true);
});
it('keeps a custom body when switching to email', () => {
const next = applyType(webhook({ bodyTemplate: 'custom {event}' }), 'email');
expect(next.bodyTemplate).toBe('custom {event}');
});
it('drops SMTP fields when switching back to webhook', () => {
const email = applyType(webhook(), 'email');
const back = applyType({ ...email, smtpPass: 'secret' }, 'webhook');
expect(back.type).toBe('webhook');
expect(back).not.toHaveProperty('smtpPass');
expect(back).not.toHaveProperty('smtpHost');
expect(back.bodyTemplate).toBe(DEFAULT_WEBHOOK_BODY);
});
});
describe('toChannel', () => {
it('emits a webhook without email fields and with trimmed headers', () => {
const ch = toChannel(webhook({ headers: { leftover: 'x' } }), [
{ name: ' Authorization ', value: ' Bearer a ' },
{ name: '', value: 'skip' },
]);
expect(ch).toEqual({
id: 'hook',
name: 'Hook',
type: 'webhook',
url: 'https://example.com/hook',
bodyTemplate: DEFAULT_WEBHOOK_BODY,
enabled: true,
headers: { Authorization: 'Bearer a' },
});
});
it('emits email fields and an empty url', () => {
const ch = toChannel({
id: ' mail ',
name: ' Ops ',
type: 'email',
url: 'https://ignored',
bodyTemplate: DEFAULT_EMAIL_BODY,
enabled: true,
smtpHost: ' smtp.qq.com ',
smtpPort: 587,
smtpSecure: false,
smtpUser: ' [email protected] ',
smtpPass: 'secret',
from: ' SnowLuma <[email protected]> ',
to: ' [email protected] ',
subjectTemplate: ' {event} ',
}, []);
expect(ch).toEqual({
id: 'mail',
name: 'Ops',
type: 'email',
url: '',
bodyTemplate: DEFAULT_EMAIL_BODY,
enabled: true,
smtpHost: 'smtp.qq.com',
smtpPort: 587,
smtpSecure: false,
smtpUser: '[email protected]',
smtpPass: 'secret',
from: 'SnowLuma <[email protected]>',
to: '[email protected]',
subjectTemplate: '{event}',
});
});
});