// THE KERNEL'S SMTP SERVER MACHINE (`smtpServer`, from `@volter/world-core`): RFC 5321's mechanics every pack that serves an // SMTP server shares (a relay's submission server, a mailbox provider's receiving server: ADR 0032 §4), behind the kernel's // stream boundary (TwinStream). It frames a connection's bytes into commands, a message's data and an AUTH response, // carries them to the pack's front over the pack's own fetch (a private bridge the pack's key signs), and parses the // RFC's command arguments. What a server answers, which senders and recipients it takes and what it keeps stay in each // pack: its replies, its policy and its writes. The kernel names no vendor. docs/contributing/architecture.md, "Other // wires: lanes, headers and line protocols". // source: RFC 5321 §4.1.1.4 "In particular, the sequence \".\" (bare line feeds, without carriage returns) MUST NOT be treated as equivalent to . as the end of mail data indication." // source: RFC 5321 §4.5.2 "If the first character is a period and there are other characters on the line, the first character is deleted." import type { HandlerContext } from './derived-core.ts'; import type { TwinStream } from './twin-fetch.ts'; /** What a server's front answers the stream: its reply lines, the moved session, and whether the stream reads a * message's data next (`data`), an AUTH response (`auth`) or commands, or closes. */ export type SmtpAnswer = { replies: string[]; session: S; mode: 'command' | 'data' | 'auth'; close?: boolean }; /** The bridge between a connection and the pack's front: the header that carries the pack's key, the key, a fresh * session, and the pack's answer when its front cannot answer (its words for a local error). */ export type SmtpBridge = { header: string; key: () => string; fresh: () => S; failure: (session: S) => SmtpAnswer }; /** A connection's bytes framed as SMTP frames them, each piece posted to the pack's front (`smtpFront`) through its * fetch with the session the connection carries: commands are lines ended by CRLF; after a 354, the message's lines up * to the lone dot, their leading dot removed; after a 334, one line of AUTH response. Pipelined commands are answered * in order. */ export function smtpStream(fetch: (request: Request) => Response | Promise, bridge: SmtpBridge): TwinStream { return (sink, peer) => { const encoder = new TextEncoder(); const decoder = new TextDecoder(); let buffer = ''; let session = bridge.fresh(); let mode: SmtpAnswer['mode'] = 'command'; let data: string[] = []; let closed = false; let chain: Promise = Promise.resolve(); const post = async (body: Record): Promise => { if (closed) return; let a: SmtpAnswer; try { const res = await fetch(new Request('http://smtp.wire/', { method: 'POST', headers: { 'content-type': 'application/json', [bridge.header]: bridge.key(), 'x-forwarded-for': peer }, body: JSON.stringify({ session, ...body }) })); a = res.ok ? (await res.json()) as SmtpAnswer : bridge.failure(session); if (!Array.isArray(a.replies) || !a.session || !['command', 'data', 'auth'].includes(a.mode)) a = bridge.failure(session); } catch { a = bridge.failure(session); } session = a.session; mode = a.mode; sink.write(encoder.encode(a.replies.map((r) => `${r}\r\n`).join(''))); if (a.close) { closed = true; sink.end(); } }; const line = async (text: string): Promise => { if (mode === 'data') { if (text === '.') { const message = data.join('\r\n') + (data.length ? '\r\n' : ''); data = []; mode = 'command'; await post({ data: message }); return; } data.push(text.startsWith('.') ? text.slice(1) : text); return; } if (mode === 'auth') { await post({ response: text }); return; } await post({ line: decoder.decode(Uint8Array.from(text, (c) => c.charCodeAt(0))) }); }; const pump = (): void => { let at: number; while ((at = buffer.indexOf('\r\n')) >= 0) { const text = buffer.slice(0, at); buffer = buffer.slice(at + 2); chain = chain.then(() => line(text)); } }; // the session counts as the twin's open work from its connect to its close (ADR 0036 §8): a step settles only once // it has ended, whatever command it is between // the count a step's settle reads: no failure to report it is taken as reported (ADR 0036 §8, no door call swallows an // error into success). A connect not counted would let a settle read the twin quiet while the session runs, so the // session is refused, named, before it is served; a close not counted leaves the session counted open, which the // settle names at its bound, never as quiet const connection = async (open: boolean): Promise => { try { const answer = await fetch(new Request('http://smtp.wire/twin/connection', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ open }) })); const text = await answer.text(); return answer.ok ? null : `answered ${answer.status} ${text.slice(0, 200)}`; } catch (error) { return error instanceof Error ? error.message : String(error); } }; let ended = false; chain = chain.then(() => connection(true)).then((failed) => { if (failed === null) return post({ open: true }); process.stderr.write(`smtp: a connection from ${peer} could not be counted open at /twin/connection (${failed}); refused\n`); sink.write(encoder.encode('421 4.3.0 the session could not be counted open; try again\r\n')); closed = true; ended = true; sink.end(); }); return { data(chunk) { if (closed) return; buffer += Array.from(chunk, (b) => String.fromCharCode(b)).join(''); pump(); }, settled: () => chain, close() { closed = true; if (!ended) { ended = true; chain = chain.then(() => connection(false)).then((failed) => { if (failed !== null) process.stderr.write(`smtp: a connection from ${peer} could not be counted closed at /twin/connection (${failed}); it stays counted open\n`); }); } }, }; }; } /** What a pack's front does with each piece the stream carries: the greeting, a command line, a message's data, an AUTH * response (a server that takes none leaves it out). */ type SmtpServer = { open(): SmtpAnswer | Promise>; command(session: S, line: string): SmtpAnswer | Promise>; data(session: S, data: string): SmtpAnswer | Promise>; response?(session: S, response: string): SmtpAnswer | Promise>; }; /** The pack's front (its `around`): a request the stream signed with the pack's key is a piece of a connection, answered * by the pack's server; any other request is the pack's own (its doors and screens). */ export async function smtpFront(ctx: HandlerContext, next: (request?: Request) => Promise, bridge: SmtpBridge, server: SmtpServer): Promise { const request = ctx.call.request; if (!request.headers.has(bridge.header)) return next(); if (request.headers.get(bridge.header) !== bridge.key()) return new Response('not the server\'s wire', { status: 403 }); const w = (ctx.body ?? {}) as { session?: S; open?: boolean; line?: string; data?: string; response?: string }; const s = w.session ?? bridge.fresh(); if (w.open) return Response.json(await server.open()); if (w.data !== undefined) return Response.json(await server.data(s, w.data)); if (w.response !== undefined && server.response) return Response.json(await server.response(s, w.response)); return Response.json(await server.command(s, String(w.line ?? ''))); } /** A command's verb (upper-cased) and its argument. */ export function smtpCommand(line: string): { verb: string; arg: string } { const [verb = '', ...rest] = line.split(' '); return { verb: verb.toUpperCase(), arg: rest.join(' ') }; } /** The session machine's word on a command from where a session stands (the manifest's states): a refusal's reply, or * undefined to go on. */ export function smtpOrder(ctx: Pick, machine: string, stage: string, op: string, to?: string): string | undefined { const refusal = ctx.legal(machine, 'stage', op, stage, to); return refusal ? `${refusal.status} ${String(refusal.code)} ${refusal.message}` : undefined; } /** EHLO's multi-line 250 reply: the server's name, then each keyword. */ // source: RFC 5321 §4.1.1.1 "ehlo-ok-rsp" export const smtpEhlo = (keywords: string[]): string[] => keywords.map((k, i) => `250${i === keywords.length - 1 ? ' ' : '-'}${k}`); /** An address in angle brackets (``, `<>` for the null sender), or undefined when it is not one. */ function smtpAddress(arg: string): string | undefined { const m = /^<([^<>\s]*)>$/.exec(arg.trim()); if (!m) return undefined; const a = m[1]!; if (a === '') return ''; return /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(a) ? a : undefined; } /** An address's domain, lower-cased. */ export const smtpDomain = (address: string): string => address.slice(address.lastIndexOf('@') + 1).toLowerCase(); /** MAIL's argument: the sender and its SIZE, BODY and SMTPUTF8 parameters, or why it is refused (the pack words it). */ // source: RFC 5321 §4.1.1.2 "MAIL FROM: [SP ] " export function smtpMailFrom(arg: string): { from: string; size?: number; smtputf8: boolean } | { refused: 'syntax' | 'sender' | 'size' } | { refused: 'parameter'; parameter: string } { const m = /^FROM:\s*(<[^>]*>)((?:\s+\S+)*)\s*$/i.exec(arg); if (!m) return { refused: 'syntax' }; const from = smtpAddress(m[1]!); if (from === undefined) return { refused: 'sender' }; let size: number | undefined; let smtputf8 = false; for (const parameter of m[2]!.trim().split(/\s+/).filter(Boolean)) { const [k = '', v] = parameter.split('='); if (k.toUpperCase() === 'SIZE') { if (!/^\d+$/.test(v ?? '')) return { refused: 'size' }; size = Number(v); } else if (k.toUpperCase() === 'BODY' && ['7BIT', '8BITMIME'].includes((v ?? '').toUpperCase())) continue; else if (k.toUpperCase() === 'SMTPUTF8' && v === undefined) smtputf8 = true; else return { refused: 'parameter', parameter }; } return { from, ...(size !== undefined ? { size } : {}), smtputf8 }; } /** RCPT's argument: the recipient, or why it is refused (the pack words it). */ // source: RFC 5321 §4.1.1.3 "RCPT TO: [ SP ] " export function smtpRcptTo(arg: string): { to: string } | { refused: 'syntax' | 'recipient' } | { refused: 'parameter'; parameter: string } { const m = /^TO:\s*(<[^>]*>)(?:\s+\S+)*\s*$/i.exec(arg); if (!m) return { refused: 'syntax' }; // source: RFC 5321 §4.1.1.11 "command, it will return code 555." if (/^TO:\s*<[^>]*>\s+\S/i.test(arg)) return { refused: 'parameter', parameter: arg.slice(arg.indexOf('>') + 1).trim() }; const to = smtpAddress(m[1]!); return to ? { to } : { refused: 'recipient' }; } /** A transaction's state cleared, the greeting kept (RSET, a new EHLO, the end of DATA): the session's `stage`, * `greeted` and an empty `rcpt`, with whatever of the session the pack keeps across transactions (`kept`). */ // source: RFC 5321 §4.1.1.5 "This command specifies that the current mail transaction will be aborted." export function smtpCleared(s: S, stage: string, kept: Omit): Omit & { stage: string; rcpt: string[]; greeted?: 'helo' | 'ehlo' } { const greeted = stage === 'helo' || stage === 'ehlo' ? stage : s.greeted; return { ...kept, stage, rcpt: [], ...(greeted ? { greeted } : {}) }; }