fix(notifications): the smtp test names its failure and the log carries it (#2196)

testSmtp logged nothing and the transport ran on nodemailer's two-minute defaults while the client gave up after eight seconds, so every failure was a generic toast over an empty log. The transport gets real timeouts, every outcome is logged without credentials, and a classified, scrubbed cause (auth, DNS, refused, filtered port, TLS mismatch, certificate) goes into the response the admin sees; the channel test calls wait long enough to receive it. The password field also rendered its mask as value, so replacing a stored password silently saved the bullets as part of the new one; it is a placeholder now, on desktop and the phone admin.
This commit is contained in:
Maurice
2026-09-02 19:58:13 +02:00
committed by Maurice
parent 1e6ab069cd
commit b6a86275f6
11 changed files with 593 additions and 20 deletions
@@ -6,6 +6,7 @@ import { logError, logInfo, logDebug, logWarn } from '../../audit/audit-log.logg
import { decrypt_api_key } from '../../common/crypto/apiKeyCrypto';
import { DatabaseService } from '../../database/database.service';
import { buildEmailHtml, buildPasswordResetHtml } from './email-html';
import { describeSmtpFailure, describeSmtpGap, parseSmtpPort, type SmtpTarget } from './smtp-diagnostics';
interface SmtpConfig {
host: string;
@@ -16,6 +17,20 @@ interface SmtpConfig {
secure: boolean;
}
/**
* Nodemailer's own defaults are 2 minutes to connect and 30 seconds for the
* greeting, both of which outlive the browser's 8-second API timeout: an admin
* pressing "Send test email" against a blocked port got a dead "Test email
* failed" while the socket was still waiting, and the eventual error had nobody
* left to tell. A relay that needs more than ten seconds to accept a connection
* or to send its banner is broken either way, so those two are cut hard. The
* inactivity timeout stays generous (nodemailer's default is ten minutes)
* because a relay that scans the message can be slow to acknowledge DATA.
*/
const CONNECT_TIMEOUT_MS = 10_000;
const GREETING_TIMEOUT_MS = 10_000;
const SOCKET_TIMEOUT_MS = 30_000;
/**
* Outgoing mail: SMTP config resolution, the password-reset delivery and the
* generic notification email.
@@ -36,21 +51,31 @@ export class MailerService {
return this.db.get<{ value: string }>('SELECT value FROM app_settings WHERE key = ?', key)?.value || null;
}
private getSmtpConfig(): SmtpConfig | null {
/** Env wins over the admin panel, per field. Read fresh on every send. */
private readSmtpSettings() {
const smtpEnv = readEnv().smtp;
const host = smtpEnv.host || this.getAppSetting('smtp_host');
const port = smtpEnv.port || this.getAppSetting('smtp_port');
const user = smtpEnv.user || this.getAppSetting('smtp_user');
const pass = smtpEnv.pass || decrypt_api_key(this.getAppSetting('smtp_pass')) || '';
const from = smtpEnv.from || this.getAppSetting('smtp_from');
if (!host || !port || !from) return null;
return {
host: smtpEnv.host || this.getAppSetting('smtp_host'),
port: smtpEnv.port || this.getAppSetting('smtp_port'),
user: smtpEnv.user || this.getAppSetting('smtp_user'),
pass: smtpEnv.pass || decrypt_api_key(this.getAppSetting('smtp_pass')) || '',
from: smtpEnv.from || this.getAppSetting('smtp_from'),
};
}
private getSmtpConfig(): SmtpConfig | null {
const { host, port, user, pass, from } = this.readSmtpSettings();
// An unusable port counts as unconfigured rather than as a dial: net.connect
// on NaN throws from inside nodemailer, where the reason gets lost.
const portNumber = parseSmtpPort(port);
if (!host || !portNumber || !from) return null;
return {
host,
port: Number.parseInt(port, 10),
port: portNumber,
user: user || '',
pass: pass || '',
from,
secure: Number.parseInt(port, 10) === 465,
secure: portNumber === 465,
};
}
@@ -69,6 +94,9 @@ export class MailerService {
port: config.port,
secure: config.secure,
auth: config.user ? { user: config.user, pass: config.pass } : undefined,
connectionTimeout: CONNECT_TIMEOUT_MS,
greetingTimeout: GREETING_TIMEOUT_MS,
socketTimeout: SOCKET_TIMEOUT_MS,
// The operator's opt-out for a relay with a self-signed certificate, off by
// default and reachable only through SMTP_SKIP_TLS_VERIFY or the matching
// admin setting. It stays because self-hosted installs behind an internal
@@ -155,7 +183,7 @@ export class MailerService {
logInfo(`Password reset email sent to=${to}`);
return { delivered: 'email' };
} catch (err) {
logError(`Password reset email failed to=${to}: ${err instanceof Error ? err.message : err}`);
logError(`Password reset email failed to=${to} ${this.explain(err, smtpCfg)}`);
return { delivered: 'failed' };
}
}
@@ -184,14 +212,26 @@ export class MailerService {
logDebug(`Email smtp=${config.host}:${config.port} from=${config.from} to=${to}`);
return true;
} catch (err) {
logError(`Email send failed to=${to}: ${err instanceof Error ? err.message : err}`);
logError(`Email send failed to=${to} ${this.explain(err, config)}`);
return false;
}
}
/**
* The admin's "Send test email" button. Unlike the delivery paths this one has
* somebody waiting for an answer, so the classified reason goes into the
* response as well as the log. Issue #2196 was an admin staring at "Test email
* failed" with an empty container log, unable to tell a wrong password from a
* blocked port.
*/
async testSmtp(to: string): Promise<{ success: boolean; error?: string }> {
const config = this.getSmtpConfig();
if (!config) return { success: false, error: 'SMTP not configured' };
if (!config) {
const { host, port, from } = this.readSmtpSettings();
const reason = describeSmtpGap({ host, port, from });
logWarn(`SMTP test not attempted to=${to}: ${reason}`);
return { success: false, error: reason };
}
try {
await this.createTransport(config).sendMail({
from: config.from,
@@ -199,9 +239,27 @@ export class MailerService {
subject: 'TREK — Test Notification',
text: 'This is a test email from TREK. If you received this, your SMTP configuration is working correctly.',
});
logInfo(`SMTP test email sent to=${to} ${this.describeTarget(config)}`);
return { success: true };
} catch (err) {
return { success: false, error: err instanceof Error ? err.message : 'Unknown error' };
const failure = describeSmtpFailure(err, this.target(config), config.pass);
logError(`SMTP test email failed to=${to} ${this.describeTarget(config)} code=${failure.code}: ${failure.reason}`);
return { success: false, error: failure.reason };
}
}
private target(config: SmtpConfig): SmtpTarget {
return { host: config.host, port: config.port, secure: config.secure };
}
/** The tail every failed-send log line carries: where it went, and why it broke. */
private explain(err: unknown, config: SmtpConfig): string {
const failure = describeSmtpFailure(err, this.target(config), config.pass);
return `${this.describeTarget(config)} code=${failure.code}: ${failure.reason}`;
}
/** Never the user or the password: the relay and how it was dialled. */
private describeTarget(config: SmtpConfig): string {
return `smtp=${config.host}:${config.port} secure=${config.secure} auth=${config.user ? 'yes' : 'no'}`;
}
}
@@ -0,0 +1,111 @@
/**
* Turning an SMTP failure into something an admin can act on.
*
* Nodemailer throws an Error carrying `code`, `command` and, when the relay said
* something back, `response` (already appended to the message). None of it used
* to reach anywhere: the test-email button logged nothing at all, so a wrong
* password and a blocked port looked identical from the outside. The classifier
* below keeps the relay's own words, which are the most useful part, and puts
* the diagnosis in front of them.
*
* Everything here is pure, so the wording can be pinned in unit tests without a
* socket.
*/
export interface SmtpTarget {
host: string;
port: number;
secure: boolean;
}
export interface SmtpFailure {
/** Nodemailer's error code, or 'UNKNOWN' when the throw carried none. */
code: string;
/** Admin-facing and credential-free: safe for both the log and the response. */
reason: string;
}
const MAX_REASON_LENGTH = 400;
const MAX_ECHOED_VALUE = 32;
/** A port TREK can actually dial, or null. Rejects '', 'abc', '0', '70000', '587abc'. */
export function parseSmtpPort(raw: string | null | undefined): number | null {
if (!raw) return null;
const trimmed = String(raw).trim();
if (!/^\d+$/.test(trimmed)) return null;
const port = Number.parseInt(trimmed, 10);
return port >= 1 && port <= 65535 ? port : null;
}
/**
* Why getSmtpConfig() came back empty. Named per field: "SMTP not configured" on
* its own sent admins hunting through a form where four of the five fields were
* filled in.
*/
export function describeSmtpGap(raw: { host?: string | null; port?: string | null; from?: string | null }): string {
if (raw.port && !parseSmtpPort(raw.port)) {
return `SMTP not configured: the port "${clip(String(raw.port), MAX_ECHOED_VALUE)}" is not a number between 1 and 65535.`;
}
const missing: string[] = [];
if (!raw.host) missing.push('host (SMTP_HOST)');
if (!raw.port) missing.push('port (SMTP_PORT)');
if (!raw.from) missing.push('from address (SMTP_FROM)');
return `SMTP not configured: missing ${missing.join(', ')}. Set it under Admin > Notifications or as the matching environment variable.`;
}
export function describeSmtpFailure(err: unknown, target: SmtpTarget, secret = ''): SmtpFailure {
const thrown = (err ?? {}) as { code?: unknown; message?: unknown };
const code = typeof thrown.code === 'string' && thrown.code ? thrown.code : 'UNKNOWN';
const message = scrub(typeof thrown.message === 'string' && thrown.message ? thrown.message : String(err), secret);
const where = `${target.host}:${target.port}`;
if (code === 'EAUTH') {
return { code, reason: `${where} rejected the credentials. Check the SMTP user and password, and whether the account needs an app-specific password. Server said: ${message}` };
}
if (code === 'EDNS' || /ENOTFOUND|EAI_AGAIN/.test(message)) {
return { code, reason: `The host ${target.host} could not be resolved: ${message}` };
}
if (/ECONNREFUSED/.test(message)) {
return { code, reason: `${where} refused the connection: nothing is listening on that port, or a firewall closed it. ${portHint(target)}` };
}
if (/EHOSTUNREACH|ENETUNREACH|EACCES/.test(message)) {
return { code, reason: `${where} is unreachable from the TREK container: ${message}` };
}
if (code === 'ETIMEDOUT' || /timed? ?out|Greeting never received/i.test(message)) {
return { code, reason: `${where} did not answer in time: ${message}. Outbound mail ports are often blocked by the host or the hosting provider. ${portHint(target)}` };
}
if (/certificate|self.signed/i.test(message)) {
return { code, reason: `The TLS certificate of ${where} was not accepted: ${message}. For an internal relay with its own certificate, turn on "Skip TLS certificate check".` };
}
if (/wrong version number|packet length too long|ssl|routines|tlsv1/i.test(message)) {
return { code, reason: `The TLS handshake with ${where} failed: ${message}. ${portHint(target)}` };
}
if (code === 'EENVELOPE') {
return { code, reason: `${where} rejected the envelope. The from address normally has to belong to the authenticated account. Server said: ${message}` };
}
if (code === 'EMESSAGE') {
return { code, reason: `${where} accepted the connection but rejected the message: ${message}` };
}
return { code, reason: `Sending through ${where} failed (${code}): ${message}` };
}
/**
* The 465-versus-587 mix-up is the one that produces a silent hang rather than a
* refusal, so every connection-level diagnosis carries it.
*/
function portHint(target: SmtpTarget): string {
return target.secure
? 'Port 465 is dialled with implicit TLS; a relay that expects STARTTLS listens on 587.'
: `Port ${target.port} is dialled in plain mode with STARTTLS; a relay that expects TLS from the first byte listens on 465.`;
}
/** The relay's words, minus anything that could carry the credential back out. */
function scrub(text: string, secret: string): string {
const collapsed = text.replace(/\s+/g, ' ').trim();
const redacted = secret.length >= 4 ? collapsed.split(secret).join('***') : collapsed;
return clip(redacted, MAX_REASON_LENGTH);
}
function clip(text: string, max: number): string {
return text.length > max ? `${text.slice(0, max)}...` : text;
}