@blamejs/core 0.9.43 → 0.9.46

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,736 @@
1
+ "use strict";
2
+ /**
3
+ * @module b.mail.server.mx
4
+ * @nav Mail
5
+ * @title Mail MX Server
6
+ * @order 540
7
+ *
8
+ * @intro
9
+ * Inbound SMTP / MX listener. Composes the framework's existing
10
+ * mail-gate substrates (`b.mail.helo`, `b.mail.rbl`,
11
+ * `b.mail.greylist`, `b.guardEnvelope`, `b.mail.auth.dmarc`,
12
+ * `b.safeMime`, `b.guardEmail`, `b.guardSmtpCommand`,
13
+ * `b.mail.agent`) into one operator-facing server that accepts
14
+ * inbound mail per RFC 5321 with PQC-shaped TLS posture, SMTP-
15
+ * smuggling defense baked into the wire-protocol layer, and the
16
+ * gate cascade running at the right phase of the state machine.
17
+ *
18
+ * `create({ ... }).listen()` binds the TCP port; every incoming
19
+ * connection drives the CONNECT → EHLO → [STARTTLS → EHLO] →
20
+ * MAIL → RCPT (×N) → DATA → DATA-body → QUIT state machine. Each
21
+ * phase passes through the operator-supplied gates (defaulting
22
+ * to "no-op" when the operator hasn't wired a gate) and refuses
23
+ * with the appropriate 5xx (permanent) or 4xx (transient) SMTP
24
+ * reply code on gate fail.
25
+ *
26
+ * ## Defenses baked in
27
+ *
28
+ * - **SMTP smuggling** (CVE-2023-51764 / CVE-2024-32178) — every
29
+ * wire line passes through `b.guardSmtpCommand.validate` which
30
+ * refuses bare LF, bare CR, NUL, C0 controls, DEL, and oversize.
31
+ * The DATA body's `\r\n.\r\n` terminator is matched on canonical
32
+ * CRLF only — bare-LF dot-terminators are refused. Together this
33
+ * defends the CVE-2023-51764 class where a hostile sender
34
+ * smuggles a second message past the framework's filter by
35
+ * terminating the first one with `\n.\n` instead of `\r\n.\r\n`.
36
+ *
37
+ * - **Open-relay defense** — RCPT TO non-local refused with 550
38
+ * 5.7.1 Relaying denied unless the operator explicitly registered
39
+ * the destination via `relayAllowedFor: [{ cidr, scope }]`. The
40
+ * default posture is "MX-only, no relay" so a misconfigured boot
41
+ * can't accidentally become an open relay.
42
+ *
43
+ * - **STARTTLS stripping (CVE-2021-38371 Exim, CVE-2021-33515 Dovecot)** —
44
+ * once STARTTLS is advertised + selected, subsequent commands
45
+ * MUST run over the negotiated TLS context. A pre-STARTTLS
46
+ * pipelining attempt (RFC 2920) to inject commands that take
47
+ * effect post-handshake is refused by clearing the command
48
+ * buffer at STARTTLS time and reading fresh from the TLS socket
49
+ * only — defends both the Exim and Dovecot variants of the
50
+ * STARTTLS-injection class.
51
+ *
52
+ * - **Resource exhaustion** — per-command line cap (default
53
+ * 1 KiB), DATA body cap (default 50 MiB per RFC 5321 §4.5.3.1.7),
54
+ * per-recipient cap (default 100 per RFC 5321 §4.5.3.1.8),
55
+ * connection idle timeout (default 5 minutes per RFC 5321
56
+ * §4.5.3.2.7). Operator opts up with explicit bounds.
57
+ *
58
+ * - **TLS posture** — `tlsContext` MUST be supplied (no implicit
59
+ * plaintext-only mode). Operator passes a `b.network.tls.context`
60
+ * output which carries the framework's TLS 1.3 default + OCSP /
61
+ * CT-log posture. Pre-STARTTLS plain commands are limited to
62
+ * EHLO / HELO / STARTTLS / NOOP / QUIT / RSET; MAIL / RCPT /
63
+ * DATA all refused with 530 5.7.0 Must issue a STARTTLS command
64
+ * first.
65
+ *
66
+ * ## Audit lifecycle
67
+ *
68
+ * - `mail.server.mx.connect` — IP, TLS state, FCrDNS hostname
69
+ * - `mail.server.mx.helo` — HELO greeting, helo-gate verdict
70
+ * - `mail.server.mx.mail_from` — sender, SPF verdict, alignment verdict
71
+ * - `mail.server.mx.rcpt_to` — recipient, RBL verdict, greylist verdict
72
+ * - `mail.server.mx.data_accepted` — message size, DKIM verdict, DMARC verdict
73
+ * - `mail.server.mx.data_refused` — refusal reason + SMTP code (5xx vs 4xx)
74
+ * - `mail.server.mx.delivered` — agent.handoff ack
75
+ * - `mail.server.mx.tls_handshake_failed` — handshake error
76
+ * - `mail.server.mx.smtp_smuggling_detected` — CRLF.CRLF injection class
77
+ * - `mail.server.mx.relay_refused` — open-relay attempt
78
+ *
79
+ * ## What v1 does NOT ship
80
+ *
81
+ * - **AUTH / submission auth** — MX listener is inbound from the
82
+ * internet, no authentication. Submission listener (port 587) is
83
+ * a separate slice with SCRAM-SHA-256 / XOAUTH2 / EXTERNAL.
84
+ * - **Sieve filtering** — composes via `b.mail.agent` at delivery
85
+ * time; the MX listener doesn't decide policy itself.
86
+ * - **Outbound DSN generation** — `b.guardDsn` parses inbound DSNs;
87
+ * outbound DSN emission deferred to the submission slice.
88
+ * - **8BITMIME** (RFC 6152, obsoletes RFC 1652) — advertised in
89
+ * the EHLO capabilities since the DATA body parser via
90
+ * `b.safeMime` is octet-clean; no transcoding needed.
91
+ * - **SMTPUTF8** (RFC 6531) + **IDN** (RFC 5891) — the wire-protocol
92
+ * layer here is encoding-agnostic; SMTPUTF8 capability
93
+ * advertisement is a follow-up slice once the operator's
94
+ * downstream (mail-store + delivery agent) accepts Unicode
95
+ * mailbox-local-part bytes. Today the listener does not
96
+ * advertise SMTPUTF8 and refuses non-ASCII in MAIL FROM /
97
+ * RCPT TO via `b.guardSmtpCommand`.
98
+ *
99
+ * ## Composition contract
100
+ *
101
+ * Every gate is a primitive that already exists. The MX slice is a
102
+ * state-machine + wire-protocol coordinator — no new crypto, no
103
+ * new parsing, no new RFC-layer primitives. If a gate isn't ready
104
+ * (e.g. operator hasn't wired `b.mail.auth.dmarc`), the listener
105
+ * skips that phase with an audit note rather than synthesizing a
106
+ * verdict.
107
+ *
108
+ * @card
109
+ * Inbound SMTP / MX listener. RFC 5321 state machine with SMTP-
110
+ * smuggling defense baked into the wire-protocol layer (RFC 5321
111
+ * §2.3.8 + CVE-2023-51764 / CVE-2024-32178), open-relay refusal by
112
+ * default, STARTTLS-stripping defense (CVE-2021-38371), and the
113
+ * framework's mail-gate cascade (HELO / RBL / greylist /
114
+ * guardEnvelope / DMARC / safeMime / guardEmail) running at the
115
+ * appropriate phase.
116
+ */
117
+
118
+ var net = require("node:net");
119
+ var nodeTls = require("node:tls");
120
+ var lazyRequire = require("./lazy-require");
121
+ var C = require("./constants");
122
+ var bCrypto = require("./crypto");
123
+ var numericBounds = require("./numeric-bounds");
124
+ var safeAsync = require("./safe-async");
125
+ var safeBuffer = require("./safe-buffer");
126
+ var safeSmtp = require("./safe-smtp");
127
+ var validateOpts = require("./validate-opts");
128
+ var guardSmtpCommand = require("./guard-smtp-command");
129
+ var { defineClass } = require("./framework-error");
130
+
131
+ var audit = lazyRequire(function () { return require("./audit"); });
132
+
133
+ var MailServerMxError = defineClass("MailServerMxError", { alwaysPermanent: true });
134
+
135
+ // RFC 5321 §4.5.3.1 — wire-protocol limits.
136
+ var DEFAULT_MAX_LINE_BYTES = C.BYTES.kib(1);
137
+ var DEFAULT_MAX_MESSAGE_BYTES = C.BYTES.mib(50);
138
+ var DEFAULT_MAX_RCPTS_PER_MESSAGE = 100; // allow:raw-byte-literal — RFC 5321 §4.5.3.1.8 recipient cap
139
+ var DEFAULT_IDLE_TIMEOUT_MS = C.TIME.minutes(5);
140
+ var DEFAULT_GREETING = "blamejs ESMTP";
141
+
142
+ // SMTP reply-code constants. The framework uses RFC 5321 enhanced
143
+ // status codes per RFC 3463 (`Dclass.Dsubject.Ddetail`) embedded in
144
+ // the reply lines for operator-side observability.
145
+ var REPLY_220_READY = "220";
146
+ var REPLY_221_BYE = "221";
147
+ var REPLY_250_OK = "250";
148
+ var REPLY_354_START_INPUT = "354";
149
+ var REPLY_421_SERVICE_NOT_AVAIL = "421"; // allow:raw-byte-literal — SMTP transient code
150
+ var REPLY_451_LOCAL_ERROR = "451"; // allow:raw-byte-literal — SMTP transient code
151
+ var REPLY_452_INSUFFICIENT_STG = "452"; // allow:raw-byte-literal — SMTP transient code
152
+ var REPLY_500_SYNTAX = "500"; // allow:raw-byte-literal — SMTP permanent code
153
+ var REPLY_501_BAD_ARGS = "501"; // allow:raw-byte-literal — SMTP permanent code
154
+ var REPLY_502_NOT_IMPLEMENTED = "502"; // allow:raw-byte-literal — SMTP permanent code
155
+ var REPLY_503_BAD_SEQUENCE = "503"; // allow:raw-byte-literal — SMTP permanent code
156
+ var REPLY_530_AUTH_REQUIRED = "530"; // allow:raw-byte-literal — SMTP permanent code
157
+ var REPLY_550_MAILBOX_UNAVAIL = "550"; // allow:raw-byte-literal — SMTP permanent code
158
+ var REPLY_552_SIZE_EXCEEDED = "552"; // allow:raw-byte-literal — SMTP permanent code
159
+ var REPLY_554_TRANSACTION_FAILED = "554"; // allow:raw-byte-literal — SMTP permanent code
160
+
161
+ var RE_MAIL_FROM = /^MAIL\s+FROM:\s*<([^>]*)>(?:\s+(.*))?$/i;
162
+ var RE_RCPT_TO = /^RCPT\s+TO:\s*<([^>]+)>(?:\s+.*)?$/i;
163
+ var RE_SIZE = /SIZE=(\d+)/i;
164
+
165
+ /**
166
+ * @primitive b.mail.server.mx.create
167
+ * @signature b.mail.server.mx.create(opts)
168
+ * @since 0.9.46
169
+ * @status stable
170
+ * @related b.mail.helo.evaluate, b.mail.rbl.create, b.mail.greylist.create, b.guardEnvelope.check, b.mail.agent.create
171
+ *
172
+ * Build the MX listener. Returns `{ listen({ port?, address? }),
173
+ * close({ timeoutMs? }), connectionCount(), _portForTest() }`.
174
+ *
175
+ * @opts
176
+ * tlsContext: TlsContext, // required — b.network.tls.context() output (no implicit plaintext)
177
+ * greeting: string, // default "blamejs ESMTP" — HELO/EHLO 220-line banner
178
+ * helo: b.mail.helo, // optional gate
179
+ * rbl: b.mail.rbl, // optional gate
180
+ * greylist: b.mail.greylist, // optional gate
181
+ * envelope: b.guardEnvelope, // optional gate (SPF/DKIM alignment)
182
+ * dmarc: b.mail.auth.dmarc, // optional gate
183
+ * agent: b.mail.agent, // optional delivery handoff
184
+ * relayAllowedFor: [{ cidr, scope }], // operator-explicit relay allowlist; default [] = MX-only
185
+ * localDomains: [string], // RCPT TO local-domain allowlist (refuse non-local with 550 5.7.1)
186
+ * maxLineBytes: number, // default 1 KiB — per-command line cap
187
+ * maxMessageBytes: number, // default 50 MiB — DATA body cap
188
+ * maxRcptsPerMessage: number, // default 100 — per RFC 5321 §4.5.3.1.8
189
+ * idleTimeoutMs: number, // default 5 minutes — RFC 5321 §4.5.3.2.7
190
+ * profile: "strict" | "balanced" | "permissive", // gate posture cascade
191
+ *
192
+ * @example
193
+ * var tls = b.network.tls.context({ cert: certPem, key: keyPem });
194
+ * var server = b.mail.server.mx.create({
195
+ * tlsContext: tls,
196
+ * greeting: "mx.example.com ESMTP blamejs",
197
+ * helo: b.mail.helo,
198
+ * rbl: b.mail.rbl.create({ providers: ["zen.spamhaus.org"] }),
199
+ * greylist: b.mail.greylist.create({ store: greylistStore }),
200
+ * envelope: b.guardEnvelope,
201
+ * agent: b.mail.agent.create({ store: mailStore }),
202
+ * localDomains: ["example.com"],
203
+ * });
204
+ * await server.listen({ port: 25 });
205
+ */
206
+ function create(opts) {
207
+ validateOpts.requireObject(opts, "mail.server.mx.create",
208
+ MailServerMxError, "mail-server-mx/bad-opts");
209
+ if (!opts.tlsContext) {
210
+ throw new MailServerMxError("mail-server-mx/no-tls-context",
211
+ "mail.server.mx.create: tlsContext is required (no implicit plaintext mode)");
212
+ }
213
+ numericBounds.requireAllPositiveFiniteIntIfPresent(opts,
214
+ ["maxLineBytes", "maxMessageBytes", "maxRcptsPerMessage", "idleTimeoutMs"],
215
+ "mail.server.mx.", MailServerMxError, "mail-server-mx/bad-bound");
216
+ if (opts.localDomains !== undefined &&
217
+ (!Array.isArray(opts.localDomains) || opts.localDomains.length === 0)) {
218
+ throw new MailServerMxError("mail-server-mx/bad-opts",
219
+ "mail.server.mx.create: localDomains must be a non-empty array if provided");
220
+ }
221
+ if (opts.relayAllowedFor !== undefined && !Array.isArray(opts.relayAllowedFor)) {
222
+ throw new MailServerMxError("mail-server-mx/bad-opts",
223
+ "mail.server.mx.create: relayAllowedFor must be an array if provided");
224
+ }
225
+
226
+ var greeting = opts.greeting || DEFAULT_GREETING;
227
+ var maxLineBytes = opts.maxLineBytes || DEFAULT_MAX_LINE_BYTES;
228
+ var maxMessageBytes = opts.maxMessageBytes || DEFAULT_MAX_MESSAGE_BYTES;
229
+ var maxRcptsPerMsg = opts.maxRcptsPerMessage || DEFAULT_MAX_RCPTS_PER_MESSAGE;
230
+ var idleTimeoutMs = opts.idleTimeoutMs || DEFAULT_IDLE_TIMEOUT_MS;
231
+ var localDomains = (opts.localDomains || []).map(function (d) { return String(d).toLowerCase(); });
232
+ var relayAllowedFor = opts.relayAllowedFor || [];
233
+ var profile = opts.profile || "strict";
234
+
235
+ var tcpServer = null;
236
+ var listening = false;
237
+ var connections = new Set();
238
+
239
+ function _emit(action, metadata, outcome) {
240
+ try {
241
+ audit().safeEmit({
242
+ action: action,
243
+ outcome: outcome || "success",
244
+ metadata: metadata || {},
245
+ });
246
+ } catch (_e) { /* drop-silent — audit best-effort */ }
247
+ }
248
+
249
+ // ---- Per-connection state machine ---------------------------------------
250
+ function _handleConnection(socket) {
251
+ var connectionId = "mxconn-" + bCrypto.generateToken(8); // allow:raw-byte-literal — connection-id length
252
+ connections.add(socket);
253
+
254
+ var state = {
255
+ id: connectionId,
256
+ remoteAddress: socket.remoteAddress || null,
257
+ remotePort: socket.remotePort || null,
258
+ tls: false,
259
+ stage: "connect", // connect | ehlo | mail | rcpt | data-body | done
260
+ helo: null,
261
+ mailFrom: null,
262
+ rcpts: [],
263
+ messageBytes: 0,
264
+ };
265
+
266
+ var lineBuffer = "";
267
+ var bodyCollector = null;
268
+ var inDataBody = false;
269
+
270
+ socket.setTimeout(idleTimeoutMs);
271
+ socket.on("timeout", function () {
272
+ _writeReply(socket, REPLY_421_SERVICE_NOT_AVAIL, "4.4.2 Idle timeout");
273
+ _closeConnection(socket);
274
+ });
275
+
276
+ socket.on("error", function (err) {
277
+ _emit("mail.server.mx.socket_error",
278
+ { connectionId: state.id, code: (err && err.code) || "unknown", message: err && err.message },
279
+ "warning");
280
+ _closeConnection(socket);
281
+ });
282
+
283
+ socket.on("close", function () {
284
+ connections.delete(socket);
285
+ });
286
+
287
+ _emit("mail.server.mx.connect", {
288
+ connectionId: state.id,
289
+ remoteAddress: state.remoteAddress,
290
+ remotePort: state.remotePort,
291
+ tls: false,
292
+ });
293
+
294
+ // 220 banner — RFC 5321 §3.1.
295
+ _writeReply(socket, REPLY_220_READY, greeting + " ready");
296
+
297
+ socket.on("data", function (chunk) {
298
+ try { _ingestBytes(state, socket, chunk); }
299
+ catch (err) {
300
+ _emit("mail.server.mx.handler_threw",
301
+ { connectionId: state.id, error: (err && err.message) || String(err) },
302
+ "failure");
303
+ try { _writeReply(socket, REPLY_421_SERVICE_NOT_AVAIL, "4.3.0 Server error"); }
304
+ catch (_e) { /* socket already gone */ }
305
+ _closeConnection(socket);
306
+ }
307
+ });
308
+
309
+ // ---- Byte-level ingestion --------------------------------------------
310
+ function _ingestBytes(state, socket, chunk) {
311
+ if (inDataBody) {
312
+ // DATA body — accumulate via boundedChunkCollector, watch for
313
+ // canonical "\r\n.\r\n" terminator only. Bare-LF dot terminator
314
+ // is the SMTP smuggling shape (CVE-2023-51764); refused.
315
+ try { bodyCollector.push(chunk); }
316
+ catch (_e) {
317
+ _emit("mail.server.mx.data_refused",
318
+ { connectionId: state.id, reason: "body-too-large", maxBytes: maxMessageBytes },
319
+ "denied");
320
+ _writeReply(socket, REPLY_552_SIZE_EXCEEDED,
321
+ "5.3.4 Message size exceeds fixed maximum (" + maxMessageBytes + " bytes)");
322
+ _resetTransaction(state);
323
+ inDataBody = false;
324
+ bodyCollector = null;
325
+ return;
326
+ }
327
+ var collected = bodyCollector.result();
328
+ // Smuggling detector — bare LF dot-line in body before the
329
+ // CRLF dot terminator. Refuse the whole transaction; emit
330
+ // smuggling-detected audit.
331
+ if (guardSmtpCommand.detectBodySmuggling(collected)) {
332
+ _emit("mail.server.mx.smtp_smuggling_detected",
333
+ { connectionId: state.id, mailFrom: state.mailFrom, rcptCount: state.rcpts.length },
334
+ "denied");
335
+ _writeReply(socket, REPLY_554_TRANSACTION_FAILED,
336
+ "5.7.0 Bare-LF in DATA body refused (RFC 5321 §2.3.8; CVE-2023-51764 SMTP smuggling)");
337
+ _resetTransaction(state);
338
+ inDataBody = false;
339
+ bodyCollector = null;
340
+ return;
341
+ }
342
+ // Canonical \r\n.\r\n terminator?
343
+ var endIdx = safeSmtp.findDotTerminator(collected);
344
+ if (endIdx !== -1) {
345
+ var body = collected.subarray(0, endIdx);
346
+ _finalizeDataBody(state, socket, body);
347
+ inDataBody = false;
348
+ bodyCollector = null;
349
+ }
350
+ return;
351
+ }
352
+
353
+ // Command phase — line-buffered.
354
+ lineBuffer += chunk.toString("utf8");
355
+ if (lineBuffer.length > maxLineBytes * 4) {
356
+ _writeReply(socket, REPLY_500_SYNTAX,
357
+ "5.5.6 Line too long (>" + maxLineBytes + " bytes)");
358
+ _closeConnection(socket);
359
+ return;
360
+ }
361
+ var crlf;
362
+ while ((crlf = lineBuffer.indexOf("\r\n")) !== -1) {
363
+ var line = lineBuffer.slice(0, crlf);
364
+ lineBuffer = lineBuffer.slice(crlf + 2);
365
+ _handleCommand(state, socket, line);
366
+ if (inDataBody) return;
367
+ }
368
+ }
369
+
370
+ function _handleCommand(state, socket, line) {
371
+ // Per-line guard — refuse bare LF / NUL / C0 / DEL / oversize
372
+ // BEFORE state-machine dispatch.
373
+ try {
374
+ guardSmtpCommand.validate(line, { profile: profile, maxLineBytes: maxLineBytes });
375
+ } catch (err) {
376
+ if (err.code === "guard-smtp-command/bare-lf" ||
377
+ err.code === "guard-smtp-command/bare-cr" ||
378
+ err.code === "guard-smtp-command/nul-byte") {
379
+ _emit("mail.server.mx.smtp_smuggling_detected",
380
+ { connectionId: state.id, code: err.code, line: line.slice(0, 200) }, // allow:raw-byte-literal — audit-log line truncation
381
+ "denied");
382
+ }
383
+ _writeReply(socket, REPLY_500_SYNTAX, "5.5.2 Syntax error (" + (err.code || "bad-line") + ")");
384
+ return;
385
+ }
386
+
387
+ var verb = line.split(/\s+/)[0].toUpperCase();
388
+ switch (verb) {
389
+ case "EHLO":
390
+ case "HELO":
391
+ _handleEhlo(state, socket, line, verb);
392
+ return;
393
+ case "STARTTLS":
394
+ _handleStartTls(state, socket);
395
+ return;
396
+ case "MAIL":
397
+ _handleMailFrom(state, socket, line);
398
+ return;
399
+ case "RCPT":
400
+ _handleRcptTo(state, socket, line);
401
+ return;
402
+ case "DATA":
403
+ _handleData(state, socket);
404
+ return;
405
+ case "NOOP":
406
+ _writeReply(socket, REPLY_250_OK, "2.0.0 OK");
407
+ return;
408
+ case "RSET":
409
+ _resetTransaction(state);
410
+ _writeReply(socket, REPLY_250_OK, "2.0.0 Reset");
411
+ return;
412
+ case "QUIT":
413
+ _writeReply(socket, REPLY_221_BYE, "2.0.0 Bye");
414
+ _closeConnection(socket);
415
+ return;
416
+ case "VRFY":
417
+ case "EXPN":
418
+ // Refuse VRFY/EXPN per modern best practice (information
419
+ // disclosure of internal aliases / valid recipients).
420
+ _writeReply(socket, REPLY_502_NOT_IMPLEMENTED, "5.5.1 Command not implemented");
421
+ return;
422
+ default:
423
+ _writeReply(socket, REPLY_500_SYNTAX, "5.5.2 Unknown command");
424
+ }
425
+ }
426
+
427
+ // ---- EHLO / HELO ------------------------------------------------------
428
+ function _handleEhlo(state, socket, line, verb) {
429
+ var helo = line.slice(verb.length).trim();
430
+ if (!helo) {
431
+ _writeReply(socket, REPLY_501_BAD_ARGS, "5.5.4 " + verb + " requires a domain argument");
432
+ return;
433
+ }
434
+ state.helo = helo;
435
+ state.stage = "ehlo";
436
+ // Multi-line 250 capabilities advertisement per RFC 5321 §4.1.1.1.
437
+ if (verb === "EHLO") {
438
+ // EHLO capabilities advertised:
439
+ // - PIPELINING per RFC 2920
440
+ // - SIZE n per RFC 1870 §3 (with the per-server byte cap)
441
+ // - 8BITMIME per RFC 6152 (obsoletes RFC 1652)
442
+ // - STARTTLS per RFC 3207 §2 (only advertised pre-TLS)
443
+ // - ENHANCEDSTATUSCODES per RFC 2034 (RFC 3463 code shape)
444
+ var caps = ["PIPELINING", "SIZE " + maxMessageBytes, "8BITMIME"];
445
+ if (!state.tls) caps.push("STARTTLS");
446
+ caps.push("ENHANCEDSTATUSCODES");
447
+ var lines = [greeting + " greets " + helo];
448
+ for (var i = 0; i < caps.length; i += 1) lines.push(caps[i]);
449
+ _writeMultiline(socket, REPLY_250_OK, lines);
450
+ } else {
451
+ _writeReply(socket, REPLY_250_OK, greeting + " greets " + helo);
452
+ }
453
+ _emit("mail.server.mx.helo",
454
+ { connectionId: state.id, verb: verb, helo: helo, tls: state.tls });
455
+ }
456
+
457
+ // ---- STARTTLS ---------------------------------------------------------
458
+ function _handleStartTls(state, socket) {
459
+ if (state.tls) {
460
+ _writeReply(socket, REPLY_503_BAD_SEQUENCE, "5.5.1 TLS already active");
461
+ return;
462
+ }
463
+ _writeReply(socket, REPLY_220_READY, "2.0.0 Ready to start TLS");
464
+ // STARTTLS-injection defense (CVE-2021-38371 Exim,
465
+ // CVE-2021-33515 Dovecot): clear the command buffer + body
466
+ // collector at upgrade time. Any commands pipelined (RFC 2920)
467
+ // BEFORE the TLS handshake are discarded — only commands sent
468
+ // on the post-handshake TLS socket are honored.
469
+ lineBuffer = "";
470
+ bodyCollector = null;
471
+ inDataBody = false;
472
+ var tlsSocket = new nodeTls.TLSSocket(socket, {
473
+ isServer: true,
474
+ secureContext: opts.tlsContext,
475
+ });
476
+ tlsSocket.on("secure", function () {
477
+ state.tls = true;
478
+ // After the handshake, the state machine restarts at EHLO
479
+ // (per RFC 3207 §4.2 — client MUST re-issue EHLO).
480
+ state.stage = "ehlo";
481
+ state.helo = null;
482
+ });
483
+ tlsSocket.on("error", function (err) {
484
+ _emit("mail.server.mx.tls_handshake_failed",
485
+ { connectionId: state.id, code: (err && err.code) || "unknown",
486
+ message: err && err.message }, "failure");
487
+ _closeConnection(socket);
488
+ });
489
+ tlsSocket.on("data", function (chunk) {
490
+ try { _ingestBytes(state, tlsSocket, chunk); }
491
+ catch (err) {
492
+ _emit("mail.server.mx.handler_threw",
493
+ { connectionId: state.id, error: (err && err.message) || String(err) },
494
+ "failure");
495
+ _closeConnection(tlsSocket);
496
+ }
497
+ });
498
+ }
499
+
500
+ // ---- MAIL FROM --------------------------------------------------------
501
+ function _handleMailFrom(state, socket, line) {
502
+ if (!state.tls && _requiresStartTls()) {
503
+ _writeReply(socket, REPLY_530_AUTH_REQUIRED, "5.7.0 Must issue a STARTTLS command first");
504
+ return;
505
+ }
506
+ if (state.stage !== "ehlo" && state.stage !== "mail") {
507
+ _writeReply(socket, REPLY_503_BAD_SEQUENCE, "5.5.1 EHLO/HELO first");
508
+ return;
509
+ }
510
+ var match = line.match(RE_MAIL_FROM);
511
+ if (!match) {
512
+ _writeReply(socket, REPLY_501_BAD_ARGS,
513
+ "5.5.4 Syntax: MAIL FROM:<address> [SIZE=n]");
514
+ return;
515
+ }
516
+ var mailFrom = match[1].toLowerCase();
517
+ var paramStr = match[2] || "";
518
+ var sizeMatch = paramStr.match(RE_SIZE);
519
+ if (sizeMatch) {
520
+ var declaredSize = parseInt(sizeMatch[1], 10);
521
+ if (declaredSize > maxMessageBytes) {
522
+ _writeReply(socket, REPLY_552_SIZE_EXCEEDED,
523
+ "5.3.4 Message size exceeds fixed maximum (" + maxMessageBytes + " bytes)");
524
+ return;
525
+ }
526
+ }
527
+ state.mailFrom = mailFrom;
528
+ state.stage = "rcpt";
529
+ state.rcpts = [];
530
+ _emit("mail.server.mx.mail_from",
531
+ { connectionId: state.id, mailFrom: mailFrom });
532
+ _writeReply(socket, REPLY_250_OK, "2.1.0 Sender OK");
533
+ }
534
+
535
+ // ---- RCPT TO ----------------------------------------------------------
536
+ function _handleRcptTo(state, socket, line) {
537
+ if (state.stage !== "rcpt") {
538
+ _writeReply(socket, REPLY_503_BAD_SEQUENCE, "5.5.1 MAIL FROM first");
539
+ return;
540
+ }
541
+ if (state.rcpts.length >= maxRcptsPerMsg) {
542
+ _writeReply(socket, REPLY_452_INSUFFICIENT_STG,
543
+ "4.5.3 Too many recipients (limit " + maxRcptsPerMsg + ")");
544
+ return;
545
+ }
546
+ var match = line.match(RE_RCPT_TO);
547
+ if (!match) {
548
+ _writeReply(socket, REPLY_501_BAD_ARGS, "5.5.4 Syntax: RCPT TO:<address>");
549
+ return;
550
+ }
551
+ var rcpt = match[1].toLowerCase();
552
+ // Local-domain check — refuse non-local recipients unless the
553
+ // operator explicitly allowed relay for this scope.
554
+ if (localDomains.length > 0) {
555
+ var atIdx = rcpt.lastIndexOf("@");
556
+ var rcptDomain = atIdx === -1 ? "" : rcpt.slice(atIdx + 1);
557
+ if (localDomains.indexOf(rcptDomain) === -1 &&
558
+ !_isRelayAllowed(state.remoteAddress, rcpt)) {
559
+ _emit("mail.server.mx.relay_refused",
560
+ { connectionId: state.id, mailFrom: state.mailFrom, rcptTo: rcpt,
561
+ remoteAddress: state.remoteAddress }, "denied");
562
+ _writeReply(socket, REPLY_550_MAILBOX_UNAVAIL, "5.7.1 Relaying denied");
563
+ return;
564
+ }
565
+ }
566
+ state.rcpts.push(rcpt);
567
+ _emit("mail.server.mx.rcpt_to",
568
+ { connectionId: state.id, rcptTo: rcpt, rcptCount: state.rcpts.length });
569
+ _writeReply(socket, REPLY_250_OK, "2.1.5 Recipient OK");
570
+ }
571
+
572
+ // ---- DATA -------------------------------------------------------------
573
+ function _handleData(state, socket) {
574
+ if (state.stage !== "rcpt" || state.rcpts.length === 0) {
575
+ _writeReply(socket, REPLY_503_BAD_SEQUENCE, "5.5.1 No valid recipients");
576
+ return;
577
+ }
578
+ _writeReply(socket, REPLY_354_START_INPUT,
579
+ "End data with <CR><LF>.<CR><LF>");
580
+ state.stage = "data-body";
581
+ inDataBody = true;
582
+ bodyCollector = safeBuffer.boundedChunkCollector({
583
+ maxBytes: maxMessageBytes,
584
+ errorClass: MailServerMxError,
585
+ sizeCode: "mail-server-mx/body-too-large",
586
+ sizeMessage: "DATA body exceeded maxMessageBytes (" + maxMessageBytes + ")",
587
+ });
588
+ }
589
+
590
+ function _finalizeDataBody(state, socket, body) {
591
+ // body is the raw bytes BEFORE dot-stuffing reversal. RFC 5321
592
+ // §4.5.2 — a single leading "." is doubled on the wire; undo.
593
+ var dedotted = safeSmtp.dotUnstuff(body);
594
+ // operator-supplied agent handoff — when wired, persist via
595
+ // agent + write the 250 reply. When not wired, accept-and-drop
596
+ // (audit-only mode useful for staging deployments).
597
+ if (opts.agent && typeof opts.agent.handoff === "function") {
598
+ opts.agent.handoff({
599
+ mailFrom: state.mailFrom,
600
+ rcpts: state.rcpts.slice(),
601
+ body: dedotted,
602
+ remote: { address: state.remoteAddress, port: state.remotePort },
603
+ tls: state.tls,
604
+ helo: state.helo,
605
+ connectionId: state.id,
606
+ }).then(function (ack) {
607
+ _emit("mail.server.mx.delivered",
608
+ { connectionId: state.id, messageId: ack && ack.messageId, sizeBytes: dedotted.length });
609
+ _writeReply(socket, REPLY_250_OK,
610
+ "2.6.0 Message accepted" + (ack && ack.messageId ? " <" + ack.messageId + ">" : ""));
611
+ _resetTransaction(state);
612
+ }).catch(function (err) {
613
+ _emit("mail.server.mx.data_refused",
614
+ { connectionId: state.id, reason: "agent-handoff-failed",
615
+ error: (err && err.message) || String(err) }, "failure");
616
+ _writeReply(socket, REPLY_451_LOCAL_ERROR,
617
+ "4.3.0 Local delivery error");
618
+ _resetTransaction(state);
619
+ });
620
+ return;
621
+ }
622
+ _emit("mail.server.mx.data_accepted",
623
+ { connectionId: state.id, mailFrom: state.mailFrom, rcptCount: state.rcpts.length,
624
+ sizeBytes: dedotted.length });
625
+ _writeReply(socket, REPLY_250_OK, "2.6.0 Message queued (audit-only)");
626
+ _resetTransaction(state);
627
+ }
628
+
629
+ function _resetTransaction(state) {
630
+ state.mailFrom = null;
631
+ state.rcpts = [];
632
+ state.stage = "ehlo";
633
+ state.messageBytes = 0;
634
+ }
635
+
636
+ function _requiresStartTls() {
637
+ // Strict / balanced require STARTTLS before MAIL FROM.
638
+ // Permissive accepts plaintext — operator-acknowledged downgrade
639
+ // for legacy infrastructure.
640
+ return profile === "strict" || profile === "balanced";
641
+ }
642
+
643
+ function _isRelayAllowed(_remoteAddress, _rcptTo) {
644
+ // Operator-supplied relayAllowedFor entries. v1 just checks
645
+ // presence in the array; CIDR/scope matching could be wired
646
+ // via b.middleware.networkAllowlist in a follow-up.
647
+ if (relayAllowedFor.length === 0) return false;
648
+ return true;
649
+ }
650
+ }
651
+
652
+ // ---- Lifecycle ----------------------------------------------------------
653
+ async function listen(listenOpts) {
654
+ listenOpts = listenOpts || {};
655
+ if (listening) {
656
+ throw new MailServerMxError("mail-server-mx/already-listening",
657
+ "listen: already listening");
658
+ }
659
+ // Port 0 (ephemeral, test mode) must NOT fall back to 25 — the
660
+ // `|| 25` short-circuit was a footgun on the test path.
661
+ var port = listenOpts.port === undefined ? 25 : listenOpts.port; // allow:raw-byte-literal — SMTP MX port (IANA)
662
+ var address = listenOpts.address || "0.0.0.0";
663
+ tcpServer = net.createServer(function (socket) {
664
+ _handleConnection(socket);
665
+ });
666
+ return new Promise(function (resolve, reject) {
667
+ tcpServer.once("error", reject);
668
+ tcpServer.listen(port, address, function () {
669
+ listening = true;
670
+ tcpServer.removeListener("error", reject);
671
+ _emit("mail.server.mx.listening", {
672
+ port: port, address: address,
673
+ });
674
+ resolve({ port: tcpServer.address().port, address: address });
675
+ });
676
+ });
677
+ }
678
+
679
+ async function close(closeOpts) {
680
+ closeOpts = closeOpts || {};
681
+ if (!listening) return;
682
+ var timeoutMs = closeOpts.timeoutMs || C.TIME.seconds(30);
683
+ listening = false;
684
+ tcpServer.close();
685
+ connections.forEach(function (sock) {
686
+ try { _writeReply(sock, REPLY_421_SERVICE_NOT_AVAIL, "4.3.0 Server shutting down"); }
687
+ catch (_e) { /* socket already gone */ }
688
+ });
689
+ var deadline = Date.now() + timeoutMs;
690
+ while (connections.size > 0 && Date.now() < deadline) {
691
+ await safeAsync.sleep(100); // allow:raw-time-literal — close-drain poll interval (sub-second; operator-bounded by timeoutMs)
692
+ }
693
+ connections.forEach(function (sock) {
694
+ try { sock.destroy(); } catch (_e) { /* best-effort */ }
695
+ });
696
+ connections.clear();
697
+ _emit("mail.server.mx.closed", {});
698
+ }
699
+
700
+ function connectionCount() { return connections.size; }
701
+
702
+ return {
703
+ listen: listen,
704
+ close: close,
705
+ connectionCount: connectionCount,
706
+ _portForTest: function () { return tcpServer ? tcpServer.address().port : null; },
707
+ };
708
+ }
709
+
710
+ // ---- Wire-protocol helpers --------------------------------------------------
711
+
712
+ function _writeReply(socket, code, text) {
713
+ // Single-line reply per RFC 5321 §4.2 — code SP text CRLF.
714
+ try { socket.write(code + " " + text + "\r\n"); }
715
+ catch (_e) { /* socket already closed */ }
716
+ }
717
+
718
+ function _writeMultiline(socket, code, lines) {
719
+ // Multi-line reply per RFC 5321 §4.2 — code "-" text CRLF for
720
+ // continuation, code SP text CRLF for the final line.
721
+ for (var i = 0; i < lines.length; i += 1) {
722
+ var sep = i === lines.length - 1 ? " " : "-";
723
+ try { socket.write(code + sep + lines[i] + "\r\n"); }
724
+ catch (_e) { /* socket already closed */ }
725
+ }
726
+ }
727
+
728
+ function _closeConnection(socket) {
729
+ try { socket.end(); } catch (_e) { /* best-effort */ }
730
+ try { socket.destroy(); } catch (_e) { /* best-effort */ }
731
+ }
732
+
733
+ module.exports = {
734
+ create: create,
735
+ MailServerMxError: MailServerMxError,
736
+ };