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.
|
||||
|
||||
Reference in new issue
Block a user