// An SMTP server the server sends its email through (spec/EMAIL.md, // "SMTP"): over `node:net`, on the loopback, plain text, offering no // STARTTLS, and AUTH PLAIN and LOGIN, which it requires, with the user and // password it was made with. It takes EHLO, HELO, AUTH, MAIL FROM, RCPT TO, // DATA, RSET, NOOP and QUIT, and keeps each message whose data it read, // with its envelope and whether it refused it: while `refusing` is set, it // answers the end of each message's data `554`. import { createServer } from 'node:net' /// Each line it answers, as the reply of `code` and `text`. const reply = (code, text) => `${code} ${text}\r\n` /// The SMTP server, once listening: `{url, from, refusing, take(), close()}` /// (see `startSmtp`), or null before. let sink = null export const smtpSink = () => sink /// A command's argument as sent: the socket is read as latin1, a byte to a /// character, and SMTPUTF8 addresses are UTF-8. const utf8 = (s) => Buffer.from(s, 'latin1').toString('utf8') /// Start the SMTP server, requiring `user` and `password` to sign in, for a /// server whose emails are to be from `from`; or answer the one started /// already, so that a server started again sends to the same one. Answers /// `{url, from, refusing, take(), close()}`: `url` is /// `smtp://user:password@127.0.0.1:port`, each percent-encoded; `refusing`, /// false at first, makes it refuse each message at the end of its data /// while set; and `take()` answers what it read since it was last called, /// oldest first: each message `{from, to, data, refused}`, the envelope's /// sender and recipients as given, without `<>`, and the data /// dot-unstuffed, its lines joined by `\r\n`; and each command it refused /// as `{problem, line}`, as a client that signs in wrongly or not at all. export async function startSmtp({ user, password, from }) { if (sink) return sink const got = [] const server = createServer((socket) => { socket.setEncoding('latin1') let buf = '' let authed = false let login = null let mail = null let data = null const send = (code, text) => socket.write(reply(code, text)) const problem = (why, line) => got.push({ problem: why, line }) const credentials = (u, p) => { if (u === user && p === password) { authed = true return send(235, '2.7.0 Authentication successful') } problem('AUTH with other credentials than PDS_EMAIL_SMTP_URL gives', JSON.stringify({ user: u, password: p })) send(535, '5.7.8 Authentication credentials invalid') } const b64 = (s) => Buffer.from(s, 'base64').toString('utf8') const line = (l) => { if (data) { if (l !== '.') return void data.push(l.startsWith('.') ? l.slice(1) : l) const message = { from: mail.from, to: mail.to, data: Buffer.from(data.join('\r\n'), 'latin1').toString('utf8'), refused: sink.refusing } got.push(message) data = null mail = null return message.refused ? send(554, '5.6.0 Message refused') : send(250, '2.0.0 OK') } if (login) { const step = login if (step.user === undefined) { login = { user: b64(l) } return send(334, 'UGFzc3dvcmQ6') } login = null return credentials(step.user, b64(l)) } const [verb, ...rest] = l.split(' ') const arg = rest.join(' ') switch (verb.toUpperCase()) { case 'EHLO': mail = null return socket.write('250-pds-harness.test\r\n250-8BITMIME\r\n250-AUTH PLAIN LOGIN\r\n250 SMTPUTF8\r\n') case 'HELO': mail = null return send(250, 'pds-harness.test') case 'AUTH': { const [mech, initial] = arg.split(' ') if (mech?.toUpperCase() === 'PLAIN') { if (!initial) { login = { plain: true } return send(334, '') } const [, u, p] = b64(initial).split('\0') return credentials(u, p) } if (mech?.toUpperCase() === 'LOGIN') { if (initial) { login = { user: b64(initial) } return send(334, 'UGFzc3dvcmQ6') } login = {} return send(334, 'VXNlcm5hbWU6') } problem('AUTH by a mechanism not offered', l) return send(504, '5.5.4 Unrecognized authentication type') } case 'MAIL': { const m = /^FROM:\s*<([^>]*)>/i.exec(arg) if (!m) return send(501, '5.5.4 Syntax: MAIL FROM:
') if (!authed) { problem('MAIL FROM without signing in', l) return send(530, '5.7.0 Authentication required') } mail = { from: utf8(m[1]), to: [] } return send(250, '2.1.0 OK') } case 'RCPT': { const m = /^TO:\s*<([^>]*)>/i.exec(arg) if (!mail) return send(503, '5.5.1 MAIL first') if (!m) return send(501, '5.5.4 Syntax: RCPT TO:
') mail.to.push(utf8(m[1])) return send(250, '2.1.5 OK') } case 'DATA': if (!mail?.to.length) return send(503, '5.5.1 RCPT first') data = [] return send(354, 'End data with .') case 'RSET': mail = null return send(250, '2.0.0 OK') case 'NOOP': return send(250, '2.0.0 OK') case 'QUIT': send(221, '2.0.0 Bye') return socket.end() default: return send(502, '5.5.2 Command not implemented') } } // AUTH PLAIN's credentials on a line of their own, after a 334. const next = (l) => { if (login?.plain) { login = null const [, u, p] = b64(l).split('\0') return credentials(u, p) } line(l) } socket.on('data', (chunk) => { buf += chunk for (let i; (i = buf.indexOf('\r\n')) !== -1; ) { const l = buf.slice(0, i) buf = buf.slice(i + 2) next(l) } }) socket.on('error', () => {}) send(220, 'pds-harness.test ESMTP') }) await new Promise((ok) => server.listen(0, '127.0.0.1', ok)) const enc = encodeURIComponent sink = { url: `smtp://${enc(user)}:${enc(password)}@127.0.0.1:${server.address().port}`, from, refusing: false, take: () => got.splice(0), close: () => server.close(), } return sink } // ------------------------------------------------------------ messages /// A message's header fields and body, `data` as the SMTP server kept it: /// `{headers, text}`, the headers by lower-case name, unfolded, each a list /// of values, and `text` every text part of the body, decoded from base64 /// or quoted-printable, joined. export function parseMessage(data) { const { headers, body } = split(data) return { headers, text: textOf(headers, body) } } /// A message's type and, for a multipart one, each of its parts' types and /// decoded text, in order: `{type, parts: [{type, text}]}`, the types /// without their parameters, in lower case. A message of one part has /// that part alone. export function partsOf(data) { const { headers, body } = split(data) const full = headers['content-type']?.[0] ?? 'text/plain' const bare = (t) => t.split(';')[0].trim().toLowerCase() const boundary = /boundary="?([^";]+)"?/i.exec(full)?.[1] if (!/^multipart\//i.test(full) || !boundary) return { type: bare(full), parts: [{ type: bare(full), text: textOf(headers, body) }] } const raw = body.split(new RegExp(`\\r?\\n?--${boundary.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(?:--)?[ \\t]*\\r?\\n?`)).slice(1, -1) const parts = raw.map((p) => { const s = split(p) return { type: bare(s.headers['content-type']?.[0] ?? 'text/plain'), text: textOf(s.headers, s.body) } }) return { type: bare(full), parts } } function split(raw) { const at = raw.search(/\r?\n\r?\n/) const head = at === -1 ? raw : raw.slice(0, at) const body = at === -1 ? '' : raw.slice(at).replace(/^\r?\n\r?\n/, '') const headers = {} for (const field of head.split(/\r?\n(?![ \t])/)) { const c = field.indexOf(':') if (c === -1) continue const name = field.slice(0, c).trim().toLowerCase() ;(headers[name] ??= []).push(field.slice(c + 1).replace(/\r?\n[ \t]/g, ' ').trim()) } return { headers, body } } function textOf(headers, body) { const type = headers['content-type']?.[0] ?? 'text/plain' const boundary = /boundary="?([^";]+)"?/i.exec(type)?.[1] if (/^multipart\//i.test(type) && boundary) { const parts = body.split(new RegExp(`\\r?\\n?--${boundary.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(?:--)?[ \\t]*\\r?\\n?`)).slice(1, -1) return parts.map((p) => { const s = split(p) return textOf(s.headers, s.body) }).join('\n') } if (!/^text\//i.test(type)) return '' const cte = (headers['content-transfer-encoding']?.[0] ?? '7bit').toLowerCase() if (cte === 'base64') return Buffer.from(body.replace(/\s+/g, ''), 'base64').toString('utf8') if (cte === 'quoted-printable') return quotedPrintable(body) return body } function quotedPrintable(s) { const bytes = [] const soft = s.replace(/=\r?\n/g, '') for (let i = 0; i < soft.length; i++) { if (soft[i] === '=' && /^[0-9A-Fa-f]{2}$/.test(soft.slice(i + 1, i + 3))) { bytes.push(parseInt(soft.slice(i + 1, i + 3), 16)) i += 2 } else bytes.push(...Buffer.from(soft[i], 'utf8')) } return Buffer.from(bytes).toString('utf8') } /// A header field's value with its RFC 2047 encoded words decoded. export function decodeWords(v) { return v.replace(/=\?([^?]+)\?([BbQq])\?([^?]*)\?=(\s+(?==\?))?/g, (_, _charset, enc, text) => enc.toUpperCase() === 'B' ? Buffer.from(text, 'base64').toString('utf8') : quotedPrintable(text.replace(/_/g, ' '))) } /// The address of a mailbox header value: `Name `, or `a@b`. export const addressOf = (v) => (/<([^>]*)>\s*$/.exec(v)?.[1] ?? v).trim()