feat(notifications): deliver online/offline alerts over SMTP
Fixes #459
This commit is contained in:
13 files changed
+1600
-109
No files matched your search
@@ -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),
|
||||
|
||||
@@ -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(),
|
||||
});
|
||||
}
|
||||
@@ -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');
|
||||
}
|
||||
@@ -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');
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user