// Tests for mail-watch: the template, the SMTP client against fake // servers, and the watch (usage-log scan, quota scan, cooldown). Everything // runs in a temp config dir (MAGPIE_CONFIG_DIR); the real folder is never // touched. import { describe, test, expect, beforeAll, afterAll } from "bun:test" import { mkdtempSync, rmSync, writeFileSync, readFileSync, existsSync, mkdirSync } from "node:fs" import { tmpdir } from "node:os" import { join } from "node:path" import net from "node:net" import { execFileSync } from "node:child_process" const dir = mkdtempSync(join(tmpdir(), "mail-watch-test-")) // bun test runs every package in one process: put the variable back when done, // or other packages' children inherit this temp dir as magpie's config dir const prevConfigDir = process.env.MAGPIE_CONFIG_DIR process.env.MAGPIE_CONFIG_DIR = dir mkdirSync(join(dir, "magpie"), { recursive: true }) // the temp dir serves every describe block; it goes when the file's tests // are all done, not when the first block's are afterAll(() => { if (prevConfigDir === undefined) delete process.env.MAGPIE_CONFIG_DIR else process.env.MAGPIE_CONFIG_DIR = prevConfigDir rmSync(dir, { recursive: true, force: true }) }) const watch = await import("./watch.js") const { fill, message, renderHtml, DEFAULT_HTML } = await import("./template.js") const { send, resolveSmtp, PRESETS } = await import("./smtp.js") const { readDigest, baselineDigest } = await import("./digest.js") const { onResponse, digestScheduleForTests, resetDigestScheduleForTests, setDigestStepCapForTests } = await import("./mail-watch.hooks.js") // ---- the fake SMTP servers --------------------------------------------- // Two shapes, matching what the client speaks: // plain (startPlain) — a net server for the relay tests; records every // command and the DATA body. // secure (startSecure) — Bun's own TLS listener (implicit TLS, the 465 // shape). Bun's client-side STARTTLS upgrade does not survive against // a Node TLSSocket on every platform (handshake completes, the session // dies seconds later), so STARTTLS is not part of the client; the // secure tests run against the transport it actually uses. A // self-signed certificate made by openssl; a machine without it skips // the TLS tests. let server, got const cert = { key: null, cert: null } try { const p = join(dir, "key.pem"), c = join(dir, "cert.pem") execFileSync("openssl", ["req", "-x509", "-newkey", "rsa:2048", "-keyout", p, "-out", c, "-days", "1", "-nodes", "-subj", "/CN=localhost"], { stdio: "ignore" }) cert.key = readFileSync(p) cert.cert = readFileSync(c) } catch {} // smtpBrain is the dialog both servers speak: greeting, answers per // command, DATA collected until ".", QUIT ends. function smtpBrain(answers = {}) { got = { commands: [], body: "", bodyInData: false } return { open(s) { s.write("220 fake ready\r\n") }, data(s, d) { const text = d.toString("utf8") if (got.bodyInData) { got.body += text if (text.endsWith("\r\n.\r\n")) { got.bodyInData = false s.write("250 queued\r\n") } return } for (const line of text.split("\r\n").filter(Boolean)) { got.commands.push(line) if (line === "DATA") { got.bodyInData = true s.write("354 go\r\n") } else if (line === "QUIT") { s.write("221 bye\r\n") setTimeout(() => s.end(), 20) // let the 221 land before the FIN } else if (/^AUTH PLAIN/.test(line)) { s.write(answers.auth ?? "235 ok\r\n") } else if (answers.failRcpt && /^RCPT/.test(line)) { s.write("550 no such user\r\n") } else if (answers.failMailFrom && /^MAIL/.test(line)) { s.write("503 bad sender\r\n") } else { s.write("250 ok\r\n") } } }, } } function startPlain(answers = {}) { const brain = smtpBrain(answers) // a net socket speaks the same .write/.end the brain's Bun-style // handlers call, so the one dialog serves both servers server = net.createServer((s) => { brain.open(s) s.on("data", (d) => brain.data(s, d)) }) return new Promise((res) => server.listen(0, "127.0.0.1", () => res(server.address().port))) } function startSecure(answers = {}) { if (!cert.cert) return Promise.resolve(null) const brain = smtpBrain(answers) server = Bun.listen({ hostname: "127.0.0.1", port: 0, tls: { key: cert.key, cert: cert.cert }, socket: brain, }) return Promise.resolve(server.port) } // ---- template ------------------------------------------------------------ describe("template", () => { test("fill replaces {{name}} and leaves unknown braces", () => { expect(fill("a {{x}} b {{y}} c {{x}}", { x: "1" })).toBe("a 1 b c 1") expect(fill("keep {{not a var}}", {})).toBe("keep {{not a var}}") expect(fill("{{missing}}", {})).toBe("") }) test("message builds RFC 5322 headers and a base64 body", () => { const m = message({ from: "magpie@example.com", to: ["a@b.c"], subject: "s", body: "hi" }) expect(m).toContain("From: magpie@example.com\r\n") expect(m).toContain("To: a@b.c\r\n") expect(m).toContain("Subject: s\r\n") expect(m).toContain('Content-Type: text/plain; charset="utf-8"\r\n') expect(m.endsWith(Buffer.from("hi").toString("base64") + "\r\n")).toBe(true) }) test("message encodes a non-ASCII subject as RFC 2047 and a display name", () => { const m = message({ from: "喵喵 ", to: ["you@example.com"], subject: "额度用尽", body: "x" }) expect(m).toContain("Subject: =?UTF-8?B?") expect(m).toContain("From: =?UTF-8?B?") expect(m).toContain("") }) test("word splits long encoded subjects at the RFC 2047 limit", () => { const m = message({ from: "f@x.y", to: ["t@x.y"], subject: "很长的主题".repeat(20), body: "x" }) for (const line of m.split("\r\n")) { // each encoded word stays within RFC 2047 §2's 75 characters, and a // folded continuation line (the leading space) stays short if (line.startsWith("Subject:")) expect(line.length).toBeLessThanOrEqual(998) else if (line.startsWith(" =?")) { expect(line.length).toBeLessThanOrEqual(76) expect(line.trim().length).toBeLessThanOrEqual(75) } } }) test("every encoded word decodes on its own (whole codepoints, valid base64)", () => { // the failure mode this locks down: slicing the base64 at a fixed // width cuts quads mid-way, and each word decodes to shifted garbage const subjects = ["很长的主题".repeat(20), "[magpie] 额度用尽 · provider-account-with-a-long-name", "emoji 😀 mixed 中文 text"] for (const s of subjects) { const m = message({ from: "f@x.y", to: ["t@x.y"], subject: s, body: "x" }) const line = m.split("\r\n").filter((l) => l.startsWith("Subject:") || l.startsWith(" =?")).join(" ") const joined = line.replace(/^Subject: /, "").replace(/ \r?\n /g, "").replace(/ /g, "") const out = [...joined.matchAll(/=\?UTF-8\?B\?(.+?)\?=/g)].map((w) => Buffer.from(w[1], "base64").toString("utf8")).join("") expect(out).toBe(s) } }) test("addr keeps a display name with specials quoted", () => { const m = message({ from: '"Acme, Inc." ', to: ["t@x.y"], subject: "s", body: "x" }) expect(m).toContain('From: "Acme, Inc." ') }) test("addr keeps an injected name on one line, as quoted text", () => { // the CRLF is gone, so nothing becomes a header of its own; what the // attacker wrote remains inside the quoted display name const m = message({ from: 'bad\r\nBcc: x@y.z ', to: ["t@x.y"], subject: "s", body: "x" }) expect(m.split("\r\n")[0]).toBe('From: "bad Bcc: x@y.z" ') for (const line of m.split("\r\n")) expect(line.startsWith("Bcc:")).toBe(false) }) test("message with html is multipart/alternative and both parts decode", () => { const m = message({ from: "f@x.y", to: ["t@x.y"], subject: "s", body: "plain", html: "

rich

" }) expect(m).toContain('Content-Type: multipart/alternative; boundary="') const boundary = /boundary="([^"]+)"/.exec(m)[1] expect(m).toContain(`--${boundary}`) expect(m.endsWith(`--${boundary}--\r\n\r\n`)).toBe(true) // the plain part decodes to the text, the html part to the layout const parts = m.split(`--${boundary}`).slice(1, -1) const plain = Buffer.from(parts[0].split("\r\n\r\n")[1].replace(/\r\n/g, ""), "base64").toString("utf8") const rich = Buffer.from(parts[1].split("\r\n\r\n")[1].replace(/\r\n/g, ""), "base64").toString("utf8") expect(plain).toBe("plain") expect(rich).toBe("

rich

") }) test("renderHtml escapes vars into the user's layout and fills the default card", () => { // an error's words stay text in the user's own page const out = renderHtml("{{err}}", { err: "", provider: "p", time: "t" }) expect(out).toContain("<script>") expect(out).not.toContain("