Bladeren bron

feat(mail): ctx.mail, and a correction to a fact I had measured wrongly

The JS surface: ctx.mail.read, ctx.mail.mailboxes and ctx.mail.send.
Three calls, each one session and one LOGIN - a login per message is what
gets a mail account throttled. Reading uses EXAMINE and BODY.PEEK so it
never marks mail seen, and every message states whether its header and
text are text or base64, because mail is routinely not UTF-8 and assuming
otherwise is how accented mail turns into mojibake.

criteria is a STRUCTURED object, never raw IMAP syntax, so a script can
never write protocol. A non-ASCII criterion value is refused by field
name: expressing it needs a CHARSET UTF-8 literal exchange this transport
does not drive, and sending the bytes anyway makes the server match
nothing - which reads as "there is no such mail" rather than as an error.

Credentials prefer passwordSecret/userSecret, naming a project secret
resolved host-side, so anything that echoes an options object cannot leak
it. Mail hosts go through the SAME SSRF guard as ctx.fetch: resolved once,
every returned address classified, the approved one pinned. decideEgress
was narrowed to take a host string, which is all it ever read.

CORRECTION. An earlier commit recorded that a custom request's write
callback receives the tagged completion line. That was WRONG, and the
error was in the check rather than in the reasoning: it searched for
" OK ", which matched the untagged "* OK [UIDVALIDITY 1]". Measured by
byte count, curl consumes BOTH the closing paren and the tagged line. The
consequence is load-bearing - a SUCCESSFUL fetch's raw buffer is missing
the framing its literal announced and so parses as NeedMore, and a caller
reading that as "truncated" rejects every good fetch. The test now
asserts exact bytes, and the note in CLAUDE.md records that the earlier
claim was wrong and why, so the next person sees the trap and not only
the answer.

Also measured: a UID FETCH naming more than one uid delivers ZERO bytes,
so a multi-message read is one command per uid. And an absent uid
delivers zero bytes, which is Ok with no messages and is skipped -
nothing a returned message carries ever comes from the raw buffer, which
is what makes "the protocol line returned as the body" structurally
impossible here rather than merely absent.

Two fixes in the fake server, both of which could have hurt CI rather
than failing a test: stop() shut only the LISTENING socket, so a thread
blocked in recv on a live client never returned and the join hung
forever; and send without MSG_NOSIGNAL lets a vanished peer kill the
whole test process with SIGPIPE.

main.cpp now actually calls mailGlobalInit() before any worker thread
exists, failing closed if libcurl is not thread-safe. CLAUDE.md had
claimed it did; it did not, because that note was written from the design
rather than from the code.

1155 tests pass through the root build.
fszontagh 1 maand geleden
bovenliggende
commit
ee423649be

+ 3 - 1
CLAUDE.md

@@ -88,7 +88,9 @@ docker run -d --name svapi-dev -p 8080:8080 -e SMARTBOTIC_VECTORAPI_KEY=dev svap
 - **`runner_net` is a separate target for testability, not tidiness.** `runner_host` links `vectorapi_core` and the database client, so putting the IMAP and MIME code there would make the largest and most defect-prone part of the feature the one part only the Docker path can compile. The division at the boundary is strict: `runner_host` converts JS values to a plain request struct and back, and does nothing else - no curl call, no IMAP knowledge, no timeout arithmetic above that line.
 - **libcurl is VENDORED at `curl-8_22_0`** (`SVAPI_CURL_TAG`, `SVAPI_VENDOR_CURL=ON`; `OFF` links the system one and is what the dev loop uses, because vendoring costs minutes). The pin comment carries the obligations, and they are real: **CVE tracking is ours now**, a statically linked curl is invisible to `apt`, and a fix means a rebuild and a republish of both binaries rather than an unattended upgrade. Judge an advisory against **what this service reaches** - exactly `imaps`/`imap`/`smtps`/`smtp` - the same discipline the httplib pin uses. `PROXY` is compiled out rather than disabled per handle, because curl reads `*_proxy` from the environment where httplib does not and `runner.env` is a file an operator edits; a stray proxy variable would silently reroute a destination the SSRF guard had already approved. `NETRC` is out so credentials can only come from project secrets. Cookies/ALTSVC/HSTS are out because each is persistent cross-request state, which a multi-tenant pool must not accumulate. A build from a git tag reports its version as `8.22.0-DEV`.
 - **A fetch goes through `CURLOPT_CUSTOMREQUEST` with `BODY.PEEK[]`, NEVER curl's `;UID=` URL form.** Measured against a live server elsewhere: the URL form **always** sets `\Seen`. Undoing it afterwards with a `UID STORE -FLAGS` is worse than the disease - it removes a flag it may not have set, so a message the user had **already read comes back unread**, and a timeout between the fetch and the undo leaves the message read anyway, which is the exact outcome peek exists to prevent. A test asserts no `STORE`, `+FLAGS` or `-FLAGS` ever reaches the wire.
-- **`SELECT`'s untagged responses do NOT reach a custom request's write callback, but the tagged final line does.** Measured, and pinned by a test against the fake server, because a parser written for the other answer silently mis-reads every fetch. Also: a `BODY.PEEK[...]` fetch comes back labelled **`BODY[...]`** without the `.PEEK`, so a parser looking for the string it sent finds nothing.
+- **curl consumes the closing `)` AND the tagged completion line; untagged response lines are what reach the write callback.** Measured by byte count, which is the only way to see it: a fetch whose fake response was a 30-byte untagged line plus a 50-byte literal plus `)\r\n` plus the tagged `OK` delivered exactly 80 bytes. **An earlier version of this note claimed the tagged line DOES arrive, and that was wrong** - it came from a substring check for `" OK "` that matched `* OK [UIDVALIDITY 1]`, an untagged line. The consequence is real: a successful fetch's raw buffer legitimately parses as **`NeedMore`**, because the framing it was told to expect was never sent, so the binding restores the framing and re-parses rather than treating that as a short read. Restoring framing is safe only because it cannot satisfy an unsent `{n}`, so a genuinely truncated literal still reports `NeedMore`. Never resolve this with a terminator search. Separately: a `BODY.PEEK[...]` fetch comes back labelled **`BODY[...]`** without the `.PEEK`, so a parser looking for the string it sent finds nothing.
+- **A `UID FETCH` naming more than one uid delivers ZERO bytes to the write callback** (`7,9` and `7:9` both; a single `7` delivers normally). So a read is one command per uid, all on the one session and the one LOGIN. Measured; it is why the obvious batching optimisation does not work.
+- **A uid absent from the mailbox arrives as zero bytes, and that is `Ok` with no messages.** The caller skips it. Nothing a returned message carries ever comes from the raw buffer, which is what makes the "tagged completion line returned as the e-mail body" bug structurally impossible here rather than merely absent.
 - **curl dot-stuffs the payload it is given, so the renderer must not.** Both doing it corrupts any line beginning with a period; neither doing it truncates the message at a lone `.`. The renderer additionally emits a leading period as `=2E` in quoted-printable, so the protection holds either way.
 - **Non-ASCII IMAP SEARCH is REFUSED by field name, not sent.** Doing it properly needs `SEARCH CHARSET UTF-8` with the term as an octet-counted literal, which is a multi-step exchange the one-shot transport does not drive. Sending the raw bytes is **worse than failing**: the server matches nothing and zero results is indistinguishable from "there is no such mail". That shipped elsewhere and produced silently wrong answers against Hungarian mail. The refusal names the field and says to filter on an ASCII-safe criterion and match the accented text after fetching. Mailbox NAMES are unaffected and still go out as modified UTF-7.
 - **An SMTP refusal after DATA arrives as `CURLcode` 8 (`WEIRD_SERVER_REPLY`) with `CURLINFO_RESPONSE_CODE` 550.** So a reply code the server actually sent **wins over curl's generic transport complaint** for the generic codes; otherwise a bad recipient was reported as a protocol fault. Codes that already carry more meaning than a reply code, such as a denied login, keep their own answer. A 4xx reply is transient (`mail_server_busy`, 503), a 5xx is the caller's problem (`mail_rejected`, **422** - a 550 is overwhelmingly a bad recipient or a rejected sender, and blaming the server sends them looking in the wrong place).

+ 8 - 0
api/llms.txt

