Co-Authored-By: Claude Fable 5.2 <[email protected]>
65 lines
2.8 KiB
TypeScript
65 lines
2.8 KiB
TypeScript
import { createServer, type Server } from 'node:net'
|
|
|
|
export type SinkMessage = { data: string; to: string[] }
|
|
|
|
/**
|
|
* A mail sink for the smoke tests: just enough SMTP for nodemailer to log in and deliver. It keeps every
|
|
* message in memory, so a test can read what the site really sent (recipients, attachments).
|
|
* e2e/create-test-admin.ts points Site integrations → E-mail sending at it (127.0.0.1:E2E_SMTP_PORT).
|
|
*/
|
|
export function startSmtpSink(port: number): Promise<{ close: () => Promise<void>; messages: SinkMessage[] }> {
|
|
const messages: SinkMessage[] = []
|
|
const server: Server = createServer((socket) => {
|
|
const mail: SinkMessage = { data: '', to: [] }
|
|
let inData = false
|
|
let buffer = ''
|
|
const reply = (line: string) => socket.write(`${line}\r\n`)
|
|
reply('220 localhost ESMTP smoke-sink')
|
|
socket.on('error', () => undefined)
|
|
socket.on('data', (chunk) => {
|
|
buffer += chunk.toString('latin1')
|
|
let index: number
|
|
while ((index = buffer.indexOf('\r\n')) >= 0) {
|
|
const line = buffer.slice(0, index)
|
|
buffer = buffer.slice(index + 2)
|
|
if (inData) {
|
|
if (line === '.') {
|
|
inData = false
|
|
messages.push({ ...mail, to: [...mail.to] })
|
|
reply('250 2.0.0 Ok: queued')
|
|
} else {
|
|
mail.data += `${line}\n`
|
|
}
|
|
continue
|
|
}
|
|
const command = line.toUpperCase()
|
|
if (command.startsWith('EHLO')) {socket.write('250-localhost\r\n250-AUTH PLAIN LOGIN\r\n250 8BITMIME\r\n')}
|
|
else if (command.startsWith('AUTH PLAIN')) {reply('235 2.7.0 Authentication successful')}
|
|
else if (command.startsWith('MAIL FROM:')) {reply('250 2.1.0 Ok')}
|
|
else if (command.startsWith('RCPT TO:')) {
|
|
mail.to.push(line.slice(8).trim())
|
|
reply('250 2.1.5 Ok')
|
|
} else if (command === 'DATA') {
|
|
inData = true
|
|
reply('354 End data with <CR><LF>.<CR><LF>')
|
|
} else if (command === 'QUIT') {
|
|
reply('221 2.0.0 Bye')
|
|
socket.end()
|
|
} else {reply('502 5.5.2 Command not recognized')}
|
|
}
|
|
})
|
|
})
|
|
return new Promise((resolve, reject) => {
|
|
server.once('error', reject)
|
|
server.listen(port, '127.0.0.1', () => resolve({ close: () => new Promise((done) => server.close(() => done())), messages }))
|
|
})
|
|
}
|
|
|
|
/** The decoded bytes of the attachment named `filename` in a raw message, or null. */
|
|
export function attachmentOf(raw: string, filename: string): Buffer | null {
|
|
const at = raw.indexOf(`filename=${filename}`) >= 0 ? raw.indexOf(`filename=${filename}`) : raw.indexOf(`filename="${filename}"`)
|
|
if (at < 0) {return null}
|
|
const body = raw.slice(raw.indexOf('\n\n', at) + 2)
|
|
return Buffer.from(body.slice(0, body.indexOf('\n--')).replace(/\s+/g, ''), 'base64')
|
|
}
|