Watch
1
0
Fork
You've already forked packages
0
packages/email/tests/email.test.weft
Weft packages 306b143104 packages/ at markup-kit dd1e6eb5270e
A snapshot of packages/ in the Weft repository; the official packages are published from these commits.

Markup-Kit-Commit: dd1e6eb5270e62e0c8b6c202b3d01f0da6e00ddc
2026-11-19 20:43:26 +00:00

451 lines
13 KiB
Text

// `weft test tests/email.test.weft`: messages, MIME, the providers' payloads and templates. packages/integration/email sends
// through both providers' APIs against a scripted server, and checks the MIME with Python's parser.
import { assert, assertEq, assertPanics, mount } from "std/testing"
import { stringify } from "std/json"
import { allowlist, clearOutbox, isValidEmail, memory, outbox, send, validate } from "../email"
import type { EmailError, Message } from "../email"
import { encodeHeader, formatAddress, quotedPrintable, toMime } from "../mime"
import * as postmark from "../postmark"
import * as resend from "../resend"
import { render } from "std/app"
import { document } from "../template"
import Broken from "./Broken"
import Escapes from "./Escapes"
import Everything from "./Everything"
import Mailto from "./Mailto"
import Unsafe from "./Unsafe"
fn message(): Message {
return { from: "info@example.com", to: ["ana@example.com"], subject: "Hello", text: "Hi" }
}
fn edit(change: (mut m: Message) => void): Message {
let mut m = message()
change(&m)
return m
}
fn problem(m: Message): string {
let _, err = try validate(m)
return match err {
InvalidMessage { field } => field,
null => "valid",
_ => "other",
}
}
// ---- validation ----
test "a good message is valid" {
assertEq(problem(message()), "valid")
assertEq(
problem(
edit((mut m) => {
m.to = [{ email: "ana@example.com", name: "Ana Novak" }]
m.html = "<p>Hi</p>"
}),
),
"valid",
)
}
test "addresses" {
for good of ["a@b.co", "first.last+tag@sub.example.com", "čebela@example.si"] {
assert(isValidEmail(good), good)
}
for bad of [
"",
"a",
"a@",
"@b.co",
"a@@b.co",
"a b@c.co",
"a@b..co",
"a@.b.co",
"a@b.co.",
"a<b@c.co",
"a,b@c.co",
"a@b.co\r\nBcc: x@y.z",
] {
assert(!isValidEmail(bad), bad)
}
}
test "what a message can't be sent without" {
assertEq(
problem(
edit((mut m) => {
m.to = []
}),
),
"to",
)
assertEq(
problem(
edit((mut m) => {
m.subject = " "
}),
),
"subject",
)
assertEq(
problem(
edit((mut m) => {
m.text = ""
}),
),
"html",
)
assertEq(
problem(
edit((mut m) => {
m.from = "nobody"
}),
),
"from",
)
assertEq(
problem(
edit((mut m) => {
m.to = ["nobody"]
}),
),
"to",
)
assertEq(
problem(
edit((mut m) => {
m.cc = ["nobody"]
}),
),
"cc",
)
assertEq(
problem(
edit((mut m) => {
m.bcc = ["nobody"]
}),
),
"bcc",
)
assertEq(
problem(
edit((mut m) => {
m.replyTo = "nobody"
}),
),
"replyTo",
)
}
test "header injection is refused" {
assertEq(
problem(
edit((mut m) => {
m.subject = "Hi\r\nBcc: victim@example.com"
}),
),
"subject",
)
assertEq(
problem(
edit((mut m) => {
m.subject = "Hi\nBcc: victim@example.com"
}),
),
"subject",
)
assertEq(
problem(
edit((mut m) => {
m.from = { email: "a@b.co", name: "A\r\nBcc: v@x.y" }
}),
),
"from",
)
assertEq(
problem(
edit((mut m) => {
m.to = [{ email: "a@b.co", name: "A\nX: y" }]
}),
),
"to",
)
assertEq(
problem(
edit((mut m) => {
m.headers = [["X-Tag", "a\r\nBcc: v@x.y"]]
}),
),
"headers",
)
assertEq(
problem(
edit((mut m) => {
m.headers = [["Bad Name", "a"]]
}),
),
"headers",
)
assertEq(
problem(
edit((mut m) => {
m.headers = [["X:Y", "a"]]
}),
),
"headers",
)
assertEq(
problem(
edit((mut m) => {
m.attachments = [{ filename: "a\r\nb.txt", content: Bytes.of([1]) }]
}),
),
"attachments",
)
}
// ---- sending ----
test "send validates, then hands the message to the transport" {
clearOutbox()
let sent = try await send(memory(), message())
assertEq(sent.provider, "memory")
assertEq(outbox().length, 1)
let _, err = try await send(
memory(),
edit((mut m) => {
m.to = []
}),
)
assert(err != null)
assertEq(outbox().length, 1)
}
test "an allowlist keeps other recipients from being sent to" {
clearOutbox()
let staging = allowlist(memory(), ["info@vidni.si"])
let skipped = try await send(staging, message())
assert(skipped.skipped)
assertEq(outbox().length, 0)
let sent = try await send(
staging,
edit((mut m) => {
m.to = ["INFO@vidni.si "]
}),
) else null
assert(sent == null, "an address with a space is invalid")
let allowed = try await send(
staging,
edit((mut m) => {
m.to = ["INFO@vidni.si"]
}),
)
assert(!allowed.skipped)
assertEq(outbox().length, 1)
// One recipient outside the list keeps the whole message back.
let mixed = try await send(
staging,
edit((mut m) => {
m.to = ["info@vidni.si"]
m.cc = ["ana@example.com"]
}),
)
assert(mixed.skipped)
let open = try await send(allowlist(memory(), ["*"]), message())
assert(!open.skipped)
}
// ---- MIME ----
test "headers stay ASCII" {
assertEq(encodeHeader("Hello"), "Hello")
assertEq(encodeHeader("Račun št. 5"), "=?UTF-8?B?UmHEjXVuIMWhdC4gNQ==?=")
// A long subject is split between characters, each encoded word at most 75 characters long.
for word of encodeHeader("č".repeat(100)).split("\r\n ") {
assert(word.length <= 75, word)
}
assertEq(formatAddress("a@b.co"), "a@b.co")
assertEq(
formatAddress({ email: "a@b.co", name: "Ana \"N\" Novak" }),
"\"Ana \\\"N\\\" Novak\" <a@b.co>",
)
assertEq(formatAddress({ email: "a@b.co", name: "Žiga" }), "=?UTF-8?B?xb1pZ2E=?= <a@b.co>")
}
test "quoted-printable" {
assertEq(quotedPrintable("a=b"), "a=3Db")
assertEq(quotedPrintable("č"), "=C4=8D")
assertEq(quotedPrintable("line one\nline two"), "line one\r\nline two")
assertEq(quotedPrintable("trailing space "), "trailing space=20")
for line of quotedPrintable("x".repeat(500)).split("\r\n") {
assert(line.length <= 76, line)
}
// A multi-byte character isn't split across a soft line break.
for line of quotedPrintable("č".repeat(100)).split("\r\n") {
assert(line.length <= 76 && !line.replace("=", "").endsWith("C4="), line)
}
}
test "a text message" {
let mime = toMime(message(), { id: "fixed", date: "Tue, 17 Nov 2026 10:00:00 +0000" })
assertEq(
mime,
"From: info@example.com\r\nTo: ana@example.com\r\nSubject: Hello\r\nDate: Tue, 17 Nov 2026 10:00:00 +0000\r\nMessage-ID: <fixed@example.com>\r\nMIME-Version: 1.0\r\nContent-Type: text/plain; charset=UTF-8\r\nContent-Transfer-Encoding: quoted-printable\r\n\r\nHi\r\n",
)
}
test "html and text, attachments and inline images nest in the right order" {
let mime = toMime(
edit((mut m) => {
m.html = "<p>Hi</p><img src=\"cid:logo\">"
m.attachments = [
{ filename: "racun.pdf", content: Bytes.of([1, 2, 3]), type: "application/pdf" },
{ filename: "logo.png", content: Bytes.of([4]), type: "image/png", contentId: "logo" },
]
}),
{ id: "x" },
)
assert(mime.includes("multipart/mixed"))
assert(mime.indexOf("multipart/mixed") < mime.indexOf("multipart/related"))
assert(mime.indexOf("multipart/related") < mime.indexOf("multipart/alternative"))
assert(mime.includes("Content-Disposition: attachment; filename=\"racun.pdf\""))
assert(mime.includes("Content-Disposition: inline; filename=\"logo.png\"\r\nContent-ID: <logo>"))
assert(mime.includes("\r\n\r\nAQID\r\n"))
}
test "bcc is never written, and every line ends in CRLF" {
let mime = toMime(
edit((mut m) => {
m.bcc = ["secret@example.com"]
m.html = "<p>a\nb</p>"
}),
{ id: "x" },
)
assert(!mime.includes("secret@example.com"))
assert(!mime.replaceAll("\r\n", "").includes("\n"))
}
test "a file name outside ASCII" {
let mime = toMime(
edit((mut m) => {
m.attachments = [{ filename: "račun.pdf", content: Bytes.of([1]) }]
}),
{ id: "x" },
)
assert(mime.includes("filename*=UTF-8''ra%C4%8Dun.pdf"))
}
// ---- the providers ----
fn full(): Message {
return {
from: { email: "info@example.com", name: "Vidni" },
to: ["ana@example.com", { email: "bor@example.com", name: "Bor" }],
cc: ["c@example.com"],
bcc: ["d@example.com"],
replyTo: "owner@example.com",
subject: "Račun",
html: "<p>Hi</p>",
text: "Hi",
headers: [["List-Unsubscribe", "<https://example.com/u>"]],
attachments: [
{
filename: "a.ics",
content: Bytes.fromUtf8("BEGIN"),
type: "text/calendar",
contentId: "cal",
},
],
}
}
test "Resend's payload" {
assertEq(
stringify(resend.payload(full())),
"{\"from\":\"\\\"Vidni\\\" <info@example.com>\",\"to\":[\"ana@example.com\",\"\\\"Bor\\\" <bor@example.com>\"],\"subject\":\"Račun\",\"cc\":[\"c@example.com\"],\"bcc\":[\"d@example.com\"],\"reply_to\":\"owner@example.com\",\"html\":\"<p>Hi</p>\",\"text\":\"Hi\",\"headers\":{\"List-Unsubscribe\":\"<https://example.com/u>\"},\"attachments\":[{\"filename\":\"a.ics\",\"content\":\"QkVHSU4=\",\"content_type\":\"text/calendar\",\"content_id\":\"cal\"}]}",
)
assertEq(
stringify(resend.payload(message())),
"{\"from\":\"info@example.com\",\"to\":[\"ana@example.com\"],\"subject\":\"Hello\",\"text\":\"Hi\"}",
)
}
test "Postmark's payload" {
assertEq(
stringify(postmark.payload(full(), "broadcast")),
"{\"From\":\"\\\"Vidni\\\" <info@example.com>\",\"To\":\"ana@example.com, \\\"Bor\\\" <bor@example.com>\",\"Subject\":\"Račun\",\"MessageStream\":\"broadcast\",\"Cc\":\"c@example.com\",\"Bcc\":\"d@example.com\",\"ReplyTo\":\"owner@example.com\",\"HtmlBody\":\"<p>Hi</p>\",\"TextBody\":\"Hi\",\"Headers\":[{\"Name\":\"List-Unsubscribe\",\"Value\":\"<https://example.com/u>\"}],\"Attachments\":[{\"Name\":\"a.ics\",\"Content\":\"QkVHSU4=\",\"ContentType\":\"text/calendar\",\"ContentID\":\"cid:cal\"}]}",
)
}
fn kind(e: EmailError): string {
return e.kind
}
test "providers' errors" {
assertEq(kind(resend.failureOf(422, null, null)), "Rejected")
assertEq(kind(resend.failureOf(401, null, null)), "Rejected")
assertEq(kind(resend.failureOf(500, null, null)), "ProviderFailure")
assertEq(
resend.failureOf(429, null, "30"),
RateLimited { message: "Resend answered 429", retryAfter: 30 },
)
assertEq(kind(postmark.failureOf(422, null)), "Rejected")
assertEq(kind(postmark.failureOf(429, null)), "RateLimited")
assertEq(kind(postmark.failureOf(503, null)), "ProviderFailure")
}
// ---- templates ----
test "everything shown in a template is escaped" {
let r = render(Escapes, { text: "<script>alert(1)</script> & co", url: "https://x.dev/?a=1&b=2" })
assert(!r.html.includes("<script>"))
assert(r.html.includes("&lt;script&gt;alert(1)&lt;/script&gt; &amp; co"))
assert(r.html.includes("href=\"https://x.dev/?a=1&amp;b=2\""))
}
test "unsafe links and images lose their address" {
let r = render(Unsafe)
assert(!r.html.includes("javascript:"))
assert(r.html.includes("click") && r.html.includes("press") && r.html.includes("a cat"))
assert(!r.text.includes("javascript:"))
}
test "the text version reads like a person wrote it" {
assertEq(
render(Everything).text,
"Thank you\n\nHi Ana, see your ticket (https://x.dev/t).\n\n- One\n- Two\n\n1. First\n2. Second\n\n---\n\nTotal: 19,99 €\nDate: 1. 12.\n\nPay (https://x.dev/pay)\n\nLogo\n\nsmall",
)
}
test "a mailto link's text doesn't repeat the address" {
assertEq(render(Mailto).text, "write to us (a@b.co)\n\nhttps://x.dev")
}
test "styles are inline, in forms mail clients read" {
let html = render(Everything).html
assert(html.includes("font-weight:700"))
assert(html.includes("margin-bottom:16px"))
assert(html.includes("#111111"))
assert(html.includes("alt=\"Logo\""))
for missing of ["class=", "var(", "oklch(", "rem", "<!--"] {
assert(!html.includes(missing), missing)
}
}
test "rendering leaves what is mounted alone" {
let view = mount(Mailto)
let before = view.text()
render(Everything)
assertEq(view.text(), before)
}
test "a panic while rendering is the caller's" {
assertPanics(() => render(Broken), "TypeError")
}
test "a whole document" {
let r = document(
render(Mailto),
{ title: "Receipt <1>", preheader: "Thanks", footer: "Vidni d.o.o.", lang: "sl" },
)
assert(r.html.startsWith("<!doctype html><html lang=\"sl\">"))
assert(r.html.includes("<title>Receipt &lt;1&gt;</title>"))
assert(r.html.includes("Thanks") && r.html.includes("Vidni d.o.o."))
assertEq(r.text, "write to us (a@b.co)\n\nhttps://x.dev\n\n--\nVidni d.o.o.\n")
}