@@ -236,6 +236,14 @@ export default async function (ctx) {
 - **A blocking host call cannot be interrupted.** The run's wall budget is enforced between bytecode operations, so while an embedding or `ctx.fetch` request is in flight the deadline cannot be noticed - the budget ends the run once the call returns. Host calls are bounded by giving them timeouts that already fit the remaining budget (connect **and** read together), not by preemption. For a hard latency ceiling, catch the error and have a fallback path.
 - `ctx.fetch(url, {method, headers, body, timeoutMs, responseType})` - outbound HTTP, **SSRF-guarded**: loopback, private and link-local destinations are refused, which means a function cannot call this API back. The refusal is reported in the run's console rather than as a network error.
 - **A job, cron or db run's `ctx` is NOT the HTTP shape.** It carries `trigger`, `depth`, `enqueued_by` and `enqueued_at_ms`, with your payload under **`ctx.body`** - there is no `ctx.method`, `ctx.path`, `ctx.query` or `ctx.params`. A cron payload is `{schedule, scheduled_at}`; a database-event payload is `{collection, table, id, event, document}`.
+- `ctx.mail` - **IMAP read and SMTP send.** Three calls, deliberately few, each opening one session and closing it. Connection fields are shared: `host`, `port` (optional, 0 or absent means the scheme default), `user`/`userSecret`, `password`/`passwordSecret`, `tls` (default **true**), `startTls`, `timeoutMs`. **Prefer `passwordSecret`/`userSecret`**: they name a project secret resolved host-side, so an error or a log that echoes your options object cannot leak it and an operator can rotate it without a code push. A literal `password` is accepted, because `ctx.env` already hands your script the value anyway. Naming a secret that does not exist is **422** `mail_secret_missing`, which names the secret and never a value; passing both a literal and a secret name for the same credential is `ambiguous_body`. An unknown option key is **refused, not ignored**.
+  - `ctx.mail.read({mailbox, criteria, limit, ...})` -> `{messages: [...], matched: n}`. `mailbox` defaults to `INBOX`; `limit` defaults to 20 and is **capped at 200** (over it is refused, not clamped). `matched` is the size of the whole search result and `messages` the newest `limit` of it, so you can tell a full page from the end of the mailbox. Each message carries `uid`, `seq`, `flags`, `internal_date`, `size`, `header`, `text`, `body_sections` and a `headerEncoding`/`textEncoding` of `text` or `base64` - **mail is routinely not UTF-8**, so the encoding is stated rather than assumed. Reading uses `EXAMINE` and `BODY.PEEK`, so **it never marks mail as seen**.
+  - **`criteria` is a structured object, never raw IMAP syntax** - the only string accepted is `'ALL'` (the default). Fields: `since`, `before`, `from`, `to`, `subject`, `text`, `body`, `headerName`+`headerValue`, `unseen`, `seen`, `flagged`, `largerThanBytes`, `smallerThanBytes`. `headerName` and `headerValue` are one criterion in two halves and must both be given, because a server answers a half-stated one with a syntax error rather than with a match. **A non-ASCII criterion value is REFUSED** (naming the field): expressing it needs a multi-step `CHARSET UTF-8` literal exchange this transport does not drive, and sending the bytes anyway makes the server match nothing - and zero results is indistinguishable from "there is no such mail", which is a silently wrong answer rather than a missing feature. Filter on an ASCII-safe criterion, or on sender or date, and match accented text yourself after fetching. Mailbox NAMES are unaffected and may be non-ASCII.
+  - `ctx.mail.mailboxes({...})` -> `[{name, nameEncoding, flags, delimiter}]`. Names are decoded from IMAP's modified UTF-7, so `Beérkezett` arrives readable.
+  - `ctx.mail.send({from, to, cc, bcc, subject, text, html, attachments, replyTo, headers, inReplyTo, references, ...})` -> `{ok: true, accepted: [...]}`. `to`/`cc`/`bcc` take a string or an array. Structure is chosen for you: text only is `text/plain`, text plus `html` is `multipart/alternative`, and attachments wrap it in `multipart/mixed`. Attachments are `{filename, contentType, base64}`. **`bcc` recipients receive the message but appear in no header of it.** A non-ASCII subject, display name or filename is encoded correctly (RFC 2047, and RFC 2231 for filenames). An address, subject, filename or header containing CR or LF is **refused by name** - that is header injection.
+  - **Mail hosts go through the same SSRF guard as `ctx.fetch`**, so loopback, private and link-local destinations are refused (`egress_blocked`, with the guard's reason) and a function cannot reach a mail server on the API host. The name is resolved **once** and every address it returns is classified, then the approved address is pinned for the connection - re-resolving is the rebinding window. Plaintext (`tls:false, startTls:false`) to anything but a loopback literal is refused as `mail_tls_required`.
+  - **One run may load at most 4 MiB of mail**, independently of any mailbox size, because a run holds a pooled runtime with its own memory limit. Exceeding it is **413** `mail_too_large` - deliberately not a timeout, because the remedies differ and a caller told "timeout" for an oversized mailbox retries forever.
+  - **Slugs worth branching on**, each with `details.retryable`: `mail_timeout` **504**, `mail_too_large` **413**, `mail_incomplete` (the server stopped mid-message; retryable, since a peek fetch changed nothing), `mail_rejected` **422** (the server refused permanently, usually a bad recipient or sender - its reply text is included), `mail_server_busy` **503** (a transient 4xx; retryable), `mail_auth_failed` (**never** retryable - repeating a rejected login is how an account gets locked), `mail_tls_untrusted` (the certificate did not verify; never retried and never downgraded), `mail_unreachable` and `mail_unresolvable` (retryable, nothing reached the server). **A send is never reported as retryable** once the conversation could have reached delivery, because a duplicate e-mail cannot be recalled.
 - **The `ctx.fetch` response** carries `status`, `headers`, `body`, `bodyEncoding` and a `res.json()` helper. `res.json()` on a base64 response throws `not_json` rather than parsing bytes as text.
 - `ctx.files.list()` returns at most **100** entries and does not page. `ctx.crypto.hmacSha256` accepts `{base64:'...'}` for either `key` or `data`, not only strings.
 - `.insert(doc)` honours an **`id` inside the document object** - the idiom for an idempotent write.

+ 870 - 10
runner/src/host_context.cpp

@@ -10,6 +10,11 @@
 #include "filters.hpp"
 #include "functions/embed_budget.hpp"
 #include "functions/timezone.hpp"
+#include "net/imap_commands.hpp"
+#include "net/imap_fetch.hpp"
+#include "net/mail_budget.hpp"
+#include "net/mail_session.hpp"
+#include "net/mime_build.hpp"
 #include "outbound_http.hpp"
 #include "principal.hpp"
 #include "project_settings.hpp"
@@ -48,6 +53,7 @@
 #include <functional>
 #include <limits>
 #include <map>
+#include <mutex>
 #include <optional>
 #include <unordered_map>
 #include <utility>
@@ -554,21 +560,26 @@ int64_t embedTimeoutFrom(const nlohmann::json& payload) {
 /// here and classified with blockReasonForAddresses(), which net_guard.hpp
 /// documents as ssrfBlockReason's own classification half. One classifier, one
 /// lookup, and the address the connection pins was the address that was checked.
-EgressDecision decideEgress(const functions::HttpUrlParts& parts,
-                            const functions::SsrfPolicy& policy, const Resolver& resolve) {
+///
+/// Takes the HOST and not a parsed URL, because the host is all it has ever
+/// looked at and a mail account has no URL to parse: fabricating one so this
+/// could keep its old signature would mean inventing a scheme and a path for a
+/// decision that reads neither.
+EgressDecision decideEgress(const std::string& host, const functions::SsrfPolicy& policy,
+                            const Resolver& resolve) {
     EgressDecision d;
-    if (isAddressLiteral(parts.host)) {
-        if (auto why = functions::ssrfBlockReason(parts.host, policy)) {
+    if (isAddressLiteral(host)) {
+        if (auto why = functions::ssrfBlockReason(host, policy)) {
             d.reason = *why;
             return d;
         }
         d.allowed = true;
-        d.pinnedAddress = parts.host;
+        d.pinnedAddress = host;
         return d;
     }
 
-    const std::vector<std::string> addresses = resolve(parts.host);
-    if (auto why = functions::blockReasonForAddresses(parts.host, addresses, policy)) {
+    const std::vector<std::string> addresses = resolve(host);
+    if (auto why = functions::blockReasonForAddresses(host, addresses, policy)) {
         d.reason = *why;
         return d;
     }
@@ -579,6 +590,527 @@ EgressDecision decideEgress(const functions::HttpUrlParts& parts,
     return d;
 }
 
+// --- ctx.mail --------------------------------------------------------------
+//
+// The division of labour runner/CMakeLists.txt states is kept strictly: the
+// command TEXT comes from imap_commands.hpp (the injection boundary), the
+// response interpretation from imap_fetch.hpp, the outgoing bytes from
+// mime_build.hpp and the timeouts from mail_budget.hpp. What is left on this
+// side is turning a JS options bag into those calls and shaping their answers
+// for a JSON boundary - no curl, no IMAP grammar, no timeout arithmetic.
+
+/// The most one ctx.mail call may pull off the wire, in bytes.
+///
+/// The same question kCtxFileMaxBytes answers, asked about mail: not what a
+/// mailbox may hold, but what ONE run may load into a 64 MiB JS heap. A read of
+/// twenty messages' headers and text is tens of kilobytes, so this leaves room
+/// for a large message or two while still refusing the mailbox whose single
+/// message is a 30 MiB video. Higher than the file cap because a read is many
+/// messages where a file is one, and the base64 inflation of a third applies to
+/// both.
+///
+/// It is enforced TWICE, because the transport's cap and the run's exposure are
+/// not the same number. `MailTransferOptions::maxBytes` is checked against one
+/// transfer's buffer, which is reset per command, so on its own it would bound
+/// one message and let a 200-message read accumulate two hundred times as much
+/// in the array it is building. The read therefore also totals what it has
+/// kept and refuses past the same number. Refused rather than truncated: half a
+/// mailbox silently presented as all of it is the wrong answer, and a caller
+/// told the cap can lower `limit` or narrow the criteria.
+constexpr int64_t kCtxMailMaxBytes = 4 * 1024 * 1024;
+
+/// How many messages a read returns when it does not say, and the most it may
+/// ever ask for. The cap is the point: a mailbox has no bound of its own, and a
+/// function that asks for everything would spend the whole run's budget finding
+/// out how much everything is.
+constexpr int64_t kCtxMailDefaultLimit = 20;
+constexpr int64_t kCtxMailMaxLimit = 200;
+
+/// One built command as the bytes CURLOPT_CUSTOMREQUEST wants.
+///
+/// The builders emit `tag VERB args CRLF`, which is what a client writing to a
+/// socket must send; curl writes the tag and the terminator itself, so sending
+/// ours would put two tags on one line. The tag is therefore stripped HERE
+/// rather than by asking imap_commands for an untagged form: that header is the
+/// injection boundary and every command has to go through it, so it keeps
+/// producing real protocol and the transport adapts to it.
+///
+/// A command needing a continuation is REFUSED rather than flattened. Its
+/// octets may only follow the server's `+`, which a one-shot custom request
+/// cannot wait for; writing them anyway works against a permissive server and
+/// deadlocks against a strict one, which is the kind of bug that only appears
+/// in production.
+std::string customRequestFor(const net::ImapCommand& c) {
+    if (c.needsContinuation())
+        throw ApiError(ErrCode::Unprocessable, "mail_bad_argument",
+                       "that argument has to be sent as an IMAP literal, which this one-shot "
+                       "mail path cannot send; use a shorter 7-bit value");
+    std::string line = c.chunks.empty() ? std::string() : c.chunks.front();
+    if (line.size() >= 2 && line.compare(line.size() - 2, 2, "\r\n") == 0)
+        line.resize(line.size() - 2);
+    const std::string prefix = c.tag + " ";
+    if (line.compare(0, prefix.size(), prefix) == 0) line.erase(0, prefix.size());
+    return line;
+}
+
+/// Is this host a loopback ADDRESS LITERAL?
+///
+/// Only a literal, deliberately: a name that resolves to 127.0.0.1 is the
+/// rebinding case, and the answer here decides whether a session may run in the
+/// clear. Reuses the guard's own CIDR arithmetic so there is one implementation
+/// of what loopback means.
+bool isLoopbackLiteral(const std::string& host) {
+    static const std::optional<functions::CidrRange> v4 = functions::parseCidr("127.0.0.0/8");
+    static const std::optional<functions::CidrRange> v6 = functions::parseCidr("::1/128");
+    return (v4 && functions::cidrContains(*v4, host)) ||
+           (v6 && functions::cidrContains(*v6, host));
+}
+
+/// How many messages this read may name. Validated rather than coerced, for the
+/// reason embedTimeoutMs records: an option accepted and ignored leaves the
+/// author believing a bound is in force. Above the cap is refused rather than
+/// silently clamped, because a script asking for 5000 is reasoning about a
+/// result set it is not going to get.
+int64_t mailReadLimit(const nlohmann::json& payload) {
+    if (!payload.is_object()) return kCtxMailDefaultLimit;
+    const auto it = payload.find("limit");
+    if (it == payload.end() || it->is_null()) return kCtxMailDefaultLimit;
+    if (!it->is_number_integer() || it->get<int64_t>() <= 0)
+        throw ApiError(ErrCode::Unprocessable, "validation",
+                       "limit must be a positive integer number of messages");
+    const int64_t want = it->get<int64_t>();
+    if (want > kCtxMailMaxLimit)
+        throw ApiError(ErrCode::Unprocessable, "validation",
+                       "limit is capped at " + std::to_string(kCtxMailMaxLimit) +
+                           " messages per read; page with a narrower criteria instead");
+    return want;
+}
+
+/// The `timeoutMs` this call asked for, or 0 for "unstated". Narrowing only -
+/// resolveMailBudget cannot raise the run's remaining budget - and validated
+/// for the same reason the limit is.
+int64_t mailTimeoutFrom(const nlohmann::json& payload) {
+    if (!payload.is_object()) return 0;
+    const auto it = payload.find("timeoutMs");
+    if (it == payload.end() || it->is_null()) return 0;
+    if (!it->is_number_integer() || it->get<int64_t>() <= 0)
+        throw ApiError(ErrCode::Unprocessable, "validation",
+                       "timeoutMs must be a positive integer number of milliseconds");
+    return it->get<int64_t>();
+}
+
+/// A credential for a mail account: a stored secret by NAME, or a literal.
+///
+/// `<x>Secret` is the preferred shape and the reason is worth stating: the value
+/// never enters the script's own variables, so an author who logs the options
+/// bag - or whose error handler echoes it - cannot leak it, and an operator can
+/// rotate it without a code push. A literal is still accepted, because ctx.env
+/// already hands the script every secret it is entitled to; refusing the literal
+/// would buy nothing, it would only move the same value one line earlier.
+///
+/// A named secret that does not exist is an ERROR. Falling back to an empty
+/// password would reach the server as an auth failure, and the author would then
+/// go looking at the mail account rather than at the typo in the name. The error
+/// names the SECRET, never a value.
+std::string mailCredential(const nlohmann::json& payload, const nlohmann::json& env,
+                           const char* literalKey, const char* secretKey) {
+    const bool hasLiteral = payload.is_object() && payload.contains(literalKey) &&
+                            payload.at(literalKey).is_string();
+    const bool hasSecret = payload.is_object() && payload.contains(secretKey) &&
+                           payload.at(secretKey).is_string();
+    if (hasLiteral && hasSecret)
+        throw ApiError(ErrCode::Unprocessable, "ambiguous_body",
+                       std::string("ctx.mail takes ") + literalKey + " or " + secretKey +
+                           ", not both");
+    if (hasSecret) {
+        const std::string name = payload.at(secretKey).get<std::string>();
+        if (!env.is_object() || !env.contains(name) || !env.at(name).is_string())
+            throw ApiError(ErrCode::Unprocessable, "mail_secret_missing",
+                           "no secret named '" + name + "' is available to this function; set it "
+                           "on the project or in the runner environment");
+        return env.at(name).get<std::string>();
+    }
+    if (hasLiteral) return payload.at(literalKey).get<std::string>();
+    return std::string();
+}
+
+/// A read's search criteria. "ALL" and absence are the same request: an empty
+/// criteria set is what imapUidSearch renders as `UID SEARCH ALL`, so the common
+/// case needs no special case here.
+net::ImapSearchCriteria mailCriteriaFrom(const nlohmann::json& v) {
+    net::ImapSearchCriteria c;
+    if (v.is_null()) return c;
+    if (v.is_string()) {
+        if (v.get<std::string>() == "ALL") return c;
+        throw ApiError(ErrCode::Unprocessable, "validation",
+                       "criteria as a string may only be 'ALL'; pass an object for anything "
+                       "narrower");
+    }
+    if (!v.is_object())
+        throw ApiError(ErrCode::Unprocessable, "validation",
+                       "criteria must be an object or the string 'ALL'");
+
+    auto text = [&v](const char* key) -> std::optional<std::string> {
+        const auto it = v.find(key);
+        if (it == v.end() || it->is_null()) return std::nullopt;
+        if (!it->is_string())
+            throw ApiError(ErrCode::Unprocessable, "validation",
+                           std::string("criteria.") + key + " must be a string");
+        return it->get<std::string>();
+    };
+    auto flag = [&v](const char* key) {
+        const auto it = v.find(key);
+        if (it == v.end() || it->is_null()) return false;
+        if (!it->is_boolean())
+            throw ApiError(ErrCode::Unprocessable, "validation",
+                           std::string("criteria.") + key + " must be a boolean");
+        return it->get<bool>();
+    };
+    auto size = [&v](const char* key) -> std::optional<uint64_t> {
+        const auto it = v.find(key);
+        if (it == v.end() || it->is_null()) return std::nullopt;
+        if (!it->is_number_integer() || it->get<int64_t>() < 0)
+            throw ApiError(ErrCode::Unprocessable, "validation",
+                           std::string("criteria.") + key +
+                               " must be a non-negative integer number of bytes");
+        return static_cast<uint64_t>(it->get<int64_t>());
+    };
+
+    c.since = text("since");
+    c.before = text("before");
+    c.from = text("from");
+    c.to = text("to");
+    c.subject = text("subject");
+    c.text = text("text");
+    c.body = text("body");
+    c.headerName = text("headerName");
+    c.headerValue = text("headerValue");
+    c.unseen = flag("unseen");
+    c.seen = flag("seen");
+    c.flagged = flag("flagged");
+    c.largerThanBytes = size("largerThanBytes");
+    c.smallerThanBytes = size("smallerThanBytes");
+    // Every remaining rule - the date shape, the ASCII-only search terms, the
+    // paired HEADER halves - belongs to imapUidSearch and is left there, so a
+    // criterion cannot be validated by two rules that drift apart.
+    return c;
+}
+
+/// One address field as a list. A single string is accepted because `to: 'a@b'`
+/// is what a script writes and an array of one is not an improvement.
+std::vector<std::string> mailAddressList(const nlohmann::json& v, const char* what) {
+    std::vector<std::string> out;
+    if (v.is_null()) return out;
+    if (v.is_string()) {
+        out.push_back(v.get<std::string>());
+        return out;
+    }
+    if (!v.is_array())
+        throw ApiError(ErrCode::Unprocessable, "validation",
+                       std::string(what) + " must be a string or an array of strings");
+    for (const nlohmann::json& e : v) {
+        if (!e.is_string())
+            throw ApiError(ErrCode::Unprocessable, "validation",
+                           std::string(what) + " must contain only address strings");
+        out.push_back(e.get<std::string>());
+    }
+    return out;
+}
+
+/// The outgoing message, as mime_build.hpp wants it.
+///
+/// Mapping only. Every rule about what a header may contain - the CR and LF
+/// refusals, the structural headers that may not be supplied, the encoded-word
+/// decisions - is buildMail's, because that is the injection boundary for a
+/// send and a second opinion here could only disagree with it.
+net::MailMessage mailMessageFrom(const nlohmann::json& payload) {
+    net::MailMessage m;
+    const auto str = [&payload](const char* key) -> std::string {
+        const auto it = payload.find(key);
+        if (it == payload.end() || it->is_null()) return std::string();
+        if (!it->is_string())
+            throw ApiError(ErrCode::Unprocessable, "validation",
+                           std::string(key) + " must be a string");
+        return it->get<std::string>();
+    };
+    const auto list = [&payload](const char* key) {
+        const auto it = payload.find(key);
+        return mailAddressList(it == payload.end() ? nlohmann::json() : *it, key);
+    };
+
+    m.from = str("from");
+    if (m.from.empty())
+        throw ApiError(ErrCode::Unprocessable, "validation", "a send needs a from address");
+    m.to = list("to");
+    m.cc = list("cc");
+    m.bcc = list("bcc");
+    if (m.to.empty() && m.cc.empty() && m.bcc.empty())
+        throw ApiError(ErrCode::Unprocessable, "validation", "a send needs at least one recipient");
+    m.replyTo = str("replyTo");
+    m.subject = str("subject");
+    m.text = str("text");
+    m.html = str("html");
+    m.inReplyTo = str("inReplyTo");
+    m.references = str("references");
+
+    const auto attachments = payload.find("attachments");
+    if (attachments != payload.end() && !attachments->is_null()) {
+        if (!attachments->is_array())
+            throw ApiError(ErrCode::Unprocessable, "validation", "attachments must be an array");
+        for (const nlohmann::json& a : *attachments) {
+            if (!a.is_object())
+                throw ApiError(ErrCode::Unprocessable, "validation",
+                               "each attachment must be an object");
+            net::MailAttachment out;
+            if (!a.contains("filename") || !a.at("filename").is_string())
+                throw ApiError(ErrCode::Unprocessable, "validation",
+                               "each attachment needs a filename");
+            out.filename = a.at("filename").get<std::string>();
+            // An empty content type is left empty on purpose: buildMail turns
+            // it into application/octet-stream, which is what unknown MEANS and
+            // is safer than guessing from the extension.
+            if (a.contains("contentType") && a.at("contentType").is_string())
+                out.contentType = a.at("contentType").get<std::string>();
+            // The same `{text}`/`{base64}` reader the crypto surface uses, so a
+            // payload cannot be decoded by two different rules.
+            out.content = bytesArgument(a, "an attachment's content");
+            m.attachments.push_back(std::move(out));
+        }
+    }
+
+    const auto headers = payload.find("headers");
+    if (headers != payload.end() && !headers->is_null()) {
+        if (!headers->is_object())
+            throw ApiError(ErrCode::Unprocessable, "validation",
+                           "headers must be an object of name -> value");
+        // nlohmann keeps an object's keys sorted, so the rendered bytes are the
+        // same for the same message - which is what makes a send assertable.
+        for (auto it = headers->begin(); it != headers->end(); ++it) {
+            if (!it.value().is_string())
+                throw ApiError(ErrCode::Unprocessable, "validation",
+                               "header '" + it.key() + "' must have a string value");
+            m.headers.push_back(net::MailHeader{it.key(), it.value().get<std::string>()});
+        }
+    }
+    return m;
+}
+
+/// The last `limit` uids of a search result.
+///
+/// UID SEARCH answers in ascending order and a mailbox's newest message carries
+/// its highest uid, so the TAIL is the recent mail - which is what a read of 20
+/// out of a thousand is asking for. Taking the head would answer with the
+/// oldest, which is almost never the question and is a silently wrong answer
+/// rather than an error. Sorted here rather than trusted, because the ordering
+/// is the server's and "newest" has to be well defined either way.
+std::vector<uint64_t> newestUids(const std::vector<uint64_t>& uids, int64_t limit) {
+    if (limit <= 0) return {};
+    std::vector<uint64_t> out = uids;
+    std::sort(out.begin(), out.end());
+    out.erase(std::unique(out.begin(), out.end()), out.end());
+    if (static_cast<int64_t>(out.size()) > limit) out.erase(out.begin(), out.end() - limit);
+    return out;
+}
+
+/// Put a fetched string on `out` as something JSON can actually carry.
+///
+/// Mail is routinely not UTF-8 - a Hungarian message in ISO-8859-2 is ordinary
+/// rather than exotic - and nlohmann's dump() answers an invalid sequence by
+/// throwing, which would reach the author as an internal error naming neither
+/// the message nor the fix. So a part that is valid UTF-8 travels as text and
+/// anything else travels as base64, with `<key>Encoding` STATING which, exactly
+/// as ctx.fetch reports a response body it could not carry as text.
+void putMailText(nlohmann::json& out, const char* key, const std::string& bytes) {
+    const std::string encodingKey = std::string(key) + "Encoding";
+    if (isValidUtf8(bytes)) {
+        out[key] = bytes;
+        out[encodingKey] = "text";
+    } else {
+        out[key] = base64Encode(bytes);
+        out[encodingKey] = "base64";
+    }
+}
+
+/// A LIST name as a script should see it.
+///
+/// imap_fetch returns the name exactly as it arrived - still modified UTF-7 on a
+/// server that is not running UTF8=ACCEPT - and documents that decoding it is
+/// the caller's job. This is that caller. A name that will not decode is handed
+/// back RAW rather than dropped: the mailbox exists either way, and a server
+/// sending something that is not modified UTF-7 is almost certainly sending
+/// UTF-8 already, so the raw bytes are both the honest answer and the only ones
+/// that can be fed back to a read.
+std::string decodeMailboxName(const std::string& raw) {
+    try {
+        return net::fromModifiedUtf7(raw);
+    } catch (const net::ImapCommandError&) {
+        return raw;
+    }
+}
+
+/// Our own sentence for a transport failure, by slug.
+///
+/// The transport's message carries curl's error buffer and the server's reply
+/// text verbatim, and neither may reach a script: the first can name the
+/// connection and the account it was made with, the second is text a remote
+/// server chose. The SLUG does reach the script, because the slugs are what
+/// distinguish the remedies, and the verbatim detail goes to the operator's
+/// journal instead - the same split the embedding path makes.
+std::string mailSlugMessage(const std::string& slug) {
+    if (slug == "mail_too_large")
+        return "the mail response was larger than one function run may load";
+    if (slug == "mail_timeout" || slug == "mail_aborted")
+        return "the mail operation ran out of the time this run could allow it";
+    if (slug == "mail_auth_failed")
+        return "the mail server rejected the credentials";
+    if (slug == "mail_access_denied")
+        return "the mail server denied access to that mailbox";
+    if (slug == "mail_rejected")
+        return "the mail server refused the message permanently; check the sender, the "
+               "recipients and the size";
+    if (slug == "mail_server_busy")
+        return "the mail server refused the command temporarily; retry later";
+    if (slug == "mail_unresolvable")
+        return "the mail host could not be resolved";
+    if (slug == "mail_unreachable")
+        return "the mail host could not be connected to";
+    if (slug == "mail_tls_untrusted")
+        return "the mail server's certificate did not verify";
+    if (slug == "mail_tls_failed")
+        return "the TLS handshake with the mail server failed";
+    if (slug == "mail_connection_lost")
+        return "the connection to the mail server was lost mid-conversation";
+    if (slug == "mail_protocol_error")
+        return "the mail server sent a reply that could not be parsed";
+    if (slug == "mail_incomplete")
+        return "the mail server stopped mid-response; the message was not received in full";
+    if (slug == "mail_no_sender")
+        return "a send needs an envelope sender";
+    if (slug == "mail_no_recipient")
+        return "a send needs at least one recipient";
+    if (slug == "mail_bad_url")
+        return "the mail host or port is not usable";
+    return "the mail operation failed";
+}
+
+/// A FETCH response as curl's IMAP download actually delivers it.
+///
+/// MEASURED, against real curl 8.22 and an in-process server, because every
+/// line of this is a fact about the transport rather than about IMAP:
+///
+///   * A successful single-uid fetch arrives as the untagged line plus the
+///     literal's octets and NOTHING MORE - `* 1 FETCH (UID 7 BODY[] {50}\r\n`
+///     followed by exactly 50 octets. curl keeps the closing `)` and the tagged
+///     completion to itself. The parser is octet-counted and right to call that
+///     buffer incomplete: it answers NeedMore.
+///   * A uid the server did not return arrives as ZERO bytes. Fetching nothing
+///     is not an error in IMAP - the server answers with the tagged completion
+///     alone - and curl passes none of it on.
+///
+/// So: an empty buffer is Ok with no messages, which the caller SKIPS. A buffer
+/// that does not parse has its closing framing restored and is parsed again,
+/// and that second parse is what decides. Restoring the framing cannot rescue a
+/// short literal, which is the whole reason it is safe: the announced `{n}` is
+/// still unsatisfied, so a server that stopped mid-literal still answers
+/// NeedMore and is still a failure. Measured both ways.
+///
+/// What this must NEVER become is a search for a terminator such as `")\r\n"`
+/// in the buffer. The reader anchors on the byte count, which is what lets a
+/// body whose CONTENT contains `")\r\n"` and a line that looks like a tagged
+/// reply come through intact; a terminator search would truncate exactly those
+/// bodies, and real mail contains them.
+net::ImapFetchResult parseCurlFetch(const std::string& response) {
+    if (response.empty()) {
+        net::ImapFetchResult empty;
+        empty.status = net::ImapParse::Ok;
+        return empty;
+    }
+    net::ImapFetchResult direct = net::parseFetchResponse(response);
+    if (direct.status == net::ImapParse::Ok) return direct;
+    return net::parseFetchResponse(response + ")\r\n");
+}
+
+/// The record for `uid`, or nullptr.
+///
+/// Matched by uid rather than taken positionally, because "the server did not
+/// return this uid" is an ordinary outcome of a mailbox that changed under us.
+/// The one fallback: a single record carrying no UID item at all is attributed
+/// to the uid this command asked for, which is sound only because each command
+/// names exactly one.
+const net::ImapFetchRecord* recordForUid(const net::ImapFetchResult& result, uint64_t uid) {
+    if (const net::ImapFetchRecord* exact = net::findByUid(result.messages, uid)) return exact;
+    if (result.messages.size() == 1 && !result.messages.front().hasUid)
+        return &result.messages.front();
+    return nullptr;
+}
+
+/// The one body part a fetch asked for.
+///
+/// Keyed by section when the server labels it the way we asked, and otherwise
+/// by being the only part present. The fallback is not laziness: each command
+/// requests exactly ONE part, so whatever single part came back IS the answer,
+/// and a server that answers `BODY[]` to a `BODY.PEEK[HEADER]` request would
+/// otherwise read as an empty message.
+std::string soleBodyPart(const net::ImapFetchRecord* record, const char* section) {
+    if (record == nullptr) return std::string();
+    const auto exact = record->bodyParts.find(section);
+    if (exact != record->bodyParts.end()) return exact->second;
+    if (record->bodyParts.size() == 1) return record->bodyParts.begin()->second;
+    return std::string();
+}
+
+/// A response that did not parse completely, as the failure it is.
+///
+/// `NeedMore` is the one that bites. It means THE RESPONSE IS INCOMPLETE, and
+/// by the time we parse, the transport has already finished the transfer - so
+/// NeedMore at this point means the server stopped mid-literal. A sibling
+/// implementation took whatever had arrived, trimmed the trailing `)` and CRLF
+/// off it and reported success, so an interrupted transfer came back as a short
+/// but perfectly valid-looking e-mail. It is therefore a failure, and a
+/// RETRYABLE one: a peek fetch changes no flag, so nothing in the mailbox was
+/// touched and repeating it is safe.
+///
+/// The fix is never to hunt for a terminator such as `")\r\n"`. The reader is
+/// octet-counted and anchors on the announced `{n}`, which is what lets a body
+/// whose CONTENT contains `")\r\n"` and a line that looks like a tagged reply
+/// come through byte-intact. A terminator search would truncate exactly those
+/// bodies, and real mail contains them.
+net::MailFailure mailParseFailure(net::ImapParse status, const char* what) {
+    if (status == net::ImapParse::NeedMore)
+        return net::MailFailure{504, "mail_incomplete",
+                                std::string("the mail server's ") + what +
+                                    " response ended mid-literal",
+                                true};
+    return net::MailFailure{502, "mail_protocol_error",
+                            std::string("the mail server's ") + what +
+                                " response could not be read",
+                            false};
+}
+
+/// A transport failure as the error a script catches.
+///
+/// `retryable` is carried in `details` rather than folded into the status,
+/// because the transport's three-way answer is the useful one: a read that timed
+/// out may be repeated, a send past the point of delivery may NOT, and a script
+/// deciding that from a status code alone would get it wrong in the direction
+/// that sends an e-mail twice.
+ApiError apiErrorForMail(const net::MailFailure& f) {
+    ErrCode code = ErrCode::Unavailable;
+    switch (f.status) {
+        case 413:
+        case 422: code = ErrCode::Unprocessable; break;
+        case 504: code = ErrCode::GatewayTimeout; break;
+        case 503: code = ErrCode::Unavailable; break;
+        case 500: code = ErrCode::Internal; break;
+        // 502 and anything unmapped. Never a guessed 422: telling a caller its
+        // payload was wrong when the server was unreachable sends it to fix
+        // something that is already correct.
+        default: code = ErrCode::Unavailable; break;
+    }
+    return ApiError(code, f.slug.empty() ? "mail_error" : f.slug, mailSlugMessage(f.slug),
+                    nlohmann::json{{"retryable", f.retryable}});
+}
+
 // --- ctx.crypto ------------------------------------------------------------
 
 std::string toHex(std::string_view bytes) {
@@ -1446,7 +1978,7 @@ struct HostContext::Impl {
         }
 
         auto decision =
-            hostdetail::decideEgress(*parts, ssrfPolicy(), hostdetail::resolveWithGetaddrinfo);
+            hostdetail::decideEgress(parts->host, ssrfPolicy(), hostdetail::resolveWithGetaddrinfo);
         if (!decision.allowed) {
             blocked.push_back(decision.reason);
             throw ApiError(ErrCode::Forbidden, "egress_blocked", decision.reason);
@@ -1788,6 +2320,332 @@ struct HostContext::Impl {
         return out;
     }
 
+    // --- mail ---------------------------------------------------------------
+
+    /// Report a transport failure, leaving its verbatim detail behind.
+    ///
+    /// An operator trace, which the ctx.fetch and embedding paths both had to
+    /// learn to leave: a failing provider visible ONLY inside a tenant's
+    /// function means the journal says nothing at all, which is the wrong way
+    /// round. The transport's own message belongs here and nowhere else, because
+    /// it carries curl's error buffer and the server's reply text verbatim.
+    [[noreturn]] void failMail(const char* what, const net::MailFailure& f) {
+        spdlog::warn("ctx.mail {} failed (project {}, function {}): {} status {} retryable {} - {}",
+                     what, config.project, config.functionId, f.slug, f.status, f.retryable,
+                     f.message);
+        throw hostdetail::apiErrorForMail(f);
+    }
+
+    /// The account and the per-call bounds for one mail session.
+    ///
+    /// Everything that decides WHETHER the session may happen is here, before a
+    /// socket exists: the TLS posture, the egress classification and the budget.
+    /// The three operations below differ only in what they then say on the wire.
+    struct MailSetup {
+        net::MailAccount account;
+        net::MailTransferOptions options;
+    };
+
+    MailSetup mailSetup(const nlohmann::json& payload) {
+        // curl_global_init is not thread-safe, and curl's lazy first-use
+        // initialisation from two pool threads at once is a real race rather
+        // than a theoretical one. Done once per process, and it also carries the
+        // transport's refusal to run on a libcurl that was not built
+        // thread-safe: fail closed, before any credential is sent.
+        static std::once_flag once;
+        static std::string initError;
+        std::call_once(once, [] { initError = net::mailGlobalInit(); });
+        if (!initError.empty())
+            throw ApiError(ErrCode::Unavailable, "mail_unavailable", initError);
+
+        MailSetup s;
+        s.account.host = payload.value("host", std::string());
+        if (s.account.host.empty())
+            throw ApiError(ErrCode::Unprocessable, "validation", "ctx.mail needs a host");
+
+        if (payload.contains("port") && !payload.at("port").is_null()) {
+            const nlohmann::json& port = payload.at("port");
+            if (!port.is_number_integer() || port.get<int64_t>() <= 0 ||
+                port.get<int64_t>() > 65535)
+                throw ApiError(ErrCode::Unprocessable, "validation",
+                               "port must be an integer between 1 and 65535");
+            s.account.port = static_cast<uint16_t>(port.get<int64_t>());
+        }
+
+        s.account.tls = !payload.contains("tls") || !payload.at("tls").is_boolean()
+                            ? true
+                            : payload.at("tls").get<bool>();
+        s.account.startTls = payload.contains("startTls") &&
+                             payload.at("startTls").is_boolean() &&
+                             payload.at("startTls").get<bool>();
+        // Refused rather than resolved by precedence: implicit TLS and STARTTLS
+        // are different ports and different handshakes, so a request for both
+        // is a misunderstanding, and silently picking one would leave an author
+        // believing the other is in force.
+        if (s.account.tls && s.account.startTls)
+            throw ApiError(ErrCode::Unprocessable, "ambiguous_body",
+                           "ctx.mail takes tls or startTls, not both: implicit TLS is a different "
+                           "port and a different handshake from STARTTLS");
+        // Plaintext is what the transport says the host layer must refuse off
+        // loopback. The credentials go over this connection in the clear, so the
+        // only place it is defensible is a server on this machine.
+        if (!s.account.tls && !s.account.startTls &&
+            !hostdetail::isLoopbackLiteral(s.account.host))
+            throw ApiError(ErrCode::Forbidden, "mail_tls_required",
+                           "a mail session to '" + s.account.host +
+                               "' must use TLS or STARTTLS; an unencrypted session is permitted "
+                               "only to a loopback address");
+
+        // Resolved BEFORE the egress check, so a typo in a secret's name is
+        // reported as a typo rather than as whatever the host lookup happens to
+        // say. Both are the author's mistake, and the one they can act on is
+        // the one they wrote two lines earlier.
+        s.account.user = hostdetail::mailCredential(payload, config.env, "user", "userSecret");
+        s.account.password =
+            hostdetail::mailCredential(payload, config.env, "password", "passwordSecret");
+
+        // The SAME classifier ctx.fetch goes through: a literal is classified
+        // directly, a name is resolved EXACTLY ONCE and every address it returns
+        // is classified. The approved address is then pinned for the transport,
+        // because re-resolving IS the rebinding window.
+        auto decision = hostdetail::decideEgress(s.account.host, ssrfPolicy(),
+                                                 hostdetail::resolveWithGetaddrinfo);
+        if (!decision.allowed) {
+            blocked.push_back(decision.reason);
+            throw ApiError(ErrCode::Forbidden, "egress_blocked", decision.reason);
+        }
+        s.options.pinnedAddresses = {decision.pinnedAddress};
+
+        // Checked BEFORE connecting, so an exhausted budget costs no socket.
+        // Not an egress refusal: nothing about the destination was wrong.
+        const int64_t budget = hostdetail::outboundTimeoutMs(config.deadlineMs, elapsedMs(), 0);
+        if (budget <= 0)
+            throw ApiError(ErrCode::Unavailable, "deadline_exceeded",
+                           "the run's time budget is exhausted; not connecting to '" +
+                               s.account.host + "'");
+        net::MailBudgetRequest want;
+        want.remainingBudgetMs = budget;
+        // No operator-configured mail timeouts to narrow with - there is no
+        // settings field for them - so both phases are derived from the run's
+        // own remaining budget. Stated rather than left to be inferred from two
+        // zeroes. The per-call value is narrowing only, which is what lets
+        // resolveMailBudget report a timeout as the script's own choice.
+        want.callTimeoutMs = hostdetail::mailTimeoutFrom(payload);
+        s.options.budget = net::resolveMailBudget(want);
+        s.options.maxBytes = hostdetail::kCtxMailMaxBytes;
+
+        return s;
+    }
+
+    /// `__hostMail(op, payload)` - read a mailbox, list mailboxes, send a message.
+    ///
+    /// Three operations, deliberately few, each opening ONE session and closing
+    /// it. A read is ONE login for the whole thing (EXAMINE, UID SEARCH, UID
+    /// FETCH): a login per message is what gets a mail account throttled or
+    /// locked, which is why the session is held across the commands rather than
+    /// reopened per uid.
+    ///
+    /// No scope rule gates this, for the same reason none gates ctx.fetch: the
+    /// destination is outside the tenancy a policy describes, so the gates that
+    /// apply are the egress guard and the credential - and a named credential is
+    /// a project secret only an admin can store.
+    nlohmann::json mailCall(const std::string& op, const nlohmann::json& payload) {
+        if (!payload.is_object())
+            throw ApiError(ErrCode::BadRequest, "validation", "the request must be an object");
+        if (op != "read" && op != "mailboxes" && op != "send")
+            throw ApiError(ErrCode::Unprocessable, "validation",
+                           "ctx.mail does not support '" + op + "'");
+
+        const MailSetup s = mailSetup(payload);
+        try {
+            if (op == "send") return mailSend(s, payload);
+            if (op == "mailboxes") return mailMailboxes(s);
+            return mailRead(s, payload);
+        } catch (const net::ImapCommandError& e) {
+            // A script author's typo is data, and the builder's message names
+            // the field the author can change. Nothing it says comes from the
+            // server or from a credential.
+            throw ApiError(ErrCode::Unprocessable, "mail_bad_argument", e.what());
+        } catch (const net::MailBuildError& e) {
+            throw ApiError(ErrCode::Unprocessable, "mail_bad_message", e.what());
+        }
+    }
+
+    /// Every command carries its mailbox in the COMMAND and leaves the URL path
+    /// EMPTY, which is not a detail: a mailbox in the path is what makes curl
+    /// issue its own SELECT, and SELECT opens the mailbox read-WRITE. EXAMINE is
+    /// the read-only form, and with BODY.PEEK that pair is what makes a read
+    /// touch no flag at all.
+    std::string mailCommand(net::ImapSession& session, const char* what,
+                            const net::ImapCommand& command) {
+        std::string response;
+        const net::MailFailure f =
+            session.command(std::string(), hostdetail::customRequestFor(command), response);
+        if (!f.ok()) failMail(what, f);
+        return response;
+    }
+
+    nlohmann::json mailRead(const MailSetup& s, const nlohmann::json& payload) {
+        const std::string mailbox = payload.contains("mailbox") &&
+                                            payload.at("mailbox").is_string()
+                                        ? payload.at("mailbox").get<std::string>()
+                                        : std::string("INBOX");
+        const int64_t limit = hostdetail::mailReadLimit(payload);
+        const net::ImapSearchCriteria criteria = hostdetail::mailCriteriaFrom(
+            payload.contains("criteria") ? payload.at("criteria") : nlohmann::json());
+
+        net::ImapSession session;
+        const net::MailFailure opened = session.open(s.account, s.options);
+        if (!opened.ok()) failMail("open", opened);
+
+        // One tagger for the session: a tag reused inside a session makes two
+        // commands indistinguishable, and the failure mode is a wrong answer
+        // attributed to the wrong command rather than an error.
+        net::ImapTagger tagger;
+        mailCommand(session, "examine", net::imapExamine(tagger.next(), mailbox));
+
+        const std::string searched =
+            mailCommand(session, "search", net::imapUidSearch(tagger.next(), criteria));
+        const net::ImapSearchResult found = net::parseSearchResponse(searched);
+        if (found.status != net::ImapParse::Ok)
+            failMail("search", hostdetail::mailParseFailure(found.status, "search"));
+
+        const std::vector<uint64_t> uids = hostdetail::newestUids(found.uids, limit);
+        nlohmann::json messages = nlohmann::json::array();
+        if (uids.empty())
+            return nlohmann::json{{"messages", messages},
+                                  {"matched", static_cast<int64_t>(found.uids.size())}};
+
+        // TWO commands per uid, and both halves of that are MEASURED rather
+        // than chosen.
+        //
+        // Per UID, because curl's IMAP download hands the write callback ZERO
+        // bytes for a UID FETCH naming more than one uid - `7,9` and `7:9` both
+        // produce nothing at all, where `7` produces the untagged line and the
+        // literal. The rule that matters is ONE LOGIN for the whole read, not
+        // one command, and the session holds its connection across every
+        // command here. Note the consequence: a read near the 200-message cap
+        // is 400 round trips, and what actually limits it is the run's wall
+        // budget rather than the cap.
+        //
+        // Two parts, because a body-part specifier names a single part while a
+        // message's headers and its text are two, and a surface that returned
+        // only one of them answers no useful question about a mailbox. Both are
+        // BODY.PEEK, which is the only form the builder emits - the unpeeked
+        // form sets \Seen as a side effect of reading.
+        int64_t keptBytes = 0;
+        for (const uint64_t uid : uids) {
+            const std::string headerBytes = mailCommand(
+                session, "fetch", net::imapUidFetch(tagger.next(), {uid}, "HEADER"));
+            const net::ImapFetchResult headers = hostdetail::parseCurlFetch(headerBytes);
+            // NOT just Malformed. NeedMore means the response is INCOMPLETE,
+            // and by now the transport has finished the transfer - so it means
+            // the server stopped mid-literal, and the partial bytes must never
+            // become a message body. See parseCurlFetch() for why restoring the
+            // framing cannot hide this.
+            if (headers.status != net::ImapParse::Ok)
+                failMail("fetch", hostdetail::mailParseFailure(headers.status, "header fetch"));
+
+            const std::string textBytes =
+                mailCommand(session, "fetch", net::imapUidFetch(tagger.next(), {uid}, "TEXT"));
+            const net::ImapFetchResult bodies = hostdetail::parseCurlFetch(textBytes);
+            if (bodies.status != net::ImapParse::Ok)
+                failMail("fetch", hostdetail::mailParseFailure(bodies.status, "body fetch"));
+
+            const net::ImapFetchRecord* h = hostdetail::recordForUid(headers, uid);
+            const net::ImapFetchRecord* b = hostdetail::recordForUid(bodies, uid);
+            // A uid the server did not return is an ordinary outcome of a
+            // mailbox that changed between the SEARCH and the FETCH: it is
+            // SKIPPED, never reported as a blank message.
+            //
+            // The trap is above the parser rather than in it. An implementation
+            // that saw a status of Ok and read the response buffer anyway
+            // handed the PROTOCOL LINE back as the e-mail, and the result was a
+            // successful fetch whose body was "A003 OK Fetch completed" and
+            // whose sender was empty. Every byte a message carries here comes
+            // from the parser's bodyParts and never from the buffer.
+            if (h == nullptr && b == nullptr) continue;
+
+            const std::string header = hostdetail::soleBodyPart(h, "HEADER");
+            const std::string text = hostdetail::soleBodyPart(b, "TEXT");
+            // The aggregate half of the cap. The transport bounded each command
+            // on its own; this bounds the array the run is building out of them.
+            keptBytes += static_cast<int64_t>(header.size() + text.size());
+            if (keptBytes > hostdetail::kCtxMailMaxBytes)
+                throw ApiError(ErrCode::Unprocessable, "mail_too_large",
+                               "this read passed the " +
+                                   std::to_string(hostdetail::kCtxMailMaxBytes) +
+                                   " bytes a single function run may load; lower the limit or "
+                                   "narrow the criteria");
+
+            nlohmann::json m = net::toJson(h != nullptr ? *h : *b);
+            if (!m.contains("uid")) m["uid"] = uid;
+            // toJson is a projection that deliberately omits part BYTES, so the
+            // two parts are added here - the one place that owns both the size
+            // cap and the encoding decision.
+            hostdetail::putMailText(m, "header", header);
+            hostdetail::putMailText(m, "text", text);
+            messages.push_back(std::move(m));
+        }
+        // `matched` is the whole search result and `messages` only the newest
+        // `limit` of it, so a script can tell "that is all of it" from "there is
+        // more behind this" instead of inferring it from a full page.
+        return nlohmann::json{{"messages", std::move(messages)},
+                              {"matched", static_cast<int64_t>(found.uids.size())}};
+    }
+
+    nlohmann::json mailMailboxes(const MailSetup& s) {
+        net::ImapSession session;
+        const net::MailFailure opened = session.open(s.account, s.options);
+        if (!opened.ok()) failMail("open", opened);
+
+        net::ImapTagger tagger;
+        // An empty reference and `*` for the pattern: everything the account can
+        // see. Both go through the builder, which is why the pattern is quoted -
+        // `*` is an atom-special.
+        const std::string listed =
+            mailCommand(session, "list", net::imapList(tagger.next(), std::string(), "*"));
+        const net::ImapListResult result = net::parseListResponse(listed);
+        if (result.status != net::ImapParse::Ok)
+            failMail("list", hostdetail::mailParseFailure(result.status, "mailbox list"));
+
+        nlohmann::json out = nlohmann::json::array();
+        for (const net::ImapMailbox& m : result.mailboxes) {
+            nlohmann::json entry = nlohmann::json::object();
+            hostdetail::putMailText(entry, "name", hostdetail::decodeMailboxName(m.nameRaw));
+            entry["flags"] = m.flags;
+            // Empty means "no delimiter" - a flat namespace - never "unknown",
+            // which is what the parser's contract says and what a script
+            // building a path has to be able to rely on.
+            entry["delimiter"] = m.delimiter;
+            out.push_back(std::move(entry));
+        }
+        return out;
+    }
+
+    nlohmann::json mailSend(const MailSetup& s, const nlohmann::json& payload) {
+        const net::MailMessage msg = hostdetail::mailMessageFrom(payload);
+        // The seed is the only variation in the rendered bytes, and it has to be
+        // unpredictable per message: a guessable MIME boundary lets anyone who
+        // can influence any part of a body close the multipart early and append
+        // parts of their own.
+        uint64_t seed = 0;
+        if (RAND_bytes(reinterpret_cast<unsigned char*>(&seed), sizeof(seed)) != 1)
+            throw ApiError(ErrCode::Internal, "crypto_unavailable",
+                           "no entropy was available for a MIME boundary");
+        const net::BuiltMail built = net::buildMail(msg, seed);
+
+        net::MailEnvelope envelope;
+        envelope.sender = built.envelopeFrom;
+        envelope.recipients = built.envelopeRecipients;
+        const net::MailFailure f = net::smtpSend(s.account, s.options, envelope, built.data);
+        if (!f.ok()) failMail("send", f);
+        // The ENVELOPE recipients, which is what was actually offered to the
+        // server - not the To header, which a sender may make say anything and
+        // which carries no Bcc at all.
+        return nlohmann::json{{"ok", true}, {"accepted", built.envelopeRecipients}};
+    }
+
     /// `__hostTime(op, payload)`. Every answer comes from functions/timezone.hpp
     /// so a function and a cron schedule can never disagree about what 08:00 in
     /// a zone means.
@@ -1989,6 +2847,7 @@ bool HostContext::install(const JsBindingTarget& target, std::string& error) {
     JSValue crypto = JS_NewCFunctionData(ctx, Impl::hostDispatch<&Impl::cryptoCall>, 2, 0, 1, data);
     JSValue time = JS_NewCFunctionData(ctx, Impl::hostDispatch<&Impl::timeCall>, 2, 0, 1, data);
     JSValue files = JS_NewCFunctionData(ctx, Impl::hostDispatch<&Impl::filesCall>, 2, 0, 1, data);
+    JSValue mail = JS_NewCFunctionData(ctx, Impl::hostDispatch<&Impl::mailCall>, 2, 0, 1, data);
     JS_FreeValue(ctx, cookie);
 
     const std::string_view prelude = hostPreludeSource();
@@ -2004,8 +2863,8 @@ bool HostContext::install(const JsBindingTarget& target, std::string& error) {
         JS_FreeValue(ctx, exc);
         ok = false;
     } else {
-        JSValueConst args[8] = {*ctxObject, db, fetch, log, jobs, crypto, time, files};
-        JSValue applied = JS_Call(ctx, factory, JS_UNDEFINED, 8, args);
+        JSValueConst args[9] = {*ctxObject, db, fetch, log, jobs, crypto, time, files, mail};
+        JSValue applied = JS_Call(ctx, factory, JS_UNDEFINED, 9, args);
         if (JS_IsException(applied)) {
             JSValue exc = JS_GetException(ctx);
             error = "the host prelude failed to install: " + toText(ctx, exc);
@@ -2023,6 +2882,7 @@ bool HostContext::install(const JsBindingTarget& target, std::string& error) {
     JS_FreeValue(ctx, crypto);
     JS_FreeValue(ctx, time);
     JS_FreeValue(ctx, files);
+    JS_FreeValue(ctx, mail);
     return ok;
 }
 

+ 257 - 1
runner/src/host_prelude.js

@@ -19,7 +19,8 @@
 // Every refusal raised here carries a `code`, for the same reason the native
 // side attaches one to an ApiError: a script branches on `e.code`, and matching
 // message text is how a function breaks on a reworded sentence.
-(function (ctx, __hostDb, __hostFetch, __hostLog, __hostJobs, __hostCrypto, __hostTime, __hostFiles) {
+(function (ctx, __hostDb, __hostFetch, __hostLog, __hostJobs, __hostCrypto, __hostTime, __hostFiles,
+          __hostMail) {
   'use strict';
 
   function fail(code, message) {
@@ -366,6 +367,261 @@
     },
   };
 
+  // --- ctx.mail --------------------------------------------------------------
+
+  // Three operations, deliberately few: read a mailbox, list its mailboxes,
+  // send a message. Each one opens a single session and closes it, and a read
+  // is ONE login for the whole thing - a login per message is what gets a mail
+  // account throttled or locked.
+  //
+  // Credentials: prefer `passwordSecret` / `userSecret`, which NAME a project
+  // secret the host resolves. The value then never enters this script's own
+  // variables, so an author who logs the options bag or whose error handler
+  // echoes it cannot leak it, and an operator can rotate it without a code
+  // push. A literal `password` is accepted too, because ctx.env already hands
+  // the script the value anyway - refusing it would only move the same secret
+  // one line earlier.
+
+  const kMailMaxLimit = 200;
+  const kMailCriteriaKeys = ['since', 'before', 'from', 'to', 'subject', 'text', 'body',
+                             'headerName', 'headerValue', 'unseen', 'seen', 'flagged',
+                             'largerThanBytes', 'smallerThanBytes'];
+  const kMailSendKeys = ['host', 'port', 'user', 'userSecret', 'password', 'passwordSecret',
+                         'tls', 'startTls', 'timeoutMs', 'from', 'to', 'cc', 'bcc', 'replyTo',
+                         'subject', 'text', 'html', 'attachments', 'headers', 'inReplyTo',
+                         'references'];
+  const kMailReadKeys = ['host', 'port', 'user', 'userSecret', 'password', 'passwordSecret',
+                         'tls', 'startTls', 'timeoutMs', 'mailbox', 'criteria', 'limit'];
+
+  function mailOnlyKeys(o, allowed, what) {
+    for (const key in o) {
+      if (!Object.prototype.hasOwnProperty.call(o, key)) continue;
+      if (o[key] === undefined) continue;
+      need(allowed.indexOf(key) >= 0,
+           what + " does not take an option named '" + key + "'; it takes: " + allowed.join(', '));
+    }
+  }
+
+  function mailCredential(o, out, literalKey, secretKey, what) {
+    const hasLiteral = o[literalKey] !== undefined && o[literalKey] !== null;
+    const hasSecret = o[secretKey] !== undefined && o[secretKey] !== null;
+    // Both would have to be reconciled, and any rule for that is a guess at
+    // which of two credentials the author meant to be in force.
+    need(!(hasLiteral && hasSecret),
+         what + ' takes ' + literalKey + ' or ' + secretKey + ', not both',
+         'ambiguous_body');
+    if (hasSecret) {
+      need(typeof o[secretKey] === 'string' && o[secretKey].length > 0,
+           what + ' ' + secretKey + ' must name a project secret');
+      out[secretKey] = o[secretKey];
+    } else if (hasLiteral) {
+      need(typeof o[literalKey] === 'string', what + ' ' + literalKey + ' must be a string');
+      out[literalKey] = o[literalKey];
+    }
+  }
+
+  // The connection half, shared by all three calls so a host, a port and a
+  // credential cannot mean three slightly different things.
+  function mailConnection(o, what) {
+    need(typeof o.host === 'string' && o.host.length > 0, what + ' needs a host');
+    const out = { host: o.host };
+    if (o.port !== undefined && o.port !== null) {
+      need(Number.isInteger(o.port) && o.port > 0 && o.port <= 65535,
+           what + ' port must be an integer between 1 and 65535');
+      out.port = o.port;
+    }
+    mailCredential(o, out, 'user', 'userSecret', what);
+    mailCredential(o, out, 'password', 'passwordSecret', what);
+    if (o.tls !== undefined && o.tls !== null) {
+      need(typeof o.tls === 'boolean', what + ' tls must be a boolean');
+      out.tls = o.tls;
+    }
+    if (o.startTls !== undefined && o.startTls !== null) {
+      need(typeof o.startTls === 'boolean', what + ' startTls must be a boolean');
+      out.startTls = o.startTls;
+    }
+    if (o.timeoutMs !== undefined && o.timeoutMs !== null) {
+      // Validated, not coerced, and narrowing only: it can ask for less than
+      // the run's remaining budget and never for more. A zero or a fraction is
+      // a script bug, and accepting one silently would leave the author
+      // believing a bound is in force when none is - which is exactly how
+      // embedTimeoutMs went unnoticed for a whole release.
+      need(Number.isInteger(o.timeoutMs) && o.timeoutMs > 0,
+           what + ' timeoutMs must be a positive integer number of milliseconds');
+      out.timeoutMs = o.timeoutMs;
+    }
+    return out;
+  }
+
+  function mailCriteria(v) {
+    if (v === undefined || v === null) return undefined;
+    if (typeof v === 'string') {
+      // 'ALL' is the only legal string, because anything else would be raw
+      // IMAP search syntax and this surface never lets a script write protocol.
+      need(v === 'ALL',
+           "ctx.mail.read() criteria as a string may only be 'ALL'; pass an object for " +
+           'anything narrower');
+      return 'ALL';
+    }
+    need(isPlainObject(v),
+         "ctx.mail.read() criteria must be an object or the string 'ALL'");
+    const out = {};
+    for (const key in v) {
+      if (!Object.prototype.hasOwnProperty.call(v, key)) continue;
+      if (v[key] === undefined || v[key] === null) continue;
+      need(kMailCriteriaKeys.indexOf(key) >= 0,
+           "ctx.mail.read() criteria has no field named '" + key + "'; it takes: " +
+           kMailCriteriaKeys.join(', '));
+      out[key] = v[key];
+    }
+    // HEADER is one criterion with two halves. A server answers a half-stated
+    // one with a syntax error rather than with a match, so it is caught here
+    // where the message can name both fields.
+    need((out.headerName === undefined) === (out.headerValue === undefined),
+         'ctx.mail.read() criteria needs both headerName and headerValue, or neither');
+    return out;
+  }
+
+  function mailAddresses(v, what) {
+    if (v === undefined || v === null) return undefined;
+    // A single string is accepted because `to: 'a@b'` is what a script writes,
+    // and an array of one is not an improvement.
+    if (typeof v === 'string') return [v];
+    need(Array.isArray(v), what + ' must be a string or an array of strings');
+    for (let i = 0; i < v.length; i++) {
+      need(typeof v[i] === 'string' && v[i].length > 0,
+           what + '[' + i + '] must be an address string');
+    }
+    return v;
+  }
+
+  ctx.mail = {
+    // Resolves to { messages: [...], matched: n }. `matched` is the whole
+    // search result and `messages` the newest `limit` of it, so a script can
+    // tell "that is all of it" from "there is more behind this".
+    //
+    // Each message carries uid, flags, internal_date, size, and the raw
+    // `header` and `text` parts with a `headerEncoding` / `textEncoding` of
+    // 'text' or 'base64' - mail is routinely not UTF-8, so the encoding is
+    // stated rather than assumed.
+    read: function (options) {
+      const o = opts(options, 'ctx.mail.read() options');
+      mailOnlyKeys(o, kMailReadKeys, 'ctx.mail.read()');
+      const out = mailConnection(o, 'ctx.mail.read()');
+      if (o.mailbox !== undefined && o.mailbox !== null) {
+        need(typeof o.mailbox === 'string' && o.mailbox.length > 0,
+             'ctx.mail.read() mailbox must be a mailbox name');
+        out.mailbox = o.mailbox;
+      }
+      if (o.limit !== undefined && o.limit !== null) {
+        need(Number.isInteger(o.limit) && o.limit > 0,
+             'ctx.mail.read() limit must be a positive integer');
+        // Refused rather than clamped: a script asking for 5000 is reasoning
+        // about a result set it is not going to get, and a silent clamp leaves
+        // it reasoning about the wrong one.
+        need(o.limit <= kMailMaxLimit,
+             'ctx.mail.read() limit is capped at ' + kMailMaxLimit +
+             ' messages per read; narrow the criteria instead');
+        out.limit = o.limit;
+      }
+      const criteria = mailCriteria(o.criteria);
+      if (criteria !== undefined) out.criteria = criteria;
+      return __hostMail('read', out);
+    },
+
+    // Resolves to an array of { name, nameEncoding, flags, delimiter }. The
+    // name is decoded from modified UTF-7 by the host; an empty delimiter means
+    // a flat namespace, never "unknown".
+    mailboxes: function (options) {
+      const o = opts(options, 'ctx.mail.mailboxes() options');
+      mailOnlyKeys(o, kMailReadKeys, 'ctx.mail.mailboxes()');
+      return __hostMail('mailboxes', mailConnection(o, 'ctx.mail.mailboxes()'));
+    },
+
+    // Resolves to { ok: true, accepted: [...] }, where `accepted` is the
+    // ENVELOPE recipients the server was given - not the To header, which
+    // carries no Bcc and which a sender may make say anything.
+    send: function (options) {
+      const o = opts(options, 'ctx.mail.send() options');
+      mailOnlyKeys(o, kMailSendKeys, 'ctx.mail.send()');
+      const out = mailConnection(o, 'ctx.mail.send()');
+
+      need(typeof o.from === 'string' && o.from.length > 0,
+           'ctx.mail.send() needs a from address');
+      out.from = o.from;
+      const to = mailAddresses(o.to, 'ctx.mail.send() to');
+      const cc = mailAddresses(o.cc, 'ctx.mail.send() cc');
+      const bcc = mailAddresses(o.bcc, 'ctx.mail.send() bcc');
+      need((to && to.length) || (cc && cc.length) || (bcc && bcc.length),
+           'ctx.mail.send() needs at least one recipient in to, cc or bcc');
+      if (to) out.to = to;
+      if (cc) out.cc = cc;
+      if (bcc) out.bcc = bcc;
+
+      const text = function (key) {
+        if (o[key] === undefined || o[key] === null) return;
+        need(typeof o[key] === 'string', 'ctx.mail.send() ' + key + ' must be a string');
+        out[key] = o[key];
+      };
+      text('replyTo');
+      text('subject');
+      text('text');
+      text('html');
+      text('inReplyTo');
+      text('references');
+      // A message with neither body is almost certainly a mistake, and it is
+      // one the recipient discovers rather than the author.
+      need((typeof out.text === 'string' && out.text.length > 0) ||
+           (typeof out.html === 'string' && out.html.length > 0),
+           'ctx.mail.send() needs a text or html body');
+
+      if (o.attachments !== undefined && o.attachments !== null) {
+        need(Array.isArray(o.attachments), 'ctx.mail.send() attachments must be an array');
+        const list = [];
+        for (let i = 0; i < o.attachments.length; i++) {
+          const a = o.attachments[i];
+          const at = 'ctx.mail.send() attachments[' + i + ']';
+          need(isPlainObject(a), at + ' must be an object');
+          need(typeof a.filename === 'string' && a.filename.length > 0,
+               at + ' needs a filename');
+          const hasBase64 = a.base64 !== undefined && a.base64 !== null;
+          const hasText = a.text !== undefined && a.text !== null;
+          need(!(hasBase64 && hasText), at + ' takes base64 or text, not both', 'ambiguous_body');
+          need(hasBase64 || hasText, at + ' needs base64 bytes or a text string');
+          const entry = { filename: a.filename };
+          // Left absent rather than guessed from the extension: the host turns
+          // an absent type into application/octet-stream, which is what
+          // unknown MEANS.
+          if (a.contentType !== undefined && a.contentType !== null) {
+            need(typeof a.contentType === 'string', at + ' contentType must be a string');
+            entry.contentType = a.contentType;
+          }
+          if (hasBase64) {
+            entry.base64 = base64String(a.base64, at + '.base64');
+          } else {
+            need(typeof a.text === 'string', at + ' text must be a string');
+            entry.text = a.text;
+          }
+          list.push(entry);
+        }
+        out.attachments = list;
+      }
+
+      if (o.headers !== undefined && o.headers !== null) {
+        need(isPlainObject(o.headers),
+             'ctx.mail.send() headers must be an object of name -> value');
+        for (const key in o.headers) {
+          if (!Object.prototype.hasOwnProperty.call(o.headers, key)) continue;
+          need(typeof o.headers[key] === 'string',
+               "ctx.mail.send() header '" + key + "' must have a string value");
+        }
+        out.headers = o.headers;
+      }
+
+      return __hostMail('send', out);
+    }
+  };
+
   // --- ctx.jobs --------------------------------------------------------------
 
   const kMaxDedupeKey = 512;

+ 18 - 0
runner/src/main.cpp

@@ -11,6 +11,7 @@
 // database client, which is what keeps run_service testable on a host where
 // that client cannot compile at all (CLAUDE.md).
 #include "db_await.hpp"
+#include "net/mail_session.hpp"
 #include "db_gateway.hpp"
 #include "errors.hpp"
 #include "function_env.hpp"
@@ -528,6 +529,19 @@ int main(int argc, char** argv) {
 
     std::signal(SIGINT, onSignal); std::signal(SIGTERM, onSignal); std::signal(SIGPIPE, SIG_IGN);
 
+    // Mail, before ANY worker thread exists. curl_global_init is not
+    // thread-safe and curl's own lazy first-use initialisation from two pool
+    // threads at once is a real race, not a theoretical one. It also verifies
+    // libcurl was built thread-safe and REFUSES TO START otherwise, in the
+    // same spirit as the runner refusing to start with no token on a
+    // non-loopback bind: a curl without CURL_VERSION_THREADSAFE cannot be
+    // driven safely from this pool, and finding that out from a crash under
+    // load costs far more than failing here.
+    if (const std::string why = svapi::runner::net::mailGlobalInit(); !why.empty()) {
+        spdlog::error("refusing to start: {}", why);
+        return 1;
+    }
+
     svapi::DbGateway db(cfg.dbAddress);
     spdlog::info("connecting to smartbotic-database at {}", cfg.dbAddress);
     // Bounded by WALL TIME, not by an attempt count - see db_await.hpp. 60 s
@@ -761,6 +775,10 @@ int main(int argc, char** argv) {
     if (worker) worker->stop();
     server.stop();
     if (http.joinable()) http.join();
+    // Paired with mailGlobalInit, and deliberately AFTER the listener and the
+    // job worker have stopped: curl_global_cleanup while a worker could still
+    // be inside a mail call is a use-after-free.
+    svapi::runner::net::mailGlobalCleanup();
     // Non-zero on a listener failure, so Restart=on-failure actually fires. A
     // signal-driven shutdown is a clean exit.
     return serveFailed ? 1 : 0;

+ 21 - 2
runner/tests/fake_mail_server.hpp

@@ -55,6 +55,15 @@ public:
 
     void stop() {
         running_ = false;
+        // The LISTENING socket is not enough. If a client is still connected
+        // the serving thread is blocked in recv() on the CLIENT socket, and
+        // closing the listener never wakes it - stop() then blocks forever on
+        // the join. That is a hang rather than a failure, so it would have
+        // stalled CI rather than reporting anything, and it only shows up when
+        // a session outlives the server (a test whose client is destroyed
+        // after the fixture tears down, which is an ordinary mistake to make).
+        const int client = clientFd_.exchange(-1);
+        if (client >= 0) ::shutdown(client, SHUT_RDWR);
         if (fd_ >= 0) {
             ::shutdown(fd_, SHUT_RDWR);
             ::close(fd_);
@@ -90,14 +99,20 @@ private:
         while (running_) {
             int client = ::accept(fd_, nullptr, nullptr);
             if (client < 0) return;
+            clientFd_ = client;
             serve(client);
+            clientFd_ = -1;
             ::close(client);
         }
     }
 
     void serve(int client) {
         const std::string hello = greeting();
-        if (!hello.empty()) ::send(client, hello.data(), hello.size(), 0);
+        // MSG_NOSIGNAL on every send. Writing to a peer that has gone away
+        // raises SIGPIPE, whose default action kills the whole test PROCESS
+        // rather than failing one test - so one client disconnecting at the
+        // wrong moment takes the entire suite down with no useful output.
+        if (!hello.empty()) ::send(client, hello.data(), hello.size(), MSG_NOSIGNAL);
 
         std::string buffer;
         char chunk[4096];
@@ -113,13 +128,17 @@ private:
                 record(line);
                 bool closeAfter = false;
                 const std::string reply = respond(line, closeAfter);
-                if (!reply.empty()) ::send(client, reply.data(), reply.size(), 0);
+                if (!reply.empty()) ::send(client, reply.data(), reply.size(), MSG_NOSIGNAL);
                 if (closeAfter) return;
             }
         }
     }
 
     int fd_ = -1;
+    /// The connection currently being served, so stop() can unblock it.
+    /// Atomic because stop() runs on the test's thread and the serving loop
+    /// writes it on its own.
+    std::atomic<int> clientFd_{-1};
     uint16_t port_ = 0;
     std::atomic<bool> running_{false};
     std::thread thread_;

+ 640 - 16
runner/tests/host_context_test.cpp

@@ -19,13 +19,20 @@
 // packaging/devstack, not here.
 #include <gtest/gtest.h>
 
+#include <algorithm>
+#include <cctype>
 #include <functional>
 #include <memory>
 #include <set>
 #include <string>
 #include <vector>
 
+#include "fake_mail_server.hpp"
 #include "file_store.hpp"
+#include "net/imap_commands.hpp"
+#include "net/imap_fetch.hpp"
+#include "net/mail_session.hpp"
+#include "net/mime_build.hpp"
 #include "apikey.hpp"
 #include "db_gateway.hpp"
 #include "errors.hpp"
@@ -79,13 +86,34 @@ std::string formatInLocale(const functions::ZoneParts& p, const std::string& pat
                            const std::string& locale);
 std::time_t secondsFromMs(int64_t ms);
 
+// The ctx.mail seams. Same reason as the rest of this block: each is a decision
+// taken before a socket exists, and each is one a mail server must not have to
+// be slow or hostile to provoke.
+std::string customRequestFor(const net::ImapCommand& c);
+bool isLoopbackLiteral(const std::string& host);
+int64_t mailReadLimit(const nlohmann::json& payload);
+int64_t mailTimeoutFrom(const nlohmann::json& payload);
+std::string mailCredential(const nlohmann::json& payload, const nlohmann::json& env,
+                           const char* literalKey, const char* secretKey);
+net::ImapSearchCriteria mailCriteriaFrom(const nlohmann::json& v);
+net::MailMessage mailMessageFrom(const nlohmann::json& payload);
+std::vector<uint64_t> newestUids(const std::vector<uint64_t>& uids, int64_t limit);
+void putMailText(nlohmann::json& out, const char* key, const std::string& bytes);
+std::string decodeMailboxName(const std::string& raw);
+std::string mailSlugMessage(const std::string& slug);
+net::MailFailure mailParseFailure(net::ImapParse status, const char* what);
+net::ImapFetchResult parseCurlFetch(const std::string& response);
+const net::ImapFetchRecord* recordForUid(const net::ImapFetchResult& result, uint64_t uid);
+std::string soleBodyPart(const net::ImapFetchRecord* record, const char* section);
+ApiError apiErrorForMail(const net::MailFailure& f);
+
 struct EgressDecision {
     bool allowed = false;
     std::string pinnedAddress;
     std::string reason;
 };
 using Resolver = std::function<std::vector<std::string>(const std::string&)>;
-EgressDecision decideEgress(const functions::HttpUrlParts& parts, const functions::SsrfPolicy& policy,
+EgressDecision decideEgress(const std::string& host, const functions::SsrfPolicy& policy,
                             const Resolver& resolve);
 
 } // namespace svapi::runner::hostdetail
@@ -513,9 +541,7 @@ TEST(HostDetail, OutboundTimeoutIsWhatIsLeftOfTheRunsBudget) {
 
 TEST(HostDetail, EgressPinsTheAddressTheGuardApproved) {
     auto policy = svapi::functions::SsrfPolicy::withDefaults();
-    auto parts = svapi::functions::parseHttpUrl("https://provider.example/v1/x");
-    ASSERT_TRUE(parts.has_value());
-    auto d = detail::decideEgress(*parts, policy,
+    auto d = detail::decideEgress("provider.example", policy,
                                   [](const std::string&) { return std::vector<std::string>{"93.184.216.34"}; });
     EXPECT_TRUE(d.allowed) << d.reason;
     EXPECT_EQ(d.pinnedAddress, "93.184.216.34");
@@ -525,10 +551,8 @@ TEST(HostDetail, EgressClassifiesEveryAddressNotJustTheFirst) {
     // The multi-A bypass: a hostile name whose first answer is public and whose
     // second is loopback. One blocked address blocks the host.
     auto policy = svapi::functions::SsrfPolicy::withDefaults();
-    auto parts = svapi::functions::parseHttpUrl("http://rebind.example/");
-    ASSERT_TRUE(parts.has_value());
     auto d = detail::decideEgress(
-        *parts, policy,
+        "rebind.example", policy,
         [](const std::string&) { return std::vector<std::string>{"93.184.216.34", "127.0.0.1"}; });
     EXPECT_FALSE(d.allowed);
     EXPECT_TRUE(d.pinnedAddress.empty());
@@ -536,9 +560,7 @@ TEST(HostDetail, EgressClassifiesEveryAddressNotJustTheFirst) {
 
 TEST(HostDetail, EgressFailsClosedOnAResolutionFailure) {
     auto policy = svapi::functions::SsrfPolicy::withDefaults();
-    auto parts = svapi::functions::parseHttpUrl("http://nx.example/");
-    ASSERT_TRUE(parts.has_value());
-    auto d = detail::decideEgress(*parts, policy,
+    auto d = detail::decideEgress("nx.example", policy,
                                   [](const std::string&) { return std::vector<std::string>{}; });
     EXPECT_FALSE(d.allowed);
     EXPECT_FALSE(d.reason.empty());
@@ -554,13 +576,9 @@ TEST(HostDetail, AnAddressLiteralIsClassifiedWithoutAResolver) {
         return std::vector<std::string>{};
     };
 
-    auto blocked = svapi::functions::parseHttpUrl("http://10.0.0.5/");
-    ASSERT_TRUE(blocked.has_value());
-    EXPECT_FALSE(detail::decideEgress(*blocked, policy, resolver).allowed);
+    EXPECT_FALSE(detail::decideEgress("10.0.0.5", policy, resolver).allowed);
 
-    auto allowed = svapi::functions::parseHttpUrl("http://8.8.8.8/");
-    ASSERT_TRUE(allowed.has_value());
-    auto d = detail::decideEgress(*allowed, policy, resolver);
+    auto d = detail::decideEgress("8.8.8.8", policy, resolver);
     EXPECT_TRUE(d.allowed) << d.reason;
     EXPECT_EQ(d.pinnedAddress, "8.8.8.8");
     EXPECT_FALSE(resolved);
@@ -1200,3 +1218,609 @@ TEST(HostContext, FromPartsReportsASkippedLocalTimeRatherThanInventingOne) {
     EXPECT_EQ(out.result.value.at("existed"), false);
     EXPECT_EQ(out.result.value.at("hasEpoch"), "number");
 }
+
+// --- ctx.mail ---------------------------------------------------------------
+//
+// Two kinds of assertion here, and they answer different questions. The pure
+// seams pin the decisions that must not be re-litigated anywhere else: that a
+// command reaches the transport untagged, that plaintext is refused off
+// loopback, that a named secret which does not exist FAILS rather than sending
+// an empty password, and that a transport failure reaches a script as a slug
+// without curl's text behind it. The three driven tests then run the real
+// engine, the real prelude and the real curl against in-process fake servers,
+// because the facts about what curl puts on the wire are only facts when
+// measured.
+
+namespace {
+
+/// A config whose egress policy permits loopback. Not a bypass: it is the
+/// explicit `function_egress_allow_private` opt-out an operator sets for an
+/// internal service, which is exactly the posture a mail server on this host
+/// would need.
+HostContextConfig mailTrigger() {
+    HostContextConfig cfg = httpTrigger({});
+    cfg.egressPolicy = std::make_shared<const svapi::functions::SsrfPolicy>(
+        svapi::functions::SsrfPolicy::fromSettings({}, true, nullptr));
+    cfg.env = {{"MAIL_PASSWORD", "correct-horse-battery-staple"}};
+    // Generous, because a real socket and a real login are involved; the budget
+    // arithmetic itself is tested in mail_net_test.cpp.
+    cfg.deadlineMs = 15000;
+    return cfg;
+}
+
+std::string withPort(std::string src, uint16_t port) {
+    const std::string marker = "%PORT%";
+    for (size_t at = src.find(marker); at != std::string::npos; at = src.find(marker))
+        src.replace(at, marker.size(), std::to_string(port));
+    return src;
+}
+
+} // namespace
+
+TEST(HostDetail, ACommandReachesTheTransportUntaggedAndWithoutItsTerminator) {
+    // curl writes the tag and the CRLF itself for a custom request, so ours
+    // would put two tags on one line. The builders still produce real protocol:
+    // this is the transport adapting to it, not a second command writer.
+    svapi::runner::net::ImapTagger tagger;
+    const std::string examine =
+        detail::customRequestFor(svapi::runner::net::imapExamine(tagger.next(), "INBOX"));
+    // An atom, because that is the narrowest legal form for INBOX - the
+    // encoder quotes only what has to be quoted, and asserting the quoted form
+    // would be asserting a preference rather than the protocol.
+    EXPECT_EQ(examine, "EXAMINE INBOX");
+    EXPECT_EQ(examine.find("A001"), std::string::npos);
+    EXPECT_EQ(examine.find('\r'), std::string::npos);
+
+    // BODY.PEEK, never BODY: the unpeeked form sets \Seen as a side effect of
+    // reading, so a function that merely looked at a mailbox would mark mail
+    // read. Asserted on the exact bytes, because the difference is invisible
+    // otherwise.
+    const std::string fetch = detail::customRequestFor(
+        svapi::runner::net::imapUidFetch(tagger.next(), {7, 9}, "HEADER"));
+    EXPECT_EQ(fetch, "UID FETCH 7,9 (UID FLAGS INTERNALDATE RFC822.SIZE BODY.PEEK[HEADER])");
+}
+
+TEST(HostDetail, ACommandNeedingAContinuationIsRefusedRatherThanFlattened) {
+    // A literal's octets may only follow the server's `+`. Concatenating them
+    // works against a permissive server and deadlocks against a strict one,
+    // which is the kind of bug that only shows up in production.
+    svapi::runner::net::ImapTagger tagger;
+    // An 8-bit mailbox name is modified-UTF-7 encoded and therefore stays
+    // quotable, so the literal case has to be provoked with a name that is
+    // simply too long to quote comfortably - here, one carrying a quote-hostile
+    // control byte is refused earlier, so use the builder's own literal form.
+    svapi::runner::net::ImapCommand c;
+    c.tag = "A001";
+    c.chunks = {"A001 LOGIN {5}\r\n", "secret\r\n"};
+    EXPECT_TRUE(c.needsContinuation());
+    try {
+        detail::customRequestFor(c);
+        FAIL() << "a continuation command must be refused";
+    } catch (const ApiError& e) {
+        EXPECT_EQ(e.slug, "mail_bad_argument");
+    }
+}
+
+TEST(HostDetail, OnlyALoopbackLiteralCountsAsLoopback) {
+    EXPECT_TRUE(detail::isLoopbackLiteral("127.0.0.1"));
+    EXPECT_TRUE(detail::isLoopbackLiteral("127.1.2.3"));
+    EXPECT_TRUE(detail::isLoopbackLiteral("::1"));
+    // A NAME is never loopback here, whatever it resolves to: that is the
+    // rebinding case, and the plaintext decision must not depend on a lookup.
+    EXPECT_FALSE(detail::isLoopbackLiteral("localhost"));
+    EXPECT_FALSE(detail::isLoopbackLiteral("mail.example.com"));
+    EXPECT_FALSE(detail::isLoopbackLiteral("10.0.0.1"));
+    EXPECT_FALSE(detail::isLoopbackLiteral(""));
+}
+
+TEST(HostDetail, AMailLimitIsValidatedAndCappedRatherThanCoerced) {
+    EXPECT_EQ(detail::mailReadLimit(nlohmann::json::object()), 20);
+    EXPECT_EQ(detail::mailReadLimit({{"limit", 5}}), 5);
+    EXPECT_EQ(detail::mailReadLimit({{"limit", 200}}), 200);
+    EXPECT_THROW(detail::mailReadLimit({{"limit", 201}}), ApiError);
+    EXPECT_THROW(detail::mailReadLimit({{"limit", 0}}), ApiError);
+    EXPECT_THROW(detail::mailReadLimit({{"limit", -1}}), ApiError);
+    EXPECT_THROW(detail::mailReadLimit({{"limit", 1.5}}), ApiError);
+    EXPECT_THROW(detail::mailReadLimit({{"limit", "20"}}), ApiError);
+    // Absent and null are the same request, and both mean the default.
+    EXPECT_EQ(detail::mailReadLimit({{"limit", nullptr}}), 20);
+}
+
+TEST(HostDetail, AMailTimeoutIsValidatedNotSilentlyIgnored) {
+    // The lesson embedTimeoutMs taught: an option accepted and dropped leaves
+    // the author believing a bound is in force when none is.
+    EXPECT_EQ(detail::mailTimeoutFrom(nlohmann::json::object()), 0);
+    EXPECT_EQ(detail::mailTimeoutFrom({{"timeoutMs", 1500}}), 1500);
+    EXPECT_THROW(detail::mailTimeoutFrom({{"timeoutMs", 0}}), ApiError);
+    EXPECT_THROW(detail::mailTimeoutFrom({{"timeoutMs", -5}}), ApiError);
+    EXPECT_THROW(detail::mailTimeoutFrom({{"timeoutMs", 2.5}}), ApiError);
+}
+
+TEST(HostDetail, ANamedSecretThatDoesNotExistFailsRatherThanSendingAnEmptyPassword) {
+    const nlohmann::json env{{"MAIL_PASSWORD", "s3cret"}};
+    EXPECT_EQ(detail::mailCredential({{"passwordSecret", "MAIL_PASSWORD"}}, env, "password",
+                                     "passwordSecret"),
+              "s3cret");
+    // The whole point: an empty password reaches the server as an auth failure,
+    // and the author then goes looking at the mail account rather than at the
+    // typo in the name.
+    try {
+        detail::mailCredential({{"passwordSecret", "MAIL_PASWORD"}}, env, "password",
+                               "passwordSecret");
+        FAIL() << "a missing secret must be refused";
+    } catch (const ApiError& e) {
+        EXPECT_EQ(e.slug, "mail_secret_missing");
+        EXPECT_NE(std::string(e.what()).find("MAIL_PASWORD"), std::string::npos);
+        // It names the secret, never a value - this message travels to a script.
+        EXPECT_EQ(std::string(e.what()).find("s3cret"), std::string::npos);
+    }
+}
+
+TEST(HostDetail, ALiteralCredentialIsAcceptedAndTwoAreNot) {
+    const nlohmann::json env{{"MAIL_PASSWORD", "s3cret"}};
+    EXPECT_EQ(detail::mailCredential({{"password", "literal"}}, env, "password", "passwordSecret"),
+              "literal");
+    // Nothing given is empty rather than an error: an IMAP server on loopback
+    // may want no credentials at all.
+    EXPECT_EQ(detail::mailCredential(nlohmann::json::object(), env, "password", "passwordSecret"),
+              "");
+    try {
+        detail::mailCredential({{"password", "a"}, {"passwordSecret", "MAIL_PASSWORD"}}, env,
+                               "password", "passwordSecret");
+        FAIL() << "two credentials must be refused rather than reconciled";
+    } catch (const ApiError& e) {
+        EXPECT_EQ(e.slug, "ambiguous_body");
+    }
+}
+
+TEST(HostDetail, SearchCriteriaMapOntoTheBuildersFieldsAndNothingElse) {
+    // "ALL" and absence are the same request, because an empty criteria set is
+    // what imapUidSearch renders as `UID SEARCH ALL`.
+    svapi::runner::net::ImapTagger tagger;
+    EXPECT_EQ(detail::customRequestFor(svapi::runner::net::imapUidSearch(
+                  tagger.next(), detail::mailCriteriaFrom(nlohmann::json()))),
+              "UID SEARCH ALL");
+    EXPECT_EQ(detail::customRequestFor(svapi::runner::net::imapUidSearch(
+                  tagger.next(), detail::mailCriteriaFrom("ALL"))),
+              "UID SEARCH ALL");
+
+    const nlohmann::json spec{{"since", "1-Jan-2026"}, {"from", "a@example.com"},
+                              {"unseen", true},        {"largerThanBytes", 1024}};
+    const std::string wire = detail::customRequestFor(
+        svapi::runner::net::imapUidSearch(tagger.next(), detail::mailCriteriaFrom(spec)));
+    EXPECT_NE(wire.find("SINCE 1-Jan-2026"), std::string::npos) << wire;
+    EXPECT_NE(wire.find("FROM a@example.com"), std::string::npos) << wire;
+    EXPECT_NE(wire.find("UNSEEN"), std::string::npos) << wire;
+    EXPECT_NE(wire.find("LARGER 1024"), std::string::npos) << wire;
+
+    EXPECT_THROW(detail::mailCriteriaFrom("UNSEEN"), ApiError);
+    EXPECT_THROW(detail::mailCriteriaFrom({{"since", 7}}), ApiError);
+    EXPECT_THROW(detail::mailCriteriaFrom({{"unseen", "yes"}}), ApiError);
+    EXPECT_THROW(detail::mailCriteriaFrom(nlohmann::json::array()), ApiError);
+}
+
+TEST(HostDetail, AnInjectedMailboxNameIsRefusedByTheBuilderNotSanitised) {
+    // The command builders are the injection boundary and this is the proof
+    // that ctx.mail actually goes through them: a CRLF in a mailbox name is two
+    // commands, and the second one is the attacker's.
+    svapi::runner::net::ImapTagger tagger;
+    EXPECT_THROW(svapi::runner::net::imapExamine(tagger.next(), "INBOX\r\nA002 LOGOUT"),
+                 svapi::runner::net::ImapCommandError);
+    EXPECT_THROW(svapi::runner::net::imapExamine(tagger.next(), std::string("IN\0BOX", 6)),
+                 svapi::runner::net::ImapCommandError);
+}
+
+TEST(HostDetail, TheNewestUidsAreTakenNotTheOldest) {
+    // UID SEARCH answers ascending and the newest message carries the highest
+    // uid, so taking the head would answer with the oldest mail - a silently
+    // wrong answer rather than an error.
+    const std::vector<uint64_t> uids{3, 7, 9, 12, 20};
+    EXPECT_EQ(detail::newestUids(uids, 2), (std::vector<uint64_t>{12, 20}));
+    EXPECT_EQ(detail::newestUids(uids, 99), uids);
+    EXPECT_TRUE(detail::newestUids(uids, 0).empty());
+    EXPECT_TRUE(detail::newestUids({}, 5).empty());
+    // Sorted and de-duplicated here rather than trusted: the ordering is the
+    // server's, and "newest" has to be well defined either way.
+    EXPECT_EQ(detail::newestUids({9, 3, 9, 7}, 2), (std::vector<uint64_t>{7, 9}));
+}
+
+TEST(HostDetail, AMailPartThatIsNotUtf8TravelsAsBase64WithItsEncodingStated) {
+    // A Hungarian message in ISO-8859-2 is ordinary, not exotic, and nlohmann's
+    // dump() throws on an invalid sequence - which would reach the author as an
+    // internal error naming neither the message nor the fix.
+    nlohmann::json out = nlohmann::json::object();
+    detail::putMailText(out, "text", "arvizturo tukorfurogep");
+    EXPECT_EQ(out.at("text"), "arvizturo tukorfurogep");
+    EXPECT_EQ(out.at("textEncoding"), "text");
+
+    nlohmann::json latin = nlohmann::json::object();
+    detail::putMailText(latin, "text", std::string("\xE1rv\xEDzt\xFBr\xF5", 8));
+    EXPECT_EQ(latin.at("textEncoding"), "base64");
+    EXPECT_EQ(detail::base64Decode(latin.at("text").get<std::string>()),
+              std::string("\xE1rv\xEDzt\xFBr\xF5", 8));
+    // And the shaped object survives the boundary it exists for, which is the
+    // assertion that would have caught the raw-bytes version.
+    EXPECT_NO_THROW(latin.dump());
+}
+
+TEST(HostDetail, AMailboxNameIsDecodedFromModifiedUtf7AndAnUndecodableOneSurvives) {
+    // imap_fetch returns the name RAW by contract; decoding it is the caller's
+    // job, and this is that caller.
+    EXPECT_EQ(detail::decodeMailboxName("INBOX"), "INBOX");
+    EXPECT_EQ(detail::decodeMailboxName("Bo&AO0-te"), "Bo\xC3\xADte");
+    // A name that will not decode is handed back raw rather than dropped: the
+    // mailbox exists either way, and the raw bytes are the only ones that can
+    // be fed back to a read.
+    EXPECT_EQ(detail::decodeMailboxName("&&&"), "&&&");
+}
+
+TEST(HostDetail, MailErrorsKeepTheirSlugAndDropTheTransportsOwnText) {
+    const svapi::runner::net::MailFailure tooLarge{
+        413, "mail_too_large", "curl: Maximum file size exceeded for imaps://user@host", false};
+    const ApiError a = detail::apiErrorForMail(tooLarge);
+    EXPECT_EQ(a.slug, "mail_too_large");
+    EXPECT_EQ(std::string(a.what()).find("curl"), std::string::npos) << a.what();
+    EXPECT_EQ(std::string(a.what()).find("imaps://"), std::string::npos) << a.what();
+    EXPECT_EQ(a.details.at("retryable"), false);
+
+    const svapi::runner::net::MailFailure timedOut{504, "mail_timeout", "Operation timed out", true};
+    EXPECT_EQ(svapi::httpStatus(detail::apiErrorForMail(timedOut).code), 504);
+    EXPECT_EQ(detail::apiErrorForMail(timedOut).details.at("retryable"), true);
+
+    // 550 is overwhelmingly the caller's fault (a bad recipient, a rejected
+    // sender), so it stays a 422 rather than becoming "the server is broken".
+    const svapi::runner::net::MailFailure rejected{
+        422, "mail_rejected", "550 5.1.1 <nobody@example.com> user unknown", false};
+    EXPECT_EQ(svapi::httpStatus(detail::apiErrorForMail(rejected).code), 422);
+    EXPECT_EQ(std::string(detail::apiErrorForMail(rejected).what()).find("550"),
+              std::string::npos);
+
+    const svapi::runner::net::MailFailure auth{502, "mail_auth_failed", "Login denied", false};
+    EXPECT_EQ(detail::apiErrorForMail(auth).slug, "mail_auth_failed");
+    // Never a guessed 422 for a transport failure: telling a caller its payload
+    // was wrong when the server was unreachable sends it to fix working code.
+    EXPECT_EQ(svapi::httpStatus(detail::apiErrorForMail(auth).code), 503);
+}
+
+TEST(HostDetail, AnOutgoingMessageKeepsBccOutOfTheHeadersAndInTheEnvelope) {
+    const nlohmann::json payload{{"from", "sender@example.com"},
+                                 {"to", "a@example.com"},
+                                 {"cc", nlohmann::json::array({"b@example.com"})},
+                                 {"bcc", "hidden@example.com"},
+                                 {"subject", "hello"},
+                                 {"text", "body"},
+                                 {"headers", {{"X-Trace", "abc"}}}};
+    const svapi::runner::net::MailMessage m = detail::mailMessageFrom(payload);
+    EXPECT_EQ(m.from, "sender@example.com");
+    EXPECT_EQ(m.to, (std::vector<std::string>{"a@example.com"}));
+    EXPECT_EQ(m.bcc, (std::vector<std::string>{"hidden@example.com"}));
+    ASSERT_EQ(m.headers.size(), 1u);
+    EXPECT_EQ(m.headers[0].name, "X-Trace");
+
+    const svapi::runner::net::BuiltMail built = svapi::runner::net::buildMail(m, 42);
+    // The classic bug in this area: a Bcc in a header discloses one recipient
+    // to another. It belongs in the envelope and nowhere else.
+    EXPECT_EQ(built.data.find("hidden@example.com"), std::string::npos);
+    EXPECT_NE(std::find(built.envelopeRecipients.begin(), built.envelopeRecipients.end(),
+                        "hidden@example.com"),
+              built.envelopeRecipients.end());
+
+    EXPECT_THROW(detail::mailMessageFrom({{"to", "a@example.com"}, {"text", "x"}}), ApiError);
+    EXPECT_THROW(detail::mailMessageFrom({{"from", "a@example.com"}, {"text", "x"}}), ApiError);
+    EXPECT_THROW(detail::mailMessageFrom({{"from", "a@b"}, {"to", 7}, {"text", "x"}}), ApiError);
+}
+
+// --- ctx.mail, driven against the fakes -------------------------------------
+
+TEST(HostContextMail, AReadIsOneLoginAndUsesExamineWithPeekSoNothingIsMarkedSeen) {
+    svapi::testing::FakeImapServer server;
+    ASSERT_TRUE(server.start());
+
+    auto out = runScript(mailTrigger(),
+                         withPort(catching("ctx.mail.read({ host: '127.0.0.1', port: %PORT%,"
+                                           "  tls: false, user: 'someone@example.com',"
+                                           "  passwordSecret: 'MAIL_PASSWORD', limit: 3 })"),
+                                  server.port()));
+    ASSERT_TRUE(out.result.ok) << out.result.error;
+    ASSERT_EQ(out.result.value.at("threw"), false) << out.result.value.dump();
+    const nlohmann::json& value = out.result.value.at("value");
+    // The fake answers `* SEARCH 7 9 11` and a FETCH for uid 7.
+    EXPECT_EQ(value.at("matched"), 3);
+    ASSERT_FALSE(value.at("messages").empty()) << value.dump();
+    EXPECT_EQ(value.at("messages").at(0).at("uid"), 7);
+    EXPECT_EQ(value.at("messages").at(0).at("headerEncoding"), "text");
+    // The bytes come from the parser's body parts, never from the response
+    // buffer - which is the difference between an e-mail and a protocol line.
+    EXPECT_NE(value.at("messages").at(0).at("header").get<std::string>().find("Subject: hello"),
+              std::string::npos)
+        << value.dump();
+    EXPECT_EQ(value.at("messages").at(0).at("header").get<std::string>().find("FETCH"),
+              std::string::npos)
+        << value.dump();
+
+    const std::vector<std::string> wire = server.received();
+    const auto count = [&wire](const std::string& needle) {
+        return std::count_if(wire.begin(), wire.end(), [&](const std::string& l) {
+            return l.find(needle) != std::string::npos;
+        });
+    };
+    // ONE login for the whole conversation. A login per message is what gets a
+    // mail account throttled or locked, and it is the only part of this that a
+    // transcript can prove.
+    EXPECT_EQ(count("LOGIN"), 1) << "wire: " << nlohmann::json(wire).dump(2);
+    EXPECT_GE(count("EXAMINE"), 1);
+    EXPECT_EQ(count("SELECT"), 0) << "SELECT opens the mailbox read-write; a read must EXAMINE";
+    EXPECT_GE(count("UID SEARCH"), 1);
+    EXPECT_GE(count("BODY.PEEK"), 1);
+    // Not a style point: the unpeeked form sets \Seen, and a STORE to undo it
+    // removes a flag it may not have set.
+    EXPECT_EQ(count("STORE"), 0);
+    for (const std::string& line : wire)
+        EXPECT_EQ(line.find("correct-horse-battery-staple"), std::string::npos)
+            << "a credential reached the transcript";
+    server.stop();
+}
+
+TEST(HostContextMail, MailboxNamesAreDecodedForTheScript) {
+    svapi::testing::FakeImapServer server;
+    ASSERT_TRUE(server.start());
+
+    auto out = runScript(mailTrigger(),
+                         withPort(catching("ctx.mail.mailboxes({ host: '127.0.0.1',"
+                                           "  port: %PORT%, tls: false,"
+                                           "  user: 'u', password: 'p' })"),
+                                  server.port()));
+    ASSERT_TRUE(out.result.ok) << out.result.error;
+    ASSERT_EQ(out.result.value.at("threw"), false) << out.result.value.dump();
+    const nlohmann::json& value = out.result.value.at("value");
+    ASSERT_EQ(value.size(), 1u) << value.dump();
+    EXPECT_EQ(value.at(0).at("name"), "INBOX");
+    EXPECT_EQ(value.at(0).at("delimiter"), "/");
+    EXPECT_EQ(value.at(0).at("flags").at(0), "\\HasNoChildren");
+    server.stop();
+}
+
+TEST(HostContextMail, ASendOffersEveryRecipientToTheServerAndNoBccHeader) {
+    svapi::testing::FakeSmtpServer server;
+    ASSERT_TRUE(server.start());
+
+    auto out = runScript(
+        mailTrigger(),
+        withPort(catching("ctx.mail.send({ host: '127.0.0.1', port: %PORT%, tls: false,"
+                          "  user: 'u', password: 'p', from: 'sender@example.com',"
+                          "  to: 'a@example.com', bcc: ['hidden@example.com'],"
+                          "  subject: 'hello', text: 'body text' })"),
+                 server.port()));
+    ASSERT_TRUE(out.result.ok) << out.result.error;
+    ASSERT_EQ(out.result.value.at("threw"), false) << out.result.value.dump();
+    EXPECT_EQ(out.result.value.at("value").at("ok"), true);
+    EXPECT_EQ(out.result.value.at("value").at("accepted").size(), 2u);
+
+    const std::string data = server.dataReceived();
+    EXPECT_NE(data.find("Subject: hello"), std::string::npos) << data;
+    EXPECT_NE(data.find("body text"), std::string::npos) << data;
+    // The envelope carries the Bcc; the message must not.
+    EXPECT_EQ(data.find("hidden@example.com"), std::string::npos) << data;
+    const std::vector<std::string> wire = server.received();
+    EXPECT_TRUE(std::any_of(wire.begin(), wire.end(), [](const std::string& l) {
+        return l.find("RCPT TO:<hidden@example.com>") != std::string::npos;
+    })) << nlohmann::json(wire).dump(2);
+    server.stop();
+}
+
+TEST(HostContextMail, AMailHostGoesThroughTheSameEgressGuardCtxFetchDoes) {
+    // Default policy: loopback is blocked, and a mail host is not special.
+    auto out = runScript(httpTrigger({}),
+                         catching("ctx.mail.mailboxes({ host: '127.0.0.1', port: 143,"
+                                  "  tls: false, user: 'u', password: 'p' })"));
+    ASSERT_TRUE(out.result.ok) << out.result.error;
+    EXPECT_EQ(out.result.value.at("threw"), true);
+    EXPECT_EQ(out.result.value.at("code"), "egress_blocked") << out.result.value.dump();
+    ASSERT_EQ(out.blocked.size(), 1u);
+    EXPECT_NE(out.blocked[0].find("127.0.0.1"), std::string::npos) << out.blocked[0];
+
+    // TLS left at its default, because the plaintext rule would otherwise
+    // answer first and this test would stop being about egress at all.
+    auto meta = runScript(httpTrigger({}),
+                          catching("ctx.mail.read({ host: '169.254.169.254',"
+                                   "  user: 'u', password: 'p' })"));
+    ASSERT_TRUE(meta.result.ok) << meta.result.error;
+    EXPECT_EQ(meta.result.value.at("code"), "egress_blocked");
+}
+
+TEST(HostContextMail, APlaintextSessionIsRefusedOffLoopback) {
+    // The credentials go over this connection in the clear, so the only place
+    // it is defensible is a server on this machine. Checked with a policy that
+    // would otherwise ALLOW the destination, or this would be testing the
+    // egress guard again rather than the TLS rule.
+    HostContextConfig cfg = mailTrigger();
+    auto out = runScript(std::move(cfg),
+                         catching("ctx.mail.read({ host: '10.0.0.5', tls: false,"
+                                  "  user: 'u', password: 'p' })"));
+    ASSERT_TRUE(out.result.ok) << out.result.error;
+    EXPECT_EQ(out.result.value.at("threw"), true);
+    EXPECT_EQ(out.result.value.at("code"), "mail_tls_required") << out.result.value.dump();
+}
+
+TEST(HostContextMail, AMissingSecretReachesTheScriptAsItsOwnCode) {
+    auto out = runScript(mailTrigger(),
+                         catching("ctx.mail.read({ host: 'mail.example.com',"
+                                  "  user: 'u', passwordSecret: 'NOPE' })"));
+    ASSERT_TRUE(out.result.ok) << out.result.error;
+    EXPECT_EQ(out.result.value.at("threw"), true);
+    EXPECT_EQ(out.result.value.at("code"), "mail_secret_missing") << out.result.value.dump();
+}
+
+TEST(HostContextMail, MailStopsWhenTheRunsBudgetIsGone) {
+    HostContextConfig cfg = mailTrigger();
+    cfg.deadlineMs = 1;
+    auto out = runScript(std::move(cfg),
+                         catching("(() => { const t = Date.now();"
+                                  "          while (Date.now() - t < 20) {}"
+                                  "          return ctx.mail.read({ host: '8.8.8.8',"
+                                  "            user: 'u', password: 'p' }); })()"));
+    ASSERT_TRUE(out.result.ok) << out.result.error;
+    EXPECT_EQ(out.result.value.at("threw"), true);
+    EXPECT_EQ(out.result.value.at("code"), "deadline_exceeded") << out.result.value.dump();
+    EXPECT_TRUE(out.blocked.empty());  // a budget refusal is not an egress refusal
+}
+
+TEST(HostDetail, AnIncompleteResponseIsAFailureAndARetryableOne) {
+    // NeedMore means THE RESPONSE IS INCOMPLETE, not "succeed with what
+    // arrived". The transport has already finished the transfer by the time we
+    // parse, so NeedMore at that point means the server stopped mid-literal. A
+    // sibling implementation trimmed the trailing `)` and CRLF off whatever had
+    // arrived and reported success, so an interrupted transfer came back as a
+    // short but perfectly valid-looking e-mail.
+    const svapi::runner::net::MailFailure needMore =
+        detail::mailParseFailure(svapi::runner::net::ImapParse::NeedMore, "body fetch");
+    EXPECT_EQ(needMore.slug, "mail_incomplete");
+    EXPECT_EQ(needMore.status, 504);
+    // A peek fetch changes no flag, so nothing in the mailbox was touched and
+    // repeating it is safe - which is the one thing a caller needs told.
+    EXPECT_TRUE(needMore.retryable);
+    EXPECT_EQ(detail::apiErrorForMail(needMore).details.at("retryable"), true);
+
+    const svapi::runner::net::MailFailure malformed =
+        detail::mailParseFailure(svapi::runner::net::ImapParse::Malformed, "body fetch");
+    EXPECT_EQ(malformed.slug, "mail_protocol_error");
+    EXPECT_FALSE(malformed.retryable);
+}
+
+TEST(HostDetail, CurlsOwnFetchDeliveryIsParsedWithoutTrustingWhatArrived) {
+    // MEASURED against real curl 8.22: a successful single-uid fetch reaches
+    // the write callback as the untagged line plus the literal's octets and
+    // NOTHING MORE - curl keeps the closing `)` and the tagged completion. The
+    // parser is octet-counted and right to call that incomplete.
+    const std::string body = "From: a@example.com\r\nSubject: hello\r\n\r\nbody text\r\n";
+    const std::string asCurlDelivers =
+        "* 1 FETCH (UID 7 BODY[] {" + std::to_string(body.size()) + "}\r\n" + body;
+    ASSERT_EQ(svapi::runner::net::parseFetchResponse(asCurlDelivers).status,
+              svapi::runner::net::ImapParse::NeedMore)
+        << "if this ever passes, curl's delivery changed and parseCurlFetch should be revisited";
+
+    const svapi::runner::net::ImapFetchResult ok = detail::parseCurlFetch(asCurlDelivers);
+    ASSERT_EQ(ok.status, svapi::runner::net::ImapParse::Ok);
+    ASSERT_EQ(ok.messages.size(), 1u);
+    EXPECT_EQ(ok.messages[0].uid, 7u);
+    EXPECT_EQ(detail::soleBodyPart(detail::recordForUid(ok, 7), "HEADER"), body);
+
+    // Zero bytes is what a uid the server did not return looks like, and
+    // fetching nothing is not an error in IMAP. Ok with no messages, which the
+    // caller skips.
+    const svapi::runner::net::ImapFetchResult absent = detail::parseCurlFetch("");
+    EXPECT_EQ(absent.status, svapi::runner::net::ImapParse::Ok);
+    EXPECT_TRUE(absent.messages.empty());
+    EXPECT_EQ(detail::recordForUid(absent, 7), nullptr);
+
+    // And the reason restoring the framing is SAFE: it cannot satisfy an
+    // announced byte count that was never sent, so a server that stopped
+    // mid-literal still answers NeedMore and is still a failure.
+    const svapi::runner::net::ImapFetchResult shortLiteral =
+        detail::parseCurlFetch("* 1 FETCH (UID 7 BODY[] {50}\r\n0123456789");
+    EXPECT_EQ(shortLiteral.status, svapi::runner::net::ImapParse::NeedMore);
+    EXPECT_TRUE(shortLiteral.messages.empty());
+}
+
+TEST(HostDetail, ABodyContainingATerminatorAndATaggedLineSurvivesByteIntact) {
+    // Why NeedMore must never be "fixed" by searching for a terminator such as
+    // `")\r\n"`: the reader is octet-counted and anchors on the announced {n},
+    // which is what lets a body whose CONTENT contains both of those come
+    // through intact. A terminator search would truncate exactly these bodies,
+    // and real mail contains them.
+    const std::string body = "line one\r\n)\r\nA003 OK Fetch completed\r\nline two\r\n";
+    const std::string response = "* 1 FETCH (UID 7 BODY[TEXT] {" +
+                                 std::to_string(body.size()) + "}\r\n" + body + ")\r\n" +
+                                 "A003 OK Fetch completed\r\n";
+    const svapi::runner::net::ImapFetchResult parsed =
+        svapi::runner::net::parseFetchResponse(response);
+    ASSERT_EQ(parsed.status, svapi::runner::net::ImapParse::Ok);
+    ASSERT_EQ(parsed.messages.size(), 1u);
+    const auto it = parsed.messages[0].bodyParts.find("TEXT");
+    ASSERT_NE(it, parsed.messages[0].bodyParts.end());
+    EXPECT_EQ(it->second, body);
+}
+
+namespace {
+
+std::string upperOf(const std::string& s) {
+    std::string out;
+    out.reserve(s.size());
+    for (char c : s) out.push_back(static_cast<char>(::toupper(static_cast<unsigned char>(c))));
+    return out;
+}
+
+/// A server whose UID FETCH answers with the tagged completion ALONE, which is
+/// what a real one does when the uid is no longer in the mailbox. Fetching
+/// nothing is not an error in IMAP.
+class AbsentUidImapServer : public svapi::testing::FakeImapServer {
+protected:
+    std::string respond(const std::string& line, bool& closeAfter) override {
+        if (upperOf(line).find("UID FETCH") != std::string::npos)
+            return line.substr(0, line.find(' ')) + " OK Fetch completed\r\n";
+        return svapi::testing::FakeImapServer::respond(line, closeAfter);
+    }
+};
+
+/// A server that ANNOUNCES more octets than it sends and then hangs up. The
+/// exact failure curl reports for this is curl's call - a short read or a lost
+/// connection - and the assertion is only that it is a failure, never a short
+/// body.
+class TruncatedLiteralImapServer : public svapi::testing::FakeImapServer {
+protected:
+    std::string respond(const std::string& line, bool& closeAfter) override {
+        if (upperOf(line).find("UID FETCH") != std::string::npos) {
+            closeAfter = true;
+            return "* 1 FETCH (UID 7 BODY[HEADER] {50000}\r\n0123456789";
+        }
+        return svapi::testing::FakeImapServer::respond(line, closeAfter);
+    }
+};
+
+} // namespace
+
+TEST(HostContextMail, AUidThatVanishedBetweenTheSearchAndTheFetchIsSkippedNotFabricated) {
+    // The bug this exists for: an implementation that saw a status of Ok and
+    // read the response buffer anyway handed the PROTOCOL LINE back as the
+    // e-mail, producing a successful fetch whose body was
+    // "A003 OK Fetch completed" and whose sender was empty.
+    AbsentUidImapServer server;
+    ASSERT_TRUE(server.start());
+
+    auto out = runScript(mailTrigger(),
+                         withPort(catching("ctx.mail.read({ host: '127.0.0.1', port: %PORT%,"
+                                           "  tls: false, user: 'u', password: 'p' })"),
+                                  server.port()));
+    ASSERT_TRUE(out.result.ok) << out.result.error;
+    ASSERT_EQ(out.result.value.at("threw"), false) << out.result.value.dump();
+    const nlohmann::json& value = out.result.value.at("value");
+    // The search still matched three uids, and not one of them became a
+    // message. An empty array is the right answer; a blank message is not.
+    EXPECT_EQ(value.at("matched"), 3);
+    EXPECT_TRUE(value.at("messages").empty()) << value.dump();
+    EXPECT_EQ(value.dump().find("Fetch completed"), std::string::npos) << value.dump();
+    server.stop();
+}
+
+TEST(HostContextMail, ATruncatedLiteralIsAnErrorRatherThanAShortBody) {
+    TruncatedLiteralImapServer server;
+    ASSERT_TRUE(server.start());
+
+    auto out = runScript(mailTrigger(),
+                         withPort(catching("ctx.mail.read({ host: '127.0.0.1', port: %PORT%,"
+                                           "  tls: false, user: 'u', password: 'p' })"),
+                                  server.port()));
+    ASSERT_TRUE(out.result.ok) << out.result.error;
+    ASSERT_EQ(out.result.value.at("threw"), true) << out.result.value.dump();
+    // Which failure it is belongs to the layer that noticed: curl reports a
+    // lost connection or a short read, and our own parser reports
+    // mail_incomplete when it gets to see the bytes at all. What must never
+    // happen is a success carrying the ten octets that did arrive.
+    const std::string code = out.result.value.at("code").get<std::string>();
+    EXPECT_TRUE(code == "mail_incomplete" || code == "mail_connection_lost" ||
+                code == "mail_timeout" || code == "mail_protocol_error")
+        << out.result.value.dump();
+    EXPECT_EQ(out.result.value.dump().find("0123456789"), std::string::npos)
+        << out.result.value.dump();
+    server.stop();
+}

+ 143 - 1
runner/tests/host_prelude_test.cpp

@@ -63,6 +63,7 @@ function __answer(kind) {
   if (kind === 'jobs') return 'job-1';
   if (kind === 'crypto') return 'deadbeef';
   if (kind === 'time') return { year: 2026, month: 10, day: 7 };
+  if (kind === 'mail') return { messages: [], matched: 0 };
   return null;
 }
 
@@ -80,7 +81,8 @@ export default function () {
   }
   const ctx = {};
   __installHost(ctx, recorder('db'), recorder('fetch'), recorder('log'),
-                recorder('jobs'), recorder('crypto'), recorder('time'));
+                recorder('jobs'), recorder('crypto'), recorder('time'),
+                recorder('files'), recorder('mail'));
 
   let value = null;
   let threw = null;
@@ -576,3 +578,143 @@ TEST(HostPrelude, LogStillFormatsObjectsAsJson) {
     ASSERT_EQ(out.at("calls").size(), 1u);
     EXPECT_EQ(out.at("calls").at(0).at("args").at(0), "two 2 {\"a\":1}");
 }
+
+
+// --- ctx.mail ---------------------------------------------------------------
+//
+// The assertion that matters here is the one only this file can make: every
+// mail argument is checked BEFORE the host is reached, so a refusal leaves the
+// recorder's call list EMPTY. A credential, a host and a timeout that reach the
+// host before being checked have already been handed to a transport.
+
+TEST(HostPrelude, InstallsTheMailSurface) {
+    const nlohmann::json out = runPrelude(
+        "return { read: typeof ctx.mail.read, mailboxes: typeof ctx.mail.mailboxes,"
+        "         send: typeof ctx.mail.send };");
+    for (auto it = out.at("value").begin(); it != out.at("value").end(); ++it)
+        EXPECT_EQ(it.value(), "function") << it.key() << " is missing from ctx.mail";
+}
+
+TEST(HostPrelude, AMailReadPassesTheConnectionAndTheCriteriaThrough) {
+    const nlohmann::json args = onlyCall(
+        runPrelude("return ctx.mail.read({ host: 'imap.example.com', port: 993,"
+                   "  user: 'u@example.com', passwordSecret: 'MAIL_PASSWORD',"
+                   "  mailbox: 'Archive', limit: 5, timeoutMs: 4000,"
+                   "  criteria: { unseen: true, from: 'boss@example.com' } });"),
+        "mail");
+    EXPECT_EQ(args.at(0), "read");
+    const nlohmann::json& p = args.at(1);
+    EXPECT_EQ(p.at("host"), "imap.example.com");
+    EXPECT_EQ(p.at("port"), 993);
+    EXPECT_EQ(p.at("user"), "u@example.com");
+    EXPECT_EQ(p.at("passwordSecret"), "MAIL_PASSWORD");
+    EXPECT_EQ(p.at("mailbox"), "Archive");
+    EXPECT_EQ(p.at("limit"), 5);
+    EXPECT_EQ(p.at("timeoutMs"), 4000);
+    EXPECT_EQ(p.at("criteria").at("unseen"), true);
+    EXPECT_EQ(p.at("criteria").at("from"), "boss@example.com");
+    // Nothing is invented on the way across: tls is the host's default, not a
+    // value the prelude guesses at, so a changed default cannot be shadowed by
+    // a stale copy here.
+    EXPECT_FALSE(p.contains("tls"));
+}
+
+TEST(HostPrelude, AMailCallRefusesTwoCredentialsRatherThanPickingOne) {
+    // Any rule for reconciling them (literal wins? secret wins?) is a guess at
+    // which of two credentials the author meant to be in force.
+    expectRefused("return ctx.mail.read({ host: 'h', password: 'p',"
+                  "  passwordSecret: 'MAIL_PASSWORD' });",
+                  "ambiguous_body");
+    expectRefused("return ctx.mail.read({ host: 'h', user: 'u', userSecret: 'MAIL_USER' });",
+                  "ambiguous_body");
+}
+
+TEST(HostPrelude, AMailTimeoutIsRefusedRatherThanIgnoredWhenItIsNotAPositiveInteger) {
+    // An option accepted and dropped leaves the author believing a bound is in
+    // force when none is, which is exactly how embedTimeoutMs went unnoticed
+    // for a whole release.
+    expectRefused("return ctx.mail.read({ host: 'h', timeoutMs: 0 });", "validation");
+    expectRefused("return ctx.mail.read({ host: 'h', timeoutMs: -1 });", "validation");
+    expectRefused("return ctx.mail.read({ host: 'h', timeoutMs: 1.5 });", "validation");
+    expectRefused("return ctx.mail.read({ host: 'h', timeoutMs: '4000' });", "validation");
+}
+
+TEST(HostPrelude, AMailReadChecksItsHostLimitMailboxAndPortBeforeTheHostIsReached) {
+    expectRefused("return ctx.mail.read({});", "validation");
+    expectRefused("return ctx.mail.read({ host: '' });", "validation");
+    expectRefused("return ctx.mail.read({ host: 'h', port: 0 });", "validation");
+    expectRefused("return ctx.mail.read({ host: 'h', port: 70000 });", "validation");
+    expectRefused("return ctx.mail.read({ host: 'h', limit: 0 });", "validation");
+    // Refused rather than clamped: a script asking for 5000 is reasoning about
+    // a result set it is not going to get.
+    expectRefused("return ctx.mail.read({ host: 'h', limit: 201 });", "validation");
+    expectRefused("return ctx.mail.read({ host: 'h', mailbox: '' });", "validation");
+    expectRefused("return ctx.mail.read({ host: 'h', tls: 'yes' });", "validation");
+    // A typo'd option is refused by name rather than silently dropped, for the
+    // same reason the write options are.
+    expectRefused("return ctx.mail.read({ host: 'h', mailBox: 'INBOX' });", "validation");
+}
+
+TEST(HostPrelude, MailCriteriaAreCheckedForShapeBeforeTheHostIsReached) {
+    // Only 'ALL' is accepted as a string, because anything else would be raw
+    // IMAP search syntax and this surface never lets a script write protocol.
+    expectRefused("return ctx.mail.read({ host: 'h', criteria: 'UNSEEN' });", "validation");
+    expectRefused("return ctx.mail.read({ host: 'h', criteria: ['UNSEEN'] });", "validation");
+    expectRefused("return ctx.mail.read({ host: 'h', criteria: { sinse: '1-Jan-2026' } });",
+                  "validation");
+    // HEADER is one criterion with two halves; a server answers a half-stated
+    // one with a syntax error rather than with a match.
+    expectRefused("return ctx.mail.read({ host: 'h', criteria: { headerName: 'X-Id' } });",
+                  "validation");
+    const nlohmann::json args = onlyCall(
+        runPrelude("return ctx.mail.read({ host: 'h', criteria: 'ALL' });"), "mail");
+    EXPECT_EQ(args.at(1).at("criteria"), "ALL");
+}
+
+TEST(HostPrelude, AMailSendNormalisesRecipientsAndChecksTheMessageFirst) {
+    const nlohmann::json args = onlyCall(
+        runPrelude("return ctx.mail.send({ host: 'smtp.example.com', port: 587, startTls: true,"
+                   "  user: 'u', passwordSecret: 'MAIL_PASSWORD',"
+                   "  from: 'Sender <s@example.com>', to: 'a@example.com',"
+                   "  cc: ['b@example.com', 'c@example.com'], bcc: 'hidden@example.com',"
+                   "  subject: 'hello', text: 'body',"
+                   "  attachments: [{ filename: 'x.bin', contentType: 'application/octet-stream',"
+                   "                  base64: 'AAEC' }],"
+                   "  headers: { 'X-Trace': 'abc' } });"),
+        "mail");
+    EXPECT_EQ(args.at(0), "send");
+    const nlohmann::json& p = args.at(1);
+    EXPECT_EQ(p.at("startTls"), true);
+    // A single string becomes a list of one, because `to: 'a@b'` is what a
+    // script writes and an array of one is not an improvement.
+    EXPECT_EQ(p.at("to"), nlohmann::json::array({"a@example.com"}));
+    EXPECT_EQ(p.at("bcc"), nlohmann::json::array({"hidden@example.com"}));
+    EXPECT_EQ(p.at("cc").size(), 2u);
+    EXPECT_EQ(p.at("attachments").at(0).at("base64"), "AAEC");
+    EXPECT_EQ(p.at("headers").at("X-Trace"), "abc");
+}
+
+TEST(HostPrelude, AMailSendRefusesAnUnsendableMessageBeforeConnecting) {
+    expectRefused("return ctx.mail.send({ host: 'h', to: 'a@b', text: 'x' });", "validation");
+    expectRefused("return ctx.mail.send({ host: 'h', from: 'a@b', text: 'x' });", "validation");
+    // A message with neither body is a mistake the recipient discovers rather
+    // than the author.
+    expectRefused("return ctx.mail.send({ host: 'h', from: 'a@b', to: 'c@d' });", "validation");
+    expectRefused("return ctx.mail.send({ host: 'h', from: 'a@b', to: [7], text: 'x' });",
+                  "validation");
+    expectRefused("return ctx.mail.send({ host: 'h', from: 'a@b', to: 'c@d', text: 'x',"
+                  "  headers: { 'X-Trace': 7 } });",
+                  "validation");
+    // Base64 is checked here, before the host, so a truncated attachment is a
+    // TypeError the author can read rather than a decode failure reported from
+    // the far side of the boundary.
+    expectRefused("return ctx.mail.send({ host: 'h', from: 'a@b', to: 'c@d', text: 'x',"
+                  "  attachments: [{ filename: 'x', base64: 'AA!' }] });",
+                  "validation");
+    expectRefused("return ctx.mail.send({ host: 'h', from: 'a@b', to: 'c@d', text: 'x',"
+                  "  attachments: [{ base64: 'AAEC' }] });",
+                  "validation");
+    expectRefused("return ctx.mail.send({ host: 'h', from: 'a@b', to: 'c@d', text: 'x',"
+                  "  attachments: [{ filename: 'x', base64: 'AAEC', text: 'y' }] });",
+                  "ambiguous_body");
+}

+ 29 - 0
runner/tests/mail_session_test.cpp

@@ -96,6 +96,35 @@ TEST_F(ImapFixture, SelectUntaggedChatterDoesNotLandInTheCommandsResponse) {
     mailGlobalCleanup();
 }
 
+TEST_F(ImapFixture, CurlConsumesTheClosingParenAndTheTaggedCompletionLine) {
+    // Pinned by EXACT BYTES, because this is where a looser check misled me.
+    // An earlier version of this suite concluded the tagged line DOES arrive,
+    // from a substring search for " OK " - which matched the untagged
+    // "* OK [UIDVALIDITY 1]" line instead. A count cannot lie the same way.
+    //
+    // The consequence is load-bearing: a SUCCESSFUL fetch's raw buffer is
+    // missing the framing the literal announced, so it legitimately parses as
+    // NeedMore, and a caller that read that as "truncated" would reject every
+    // good fetch.
+    ASSERT_EQ(mailGlobalInit(), std::string());
+    server.messageBody = "0123456789";  // 10 bytes, so the arithmetic is obvious
+    ImapSession session;
+    ASSERT_TRUE(session.open(accountFor(server.port()), optionsFor()).ok());
+
+    std::string response;
+    ASSERT_TRUE(session.command("INBOX", "UID FETCH 7 BODY.PEEK[]", response).ok());
+
+    // What the fake sent was: the untagged line, the literal, ")\r\n", then
+    // "A00n OK fetched\r\n". What arrives is the first two and nothing else.
+    const std::string expected = "* 1 FETCH (UID 7 BODY[] {10}\r\n0123456789";
+    EXPECT_EQ(response, expected);
+    EXPECT_EQ(response.find(")\r\n"), std::string::npos) << "the closing paren arrived";
+    // No TAGGED line. A tagged line starts the buffer line with the tag, never
+    // with '*', so this is the precise check rather than a search for " OK ".
+    EXPECT_EQ(response.find("\r\nA"), std::string::npos) << "a tagged line arrived";
+    mailGlobalCleanup();
+}
+
 TEST_F(ImapFixture, TheSessionReusesOneConnectionForSeveralCommands) {
     // One handle per (run, account): a fresh handle per command would mean a
     // TCP connect, a TLS handshake and a LOGIN every time, which is both slow