Bläddra i källkod

feat(mail): the IMAP and SMTP transport, with its pure halves tested

Adds runner_net, a fourth runner library holding libcurl plus the mail
parsers, the budget split and the error map. It is a separate target from
runner_host for one reason: 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 this feature the one part that only
the Docker path can compile. runner_net links neither, so all 203 of its
tests run anywhere.

libcurl is vendored at curl-8_22_0 with an explicit disable list, and the
pin comment records the obligation that comes with vendoring: CVE tracking
is now ours, a statically linked curl is invisible to apt, and a fix means
a rebuild and a republish rather than an upgrade. The reachable protocol
set is exactly imaps/imap/smtps/smtp, so an advisory outside it is not our
exposure. HTTP and PROXY are compiled out: ctx.fetch is cpp-httplib with
its own guard and its own defaults, and curl reads proxy environment
variables where httplib does not, which would silently reroute a
destination the SSRF guard had already approved.

Three facts here were measured rather than assumed, and each is pinned by
a test against an in-process fake server on an ephemeral loopback port:

  - A fetch goes through CUSTOMREQUEST and never curl's ";UID=" URL form,
    because that form always sets \Seen. Undoing it afterwards with a
    STORE is worse than the disease: it removes a flag it may not have
    set, so an already-read message comes back unread, and a timeout
    between the two leaves the message read anyway. A test asserts no
    STORE or FLAGS change ever reaches the wire.
  - SELECT's untagged responses do NOT reach a custom request's write
    callback, but the tagged final line does. A parser written for the
    other answer would silently mis-read every fetch.
  - 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 ".".

An SMTP refusal after DATA arrives as CURLcode 8 with response code 550,
so a server's explicit reply code now wins over curl's generic transport
complaint: otherwise a bad recipient was reported as a protocol fault and
sent the caller looking in the wrong place. Codes that already carry more
meaning than a reply code, such as a denied login, keep their own answer.

Retryability is classified rather than guessed, and it is a parameter
rather than something inferred. A failure is retryable only when nothing
can have happened: DNS and connect failures are, a mailbox read that
times out is, and a send is never retryable past the point where delivery
was possible, because a duplicate cannot be recalled. A rejected login is
not retryable either, since repeating it is how an account gets locked.

Non-ASCII IMAP SEARCH is refused by field name rather than sent. Sending
it is worse than failing: the server matches nothing and zero results
reads as "there is no such mail", which is a silently wrong answer for
accented mail rather than a missing feature.

mime_words is adapted from an existing internal implementation and is now
ours to maintain.
fszontagh 1 månad sedan
förälder
incheckning
20f9e50829

+ 151 - 0
runner/CMakeLists.txt

@@ -60,6 +60,104 @@ else()
 endif()
 FetchContent_MakeAvailable(quickjs)
 
+#
+# libcurl, for the mail surface (IMAP + SMTP). Vendored by default.
+#
+# This is a DECISION, not a default. Linking Debian's libcurl would mean the
+# distro's security team tracks curl CVEs for us and a fix reaches every
+# deployed box through unattended-upgrades without us republishing anything.
+# Vendoring gives that up, and the obligations that come with it are accepted
+# deliberately:
+#
+#   1. CVE TRACKING IS NOW OURS. curl ships security advisories with most
+#      releases, on a roughly 8-week cadence. A statically linked curl inside
+#      our binaries is invisible to `apt` and to the distro's tooling, so a
+#      vulnerable version sits on a customer box until somebody here notices.
+#      A fix means a rebuild AND a republish of both binaries, not an apt
+#      upgrade. Review at every curl release.
+#   2. The pin is reviewed against WHAT THIS SERVICE ACTUALLY REACHES, not
+#      against an advisory's severity score - the same discipline the
+#      cpp-httplib pin uses, and the discipline that correctly ruled curl's
+#      HTTP/3, proxy, NTLM and Kerberos surface out of scope here, because the
+#      disable list below compiles all of it out.
+#   3. The reachable protocol set is exactly: imaps, imap, smtps, smtp. An
+#      advisory in any other protocol is not our exposure.
+#
+# curl-8_22_0 was released 2 Sep 2026; the next release is due 14 Oct 2026.
+# curl's git tags are underscored, which is why this does not read 8.22.0.
+#
+# SFTP is deliberately NOT in the surface, which is what keeps this to ONE
+# vendored upstream: SFTP would require libssh2 as well, and libssh2 is far
+# less watched than curl while having had remotely reachable issues.
+set(SVAPI_CURL_TAG "curl-8_22_0" CACHE STRING "curl git tag to vendor")
+option(SVAPI_VENDOR_CURL "Vendor libcurl rather than linking the system one" ON)
+
+if(SVAPI_VENDOR_CURL)
+    # The disable list IS the attack surface of the pin, so it is explicit
+    # rather than inherited from curl's defaults.
+    set(BUILD_CURL_EXE OFF CACHE BOOL "" FORCE)        # the library, not the tool
+    set(CURL_DISABLE_INSTALL ON CACHE BOOL "" FORCE)   # curl must not land in our .deb
+    set(ENABLE_CURL_MANUAL OFF CACHE BOOL "" FORCE)
+    set(CURL_USE_OPENSSL ON CACHE BOOL "" FORCE)       # the TLS backend everything else here uses
+    set(CURL_USE_LIBSSH2 OFF CACHE BOOL "" FORCE)      # no SFTP, so no second upstream to track
+    set(CURL_USE_LIBSSH OFF CACHE BOOL "" FORCE)
+    set(CURL_USE_LIBPSL OFF CACHE BOOL "" FORCE)       # a cookie-domain concern; we have no cookies
+    set(CURL_USE_GSSAPI OFF CACHE BOOL "" FORCE)
+    set(CURL_ENABLE_SSL ON CACHE BOOL "" FORCE)
+    set(ENABLE_THREADED_RESOLVER ON CACHE BOOL "" FORCE)
+    set(USE_NGHTTP2 OFF CACHE BOOL "" FORCE)
+    set(USE_NGTCP2 OFF CACHE BOOL "" FORCE)
+    set(USE_QUICHE OFF CACHE BOOL "" FORCE)
+    set(CURL_DISABLE_NTLM ON CACHE BOOL "" FORCE)
+    # HTTP is compiled OUT on purpose. ctx.fetch is cpp-httplib, with its own
+    # SSRF guard, its own address pinning and its own outbound defaults; two
+    # HTTP clients with two sets of defaults is exactly how the two drift.
+    # Consequence, recorded rather than discovered later: WebDAV/CalDAV are
+    # HTTP and are therefore NOT in this slice. Re-enabling HTTP here also
+    # brings redirects back, which would then need REDIR_PROTOCOLS_STR set
+    # separately and FOLLOWLOCATION off.
+    set(CURL_DISABLE_HTTP ON CACHE BOOL "" FORCE)
+    # PROXY is compiled out rather than disabled per handle. curl reads
+    # *_proxy and ALL_PROXY from the environment by default, and runner.env is
+    # a file an operator edits; a proxy variable nobody intended to apply to
+    # mail would silently reroute a destination the SSRF guard had already
+    # approved, defeating the address pinning. Compiling it out cannot be
+    # undone by a later patch that forgets to set CURLOPT_PROXY.
+    set(CURL_DISABLE_PROXY ON CACHE BOOL "" FORCE)
+    # NETRC off: credentials come from project secrets and nowhere else, never
+    # from a file on disk.
+    set(CURL_DISABLE_NETRC ON CACHE BOOL "" FORCE)
+    # Each of these is persistent cross-request state, which is precisely what
+    # a multi-tenant pool must not accumulate. Removing the feature beats
+    # scrubbing it between tenants.
+    set(CURL_DISABLE_COOKIES ON CACHE BOOL "" FORCE)
+    set(CURL_DISABLE_ALTSVC ON CACHE BOOL "" FORCE)
+    set(CURL_DISABLE_HSTS ON CACHE BOOL "" FORCE)
+    foreach(_proto FILE DICT GOPHER LDAP LDAPS MQTT RTSP SMB TELNET TFTP WEBSOCKETS POP3 FTP)
+        set(CURL_DISABLE_${_proto} ON CACHE BOOL "" FORCE)
+    endforeach()
+
+    if(CMAKE_VERSION VERSION_GREATER_EQUAL 3.28)
+        FetchContent_Declare(curl
+            GIT_REPOSITORY https://github.com/curl/curl.git
+            GIT_TAG        ${SVAPI_CURL_TAG}
+            GIT_SHALLOW    TRUE
+            EXCLUDE_FROM_ALL)
+    else()
+        FetchContent_Declare(curl
+            GIT_REPOSITORY https://github.com/curl/curl.git
+            GIT_TAG        ${SVAPI_CURL_TAG}
+            GIT_SHALLOW    TRUE)
+    endif()
+    FetchContent_MakeAvailable(curl)
+    set(SVAPI_CURL_TARGET CURL::libcurl)
+else()
+    # The escape hatch, and what the dev loop uses: a system libcurl builds in
+    # seconds where the vendored one takes minutes. It is NOT what ships.
+    find_package(CURL REQUIRED)
+    set(SVAPI_CURL_TARGET CURL::libcurl)
+endif()
+
 # Found by the root project already; the guard is what makes this directory
 # usable on its own.
 if(NOT TARGET nlohmann_json::nlohmann_json)
@@ -100,6 +198,38 @@ target_link_libraries(runner_protocol PUBLIC
 target_compile_features(runner_protocol PUBLIC cxx_std_20)
 set_target_properties(runner_protocol PROPERTIES POSITION_INDEPENDENT_CODE ON)
 
+# The protocol host: libcurl plus the mail parsers, the budget split and the
+# error map. A FOURTH library rather than part of runner_host, and the reason
+# is testability: runner_host links vectorapi_core and the database client and
+# therefore cannot be built on the dev host, so putting the IMAP and MIME code
+# there would make the largest and most defect-prone piece of this feature the
+# one piece only the Docker path can compile. That is backwards. runner_net
+# links neither, so its tests run anywhere.
+#
+# The division of labour at the runner_host boundary is strict: runner_host
+# converts JS values to a plain request struct and converts a plain result
+# struct back, and does nothing else. No curl call, no IMAP knowledge and no
+# timeout arithmetic above that line.
+add_library(runner_net STATIC
+    src/net/imap_commands.cpp
+    src/net/imap_fetch.cpp
+    src/net/mime_build.cpp
+    src/net/curl_errors.cpp
+    src/net/mail_session.cpp
+    ${SVAPI_SRC_DIR}/functions/mime_words.cpp)
+target_include_directories(runner_net PUBLIC
+    ${CMAKE_CURRENT_SOURCE_DIR}/src
+    ${SVAPI_SRC_DIR})
+if(NOT TARGET spdlog::spdlog)
+    find_package(spdlog REQUIRED)
+endif()
+# curl is PUBLIC rather than PRIVATE only because the transport TEST includes
+# curl/curl.h to name CURLcode values; nothing above runner_net touches curl.
+target_link_libraries(runner_net PUBLIC
+    nlohmann_json::nlohmann_json spdlog::spdlog Threads::Threads ${SVAPI_CURL_TARGET})
+target_compile_features(runner_net PUBLIC cxx_std_20)
+set_target_properties(runner_net PROPERTIES POSITION_INDEPENDENT_CODE ON)
+
 if(BUILD_TESTS)
     # Same find-then-fetch dance as tests/CMakeLists.txt, guarded so that
     # wiring this directory into the root project does not fetch twice.
@@ -172,6 +302,27 @@ if(BUILD_TESTS)
         tests/runner_auth_test.cpp)
     target_link_libraries(test_runner_env_auth PRIVATE runner_protocol GTest::gtest_main)
     gtest_discover_tests(test_runner_env_auth)
+
+    # The mail surface's pure halves: command construction (the injection
+    # boundary), response interpretation, message assembly, the budget split
+    # and the error map. All of it runs with no network, which is the whole
+    # reason runner_net is a separate target.
+    add_executable(test_mail_pure
+        tests/imap_commands_test.cpp
+        tests/imap_fetch_test.cpp
+        tests/mime_build_test.cpp
+        tests/mail_net_test.cpp)
+    target_link_libraries(test_mail_pure PRIVATE runner_net GTest::gtest_main)
+    gtest_discover_tests(test_mail_pure PROPERTIES TIMEOUT 120)
+
+    # The transport, driven against in-process fake IMAP and SMTP servers on
+    # ephemeral loopback ports. Not a mock of curl: real curl, real sockets,
+    # which is the only way the facts about what curl puts on the wire stay
+    # true rather than becoming assumptions.
+    add_executable(test_mail_session tests/mail_session_test.cpp)
+    target_include_directories(test_mail_session PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/tests)
+    target_link_libraries(test_mail_session PRIVATE runner_net GTest::gtest_main)
+    gtest_discover_tests(test_mail_session PROPERTIES TIMEOUT 120)
 endif()
 
 # The host bindings: the ctx.* surface. A SEPARATE target from runner_core

+ 188 - 0
runner/src/net/curl_errors.cpp

@@ -0,0 +1,188 @@
+#include "net/curl_errors.hpp"
+
+#include <curl/curl.h>
+
+namespace svapi::runner::net {
+namespace {
+
+/// The curl error buffer when it has something, the code's own name otherwise.
+/// curl's buffer names the host and the TLS reason; the enum name does not, and
+/// "could not connect" without the address is an unactionable answer.
+std::string detailOr(std::string_view curlMessage, const char* fallback) {
+    std::string out(curlMessage);
+    while (!out.empty() && (out.back() == '\n' || out.back() == '\r' || out.back() == ' '))
+        out.pop_back();
+    return out.empty() ? std::string(fallback) : out;
+}
+
+MailFailure make(int status, const char* slug, std::string message, bool retryable) {
+    MailFailure f;
+    f.status = status;
+    f.slug = slug;
+    f.message = std::move(message);
+    f.retryable = retryable;
+    return f;
+}
+
+} // namespace
+
+MailFailure mailFailureFor(int curlCode, long responseCode, std::string_view curlMessage,
+                           bool sideEffecting) {
+    if (curlCode == CURLE_OK) {
+        // curl succeeded at the transport level, but a mail server reports a
+        // refusal in the reply CODE while the transfer itself is fine. A 2xx
+        // (or no code at all, for a command curl does not score) is the only
+        // real success.
+        if (responseCode >= 400) return mailFailureForReplyCode(responseCode, curlMessage);
+        return MailFailure{};
+    }
+
+    // MEASURED: an SMTP server refusing a message after DATA produces
+    // CURLcode 8 (CURLE_WEIRD_SERVER_REPLY) with CURLINFO_RESPONSE_CODE set to
+    // 550. curl's code says only "I did not understand that reply"; the 550
+    // says which of the many refusals it was. So for the codes that are merely
+    // curl's generic transport complaint, a reply code the server actually sent
+    // WINS - otherwise a bad recipient is reported as a protocol fault and the
+    // caller goes looking in the wrong place.
+    //
+    // The specific codes below are NOT overridden, because they already carry
+    // more meaning than the reply code does: a 535 with CURLE_LOGIN_DENIED is
+    // an auth failure, not a generic "permanent refusal".
+    if (responseCode >= 400) {
+        switch (curlCode) {
+            case CURLE_WEIRD_SERVER_REPLY:
+            case CURLE_UPLOAD_FAILED:
+            case CURLE_SEND_ERROR:
+            case CURLE_RECV_ERROR:
+            case CURLE_GOT_NOTHING:
+            case CURLE_PARTIAL_FILE:
+                return mailFailureForReplyCode(responseCode, curlMessage);
+            default:
+                break;
+        }
+    }
+
+    switch (curlCode) {
+        case CURLE_URL_MALFORMAT:
+        case CURLE_UNSUPPORTED_PROTOCOL:
+            // Ours or the script's mistake, not the server's, and no amount of
+            // retrying changes it.
+            return make(422, "mail_bad_url", detailOr(curlMessage, "malformed mail URL"), false);
+
+        case CURLE_COULDNT_RESOLVE_HOST:
+        case CURLE_COULDNT_RESOLVE_PROXY:
+            // Retryable: DNS failures are frequently transient, and nothing
+            // reached the server, so nothing can have happened.
+            return make(502, "mail_unresolvable",
+                        detailOr(curlMessage, "could not resolve the mail host"), true);
+
+        case CURLE_COULDNT_CONNECT:
+            return make(502, "mail_unreachable",
+                        detailOr(curlMessage, "could not connect to the mail host"), true);
+
+        case CURLE_OPERATION_TIMEDOUT:
+            // 504 rather than 503, for the reason the database deadline case
+            // records: 503 means "retry as-is", and for anything side-effecting
+            // that is dangerous advice. A read may retry; a send may not.
+            return make(504, "mail_timeout",
+                        detailOr(curlMessage, "the mail server did not answer in time"),
+                        !sideEffecting);
+
+        case CURLE_PEER_FAILED_VERIFICATION:
+        case CURLE_SSL_CACERT_BADFILE:
+        case CURLE_SSL_ISSUER_ERROR:
+        case CURLE_SSL_PINNEDPUBKEYNOTMATCH:
+            // NEVER retryable and never downgraded. A certificate that does not
+            // verify is the one failure where carrying on is worse than
+            // failing, because the credentials are about to go over that
+            // connection. Its own slug so it cannot be mistaken for a network
+            // blip in a log.
+            return make(502, "mail_tls_untrusted",
+                        detailOr(curlMessage, "the mail server's certificate did not verify"),
+                        false);
+
+        case CURLE_SSL_CONNECT_ERROR:
+        case CURLE_USE_SSL_FAILED:
+            return make(502, "mail_tls_failed",
+                        detailOr(curlMessage, "the TLS handshake with the mail server failed"),
+                        false);
+
+        case CURLE_LOGIN_DENIED:
+            // Deliberately NOT retryable, even though a 4xx-ish auth refusal
+            // can be transient. Repeating a rejected login is how an account
+            // gets locked out or an IP gets blocked, and that failure is far
+            // more expensive and far longer-lived than the one being retried.
+            return make(502, "mail_auth_failed",
+                        detailOr(curlMessage, "the mail server rejected the credentials"), false);
+
+        case CURLE_REMOTE_ACCESS_DENIED:
+            return make(502, "mail_access_denied",
+                        detailOr(curlMessage, "the mail server denied access to that mailbox"),
+                        false);
+
+        case CURLE_WEIRD_SERVER_REPLY:
+        case CURLE_BAD_CONTENT_ENCODING:
+            return make(502, "mail_protocol_error",
+                        detailOr(curlMessage, "the mail server sent a reply we could not parse"),
+                        false);
+
+        case CURLE_ABORTED_BY_CALLBACK:
+            // Our own progress callback stopped this, so the reason is one we
+            // already know. The caller substitutes the specific answer
+            // (deadline or too large); this is the fallback if it does not.
+            return make(504, "mail_aborted",
+                        detailOr(curlMessage, "the mail transfer was stopped by its own budget"),
+                        false);
+
+        case CURLE_FILESIZE_EXCEEDED:
+            return make(413, "mail_too_large",
+                        detailOr(curlMessage, "the mail transfer exceeded the size this run may load"),
+                        false);
+
+        case CURLE_SEND_ERROR:
+        case CURLE_RECV_ERROR:
+        case CURLE_GOT_NOTHING:
+        case CURLE_PARTIAL_FILE:
+            // The socket broke mid-conversation. For a read that is safe to
+            // repeat; for a send this is exactly the "delivered then
+            // unanswered" case, where the message may already be accepted and
+            // a retry would send it twice.
+            return make(502, "mail_connection_lost",
+                        detailOr(curlMessage, "the connection to the mail server was lost"),
+                        !sideEffecting);
+
+        case CURLE_OUT_OF_MEMORY:
+            return make(503, "mail_out_of_memory", detailOr(curlMessage, "out of memory"), false);
+
+        default:
+            // An unmapped code is reported as ours rather than guessed at. 502
+            // with the curl text is honest and still actionable, and a guessed
+            // 422 would tell a caller to fix a payload that may be fine.
+            return make(502, "mail_error",
+                        detailOr(curlMessage, "the mail operation failed"), false);
+    }
+}
+
+MailFailure mailFailureForReplyCode(long responseCode, std::string_view detail) {
+    if (responseCode > 0 && responseCode < 400) return MailFailure{};
+
+    std::string message = detailOr(detail, "the mail server refused the command");
+    message += " (server replied " + std::to_string(responseCode) + ")";
+
+    if (responseCode >= 400 && responseCode < 500)
+        // The protocol's own definition of transient: try again later. The one
+        // case where the code alone settles retryability.
+        return make(503, "mail_server_busy", std::move(message), true);
+
+    if (responseCode >= 500)
+        // Permanent by the protocol's definition. 422 rather than 502, because
+        // a 550 is overwhelmingly the caller's fault - a bad recipient, a
+        // rejected sender, a message over the server's size limit - and
+        // telling them the server is broken sends them looking in the wrong
+        // place. The reply text is passed through so they can see which.
+        return make(422, "mail_rejected", std::move(message), false);
+
+    return make(502, "mail_error", std::move(message), false);
+}
+
+} // namespace svapi::runner::net

+ 57 - 0
runner/src/net/curl_errors.hpp

@@ -0,0 +1,57 @@
+#pragma once
+#include <string>
+#include <string_view>
+
+/// Turning a libcurl outcome into an answer a function author can act on.
+///
+/// Deliberately NOT svapi::ApiError: runner_net must not depend on the server's
+/// error type, so this carries the same three things (status, slug, message)
+/// plus the one thing a mail failure needs and an HTTP one does not - whether
+/// retrying is safe. The host layer converts.
+///
+/// The classification rule throughout: a failure is `retryable` only when we
+/// know NOTHING happened. That is the same three-way reasoning RunnerPool uses
+/// for a function run, and it matters more here, because the side effect at
+/// stake is a sent e-mail. "Delivered then unanswered" is not retryable.
+namespace svapi::runner::net {
+
+struct MailFailure {
+    /// 0 means success.
+    int status = 0;
+    std::string slug;
+    std::string message;
+    /// True only when the operation provably did not happen.
+    bool retryable = false;
+
+    bool ok() const { return status == 0; }
+};
+
+/// Classify a finished curl transfer.
+///
+/// `responseCode` is CURLINFO_RESPONSE_CODE: the last protocol reply code (an
+/// SMTP or IMAP one, so 250/550/451, not an HTTP one), or 0 if there was none.
+/// `curlMessage` is the error buffer, which is far more specific than the
+/// CURLcode's own name and is worth surfacing.
+///
+/// `curlCode` is taken as an int rather than a CURLcode so that callers and
+/// tests need no curl header to use this; the values are curl's.
+///
+/// `sideEffecting` is the caller saying whether this operation changes anything
+/// at the far end. It is a PARAMETER rather than something inferred, for the
+/// same reason the run kind is a parameter to RunService::run: inferring it
+/// means getting it wrong silently. A mailbox read is not side-effecting, so a
+/// timeout or a dropped socket is safe to retry. A send IS, so the moment the
+/// conversation could have reached the point of delivery, nothing about it is
+/// retryable - a duplicate e-mail cannot be recalled.
+MailFailure mailFailureFor(int curlCode, long responseCode, std::string_view curlMessage,
+                           bool sideEffecting);
+
+/// Classify a protocol reply code on its own, for a command whose reply we read
+/// ourselves rather than letting curl drive it.
+///
+/// 4xx is transient by the SMTP definition (try again later) and 5xx is
+/// permanent (do not), which is the one case where a code alone is enough to
+/// decide retryability.
+MailFailure mailFailureForReplyCode(long responseCode, std::string_view detail);
+
+} // namespace svapi::runner::net

+ 608 - 0
runner/src/net/imap_commands.cpp

@@ -0,0 +1,608 @@
+#include "imap_commands.hpp"
+
+#include <algorithm>
+#include <array>
+#include <utility>
+
+namespace svapi::runner::net {
+namespace {
+
+constexpr char kB64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+,";
+
+/// RFC 3501 atom-specials, plus CTL and SP. `]` is in there via resp-specials,
+/// which is easy to miss and would let a value ending in `]` close a
+/// body-part bracket it was never inside.
+bool isAtomChar(unsigned char c) {
+    if (c <= 0x1f || c == 0x7f) return false;   // CTL
+    if (c >= 0x80) return false;                // 8-bit needs a literal
+    switch (c) {
+        case ' ':
+        case '(':
+        case ')':
+        case '{':
+        case '%':
+        case '*':
+        case '"':
+        case '\\':
+        case ']':
+            return false;
+        default:
+            return true;
+    }
+}
+
+bool isControlOrEightBit(unsigned char c) { return c <= 0x1f || c == 0x7f || c >= 0x80; }
+
+void requireAtomOnly(std::string_view value, std::string_view field) {
+    if (value.empty()) throw ImapCommandError(std::string(field), "must not be empty");
+    for (const char c : value)
+        if (!isAtomChar(static_cast<unsigned char>(c)))
+            throw ImapCommandError(std::string(field), "contains a character that is not allowed here");
+}
+
+/// Decode one UTF-8 scalar, refusing the forms that are not the shortest one.
+/// An overlong encoding of `&` would otherwise slip a shift character past the
+/// direct-encoding test and land inside a base64 run.
+size_t utf8Next(std::string_view s, size_t at, uint32_t& cp, std::string_view field) {
+    const auto bad = [&]() -> size_t {
+        throw ImapCommandError(std::string(field), "is not valid UTF-8");
+    };
+    const unsigned char b0 = static_cast<unsigned char>(s[at]);
+    size_t len = 0;
+    uint32_t v = 0;
+    if (b0 < 0x80) { cp = b0; return 1; }
+    if ((b0 & 0xe0) == 0xc0) { len = 2; v = b0 & 0x1fu; }
+    else if ((b0 & 0xf0) == 0xe0) { len = 3; v = b0 & 0x0fu; }
+    else if ((b0 & 0xf8) == 0xf0) { len = 4; v = b0 & 0x07u; }
+    else return bad();
+    if (at + len > s.size()) return bad();
+    for (size_t i = 1; i < len; ++i) {
+        const unsigned char b = static_cast<unsigned char>(s[at + i]);
+        if ((b & 0xc0) != 0x80) return bad();
+        v = (v << 6) | (b & 0x3fu);
+    }
+    if (len == 2 && v < 0x80) return bad();
+    if (len == 3 && v < 0x800) return bad();
+    if (len == 4 && v < 0x10000) return bad();
+    if (v > 0x10ffff) return bad();
+    if (v >= 0xd800 && v <= 0xdfff) return bad();   // a lone surrogate is never a scalar
+    cp = v;
+    return len;
+}
+
+void utf8Append(std::string& out, uint32_t cp) {
+    if (cp < 0x80) {
+        out += static_cast<char>(cp);
+    } else if (cp < 0x800) {
+        out += static_cast<char>(0xc0 | (cp >> 6));
+        out += static_cast<char>(0x80 | (cp & 0x3f));
+    } else if (cp < 0x10000) {
+        out += static_cast<char>(0xe0 | (cp >> 12));
+        out += static_cast<char>(0x80 | ((cp >> 6) & 0x3f));
+        out += static_cast<char>(0x80 | (cp & 0x3f));
+    } else {
+        out += static_cast<char>(0xf0 | (cp >> 18));
+        out += static_cast<char>(0x80 | ((cp >> 12) & 0x3f));
+        out += static_cast<char>(0x80 | ((cp >> 6) & 0x3f));
+        out += static_cast<char>(0x80 | (cp & 0x3f));
+    }
+}
+
+/// Modified base64 of a UTF-16BE byte run, no padding.
+void appendShifted(std::string& out, const std::string& utf16be) {
+    size_t i = 0;
+    while (i + 3 <= utf16be.size()) {
+        const uint32_t n = (static_cast<unsigned char>(utf16be[i]) << 16) |
+                           (static_cast<unsigned char>(utf16be[i + 1]) << 8) |
+                           static_cast<unsigned char>(utf16be[i + 2]);
+        out += kB64[(n >> 18) & 0x3f];
+        out += kB64[(n >> 12) & 0x3f];
+        out += kB64[(n >> 6) & 0x3f];
+        out += kB64[n & 0x3f];
+        i += 3;
+    }
+    const size_t rest = utf16be.size() - i;
+    if (rest == 1) {
+        const uint32_t n = static_cast<unsigned char>(utf16be[i]) << 16;
+        out += kB64[(n >> 18) & 0x3f];
+        out += kB64[(n >> 12) & 0x3f];
+    } else if (rest == 2) {
+        const uint32_t n = (static_cast<unsigned char>(utf16be[i]) << 16) |
+                           (static_cast<unsigned char>(utf16be[i + 1]) << 8);
+        out += kB64[(n >> 18) & 0x3f];
+        out += kB64[(n >> 12) & 0x3f];
+        out += kB64[(n >> 6) & 0x3f];
+    }
+}
+
+int b64Value(char c) {
+    for (int i = 0; i < 64; ++i)
+        if (kB64[i] == c) return i;
+    return -1;
+}
+
+bool hasEightBit(std::string_view s) {
+    return std::any_of(s.begin(), s.end(),
+                       [](char c) { return static_cast<unsigned char>(c) >= 0x80; });
+}
+
+/// `d-MMM-yyyy`. The month is matched against the fixed English list IMAP
+/// defines; a locale-dependent month name would make the same criteria produce
+/// different commands on different hosts.
+void requireImapDate(std::string_view v, std::string_view field) {
+    static constexpr std::array<const char*, 12> kMonths = {
+        "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
+    const auto bad = [&]() {
+        throw ImapCommandError(std::string(field), "must be an IMAP date like 1-Jan-2026");
+    };
+    const size_t d1 = v.find('-');
+    if (d1 == std::string_view::npos) bad();
+    const size_t d2 = v.find('-', d1 + 1);
+    if (d2 == std::string_view::npos) bad();
+    const std::string_view day = v.substr(0, d1);
+    const std::string_view mon = v.substr(d1 + 1, d2 - d1 - 1);
+    const std::string_view year = v.substr(d2 + 1);
+    if (day.empty() || day.size() > 2 || year.size() != 4) bad();
+    for (const char c : day)
+        if (c < '0' || c > '9') bad();
+    for (const char c : year)
+        if (c < '0' || c > '9') bad();
+    if (std::find_if(kMonths.begin(), kMonths.end(),
+                     [&](const char* m) { return mon == m; }) == kMonths.end())
+        bad();
+}
+
+/// Accumulates a command, starting a new chunk wherever a literal forces the
+/// client to wait for a continuation.
+class Writer {
+public:
+    Writer(std::string_view tag, std::string_view verb) {
+        requireAtomOnly(tag, "tag");
+        requireAtomOnly(verb, "verb");
+        cmd_.tag = std::string(tag);
+        cur_ = std::string(tag) + " " + std::string(verb);
+    }
+
+    /// Protocol text we produced ourselves - a keyword, a UID set, a body-part
+    /// specifier that has already been validated. Never caller text.
+    void raw(std::string_view text) {
+        cur_ += ' ';
+        cur_ += text;
+    }
+
+    void arg(const ImapArg& a) {
+        cur_ += ' ';
+        cur_ += a.head;
+        if (a.isLiteral()) {
+            // The `{n}\r\n` is already in `head`, so the chunk ends here and
+            // the octets open the next one.
+            cmd_.chunks.push_back(cur_);
+            cur_ = a.payload;
+        }
+    }
+
+    ImapCommand finish() {
+        cur_ += "\r\n";
+        cmd_.chunks.push_back(cur_);
+        return std::move(cmd_);
+    }
+
+private:
+    ImapCommand cmd_;
+    std::string cur_;
+};
+
+/// A mailbox name as it must reach the wire: refused if it carries an injection
+/// byte, then modified UTF-7, then encoded. Order matters - encoding first
+/// would hide a CR inside a base64 run where the refusal could not see it.
+ImapArg mailboxArg(std::string_view utf8, std::string_view field) {
+    imapRejectControlBytes(utf8, field);
+    return imapEncodeArg(toModifiedUtf7(utf8, field), field);
+}
+
+/// ⚠ A non-ASCII SEARCH term is REFUSED, never sent.
+///
+/// Measured against a live server: a term carrying 8-bit bytes cannot be
+/// expressed on the one-shot command path this layer serves. Doing it properly
+/// needs `SEARCH CHARSET UTF-8` with the term as an octet-counted literal,
+/// which is a multi-step exchange with a `+` continuation that the transport
+/// below us does not drive. Sending the raw octets anyway is worse than
+/// failing: the server either rejects the command or matches nothing, and zero
+/// results is indistinguishable from "there is no such mail". That exact
+/// shortcut shipped elsewhere and produced silently wrong answers against
+/// Hungarian mail, which is the case this surface exists for.
+///
+/// Not stripped, not transliterated: "Beerkezett" is a different search from
+/// "Beérkezett" and quietly substituting one for the other is the same silent
+/// wrong answer wearing a different hat. Mailbox NAMES are a separate question
+/// and do go out encoded, as modified UTF-7.
+void requireAsciiSearchTerm(std::string_view value, std::string_view field) {
+    if (!hasEightBit(value)) return;
+    throw ImapCommandError(
+        std::string(field),
+        "cannot contain non-ASCII characters: an accented IMAP search needs a literal "
+        "continuation this client does not drive, and sending it unannounced would match "
+        "nothing while looking like an empty mailbox. Filter on an ASCII-safe criterion "
+        "instead (sender, date, or an ASCII substring) and match the accented text after "
+        "fetching.");
+}
+
+/// A search term: refused for control bytes and for non-ASCII, then encoded
+/// as-is. Never modified UTF-7 - that applies to mailbox NAMES only, and
+/// encoding a term would search for the ampersand sequences rather than the
+/// text.
+void addTerm(Writer& w, const char* keyword, std::string_view value, std::string_view field) {
+    imapRejectControlBytes(value, field);
+    requireAsciiSearchTerm(value, field);
+    if (*keyword != '\0') w.raw(keyword);
+    w.arg(imapEncodeArg(value, field));
+}
+
+} // namespace
+
+std::string ImapCommand::joined() const {
+    std::string out;
+    for (const auto& c : chunks) out += c;
+    return out;
+}
+
+// --- Tags -----------------------------------------------------------------
+
+ImapTagger::ImapTagger(char prefix) : prefix_(prefix) {
+    if (!isAtomChar(static_cast<unsigned char>(prefix)) || (prefix >= '0' && prefix <= '9'))
+        throw ImapCommandError("tag prefix", "must be a letter usable in an atom");
+}
+
+std::string ImapTagger::next() {
+    ++issued_;
+    std::string n = std::to_string(issued_);
+    // Zero-padded to three digits, the conventional "A001" width, for
+    // readability in a protocol trace - but NOT truncated to three: past 999
+    // the tag simply gets longer, because a wrapped tag is an ambiguous tag.
+    if (n.size() < 3) n.insert(0, 3 - n.size(), '0');
+    return std::string(1, prefix_) + n;
+}
+
+// --- Argument encoding ----------------------------------------------------
+
+bool imapNeedsLiteral(std::string_view value) {
+    return std::any_of(value.begin(), value.end(), [](char c) {
+        return isControlOrEightBit(static_cast<unsigned char>(c));
+    });
+}
+
+std::string imapQuote(std::string_view value, std::string_view field) {
+    if (imapNeedsLiteral(value))
+        throw ImapCommandError(std::string(field),
+                               "contains a byte that cannot appear in a quoted string");
+    std::string out;
+    out.reserve(value.size() + 2);
+    out += '"';
+    for (const char c : value) {
+        // Both escapes, always. Escaping only the quote would let a trailing
+        // backslash escape the closing quote and run the rest of the value as
+        // protocol - the classic quote-break.
+        if (c == '\\' || c == '"') out += '\\';
+        out += c;
+    }
+    out += '"';
+    return out;
+}
+
+ImapArg imapEncodeArg(std::string_view value, std::string_view field) {
+    ImapArg a;
+    if (imapNeedsLiteral(value)) {
+        a.form = ImapArgForm::Literal;
+        // The count is in OCTETS, not characters. A name of six accented
+        // letters is twelve octets in UTF-8, and a count of six would leave the
+        // server reading the rest of the name as the next command - which is an
+        // injection primitive, not merely a parse error.
+        a.payload = std::string(value);
+        a.head = "{" + std::to_string(a.payload.size()) + "}\r\n";
+        return a;
+    }
+    const bool atomSafe =
+        !value.empty() && std::all_of(value.begin(), value.end(), [](char c) {
+            return isAtomChar(static_cast<unsigned char>(c));
+        });
+    if (atomSafe) {
+        a.form = ImapArgForm::Atom;
+        a.head = std::string(value);
+        return a;
+    }
+    a.form = ImapArgForm::Quoted;
+    a.head = imapQuote(value, field);
+    return a;
+}
+
+void imapRejectControlBytes(std::string_view value, std::string_view field) {
+    for (const char c : value) {
+        if (c == '\r')
+            throw ImapCommandError(std::string(field), "must not contain a carriage return");
+        if (c == '\n')
+            throw ImapCommandError(std::string(field), "must not contain a line feed");
+        if (c == '\0')
+            throw ImapCommandError(std::string(field), "must not contain a NUL byte");
+    }
+}
+
+// --- Modified UTF-7 -------------------------------------------------------
+
+std::string toModifiedUtf7(std::string_view utf8, std::string_view field) {
+    std::string out;
+    std::string pending;   // UTF-16BE bytes of the current shifted run
+    const auto flush = [&]() {
+        if (pending.empty()) return;
+        out += '&';
+        appendShifted(out, pending);
+        out += '-';
+        pending.clear();
+    };
+    size_t at = 0;
+    while (at < utf8.size()) {
+        uint32_t cp = 0;
+        at += utf8Next(utf8, at, cp, field);
+        if (cp >= 0x20 && cp <= 0x7e) {
+            flush();
+            // The one printable ASCII character that cannot stand for itself,
+            // since it is the shift.
+            if (cp == '&') out += "&-";
+            else out += static_cast<char>(cp);
+            continue;
+        }
+        if (cp < 0x10000) {
+            pending += static_cast<char>((cp >> 8) & 0xff);
+            pending += static_cast<char>(cp & 0xff);
+        } else {
+            const uint32_t v = cp - 0x10000;
+            const uint32_t hi = 0xd800 + (v >> 10);
+            const uint32_t lo = 0xdc00 + (v & 0x3ff);
+            pending += static_cast<char>((hi >> 8) & 0xff);
+            pending += static_cast<char>(hi & 0xff);
+            pending += static_cast<char>((lo >> 8) & 0xff);
+            pending += static_cast<char>(lo & 0xff);
+        }
+    }
+    flush();
+    return out;
+}
+
+std::string fromModifiedUtf7(std::string_view encoded, std::string_view field) {
+    const auto bad = [&](const char* why) { throw ImapCommandError(std::string(field), why); };
+    std::string out;
+    size_t at = 0;
+    while (at < encoded.size()) {
+        const char c = encoded[at];
+        if (c != '&') {
+            if (isControlOrEightBit(static_cast<unsigned char>(c)))
+                bad("contains a byte that is not legal in modified UTF-7");
+            out += c;
+            ++at;
+            continue;
+        }
+        ++at;
+        if (at < encoded.size() && encoded[at] == '-') { out += '&'; ++at; continue; }
+        // Collect the base64 run. An unterminated run is refused rather than
+        // decoded to the end of the string: a name that is missing its shift
+        // terminator is a name we do not actually know.
+        const size_t start = at;
+        while (at < encoded.size() && b64Value(encoded[at]) >= 0) ++at;
+        if (at >= encoded.size() || encoded[at] != '-') bad("has an unterminated &-sequence");
+        const std::string_view run = encoded.substr(start, at - start);
+        ++at;
+        if (run.empty()) bad("has an empty &-sequence");
+        if (run.size() % 4 == 1) bad("has a base64 run of an impossible length");
+
+        std::string bytes;
+        uint32_t acc = 0;
+        int bits = 0;
+        for (const char rc : run) {
+            acc = (acc << 6) | static_cast<uint32_t>(b64Value(rc));
+            bits += 6;
+            if (bits >= 8) {
+                bits -= 8;
+                bytes += static_cast<char>((acc >> bits) & 0xff);
+            }
+        }
+        // Leftover bits must be zero. Non-zero leftovers mean two different
+        // encodings would decode to the same name, and a name that is not
+        // canonical cannot be used as a key.
+        if (bits > 0 && (acc & ((1u << bits) - 1)) != 0) bad("has non-zero trailing base64 bits");
+        if (bytes.size() % 2 != 0) bad("has an odd number of UTF-16 octets");
+
+        for (size_t i = 0; i < bytes.size(); i += 2) {
+            uint32_t u = (static_cast<unsigned char>(bytes[i]) << 8) |
+                         static_cast<unsigned char>(bytes[i + 1]);
+            if (u >= 0xd800 && u <= 0xdbff) {
+                if (i + 4 > bytes.size()) bad("ends inside a surrogate pair");
+                const uint32_t lo = (static_cast<unsigned char>(bytes[i + 2]) << 8) |
+                                    static_cast<unsigned char>(bytes[i + 3]);
+                if (lo < 0xdc00 || lo > 0xdfff) bad("has an unpaired high surrogate");
+                u = 0x10000 + ((u - 0xd800) << 10) + (lo - 0xdc00);
+                i += 2;
+            } else if (u >= 0xdc00 && u <= 0xdfff) {
+                bad("has an unpaired low surrogate");
+            }
+            utf8Append(out, u);
+        }
+    }
+    return out;
+}
+
+// --- Command builders -----------------------------------------------------
+
+ImapCommand imapBuildCommand(std::string_view tag, std::string_view verb,
+                             const std::vector<ImapArg>& args) {
+    Writer w(tag, verb);
+    for (const auto& a : args) w.arg(a);
+    return w.finish();
+}
+
+ImapCommand imapCapability(std::string_view tag) { return imapBuildCommand(tag, "CAPABILITY", {}); }
+
+ImapCommand imapLogin(std::string_view tag, std::string_view user, std::string_view password) {
+    imapRejectControlBytes(user, "user");
+    imapRejectControlBytes(password, "password");
+    return imapBuildCommand(tag, "LOGIN",
+                            {imapEncodeArg(user, "user"), imapEncodeArg(password, "password")});
+}
+
+ImapCommand imapSelect(std::string_view tag, std::string_view mailboxUtf8) {
+    return imapBuildCommand(tag, "SELECT", {mailboxArg(mailboxUtf8, "mailbox")});
+}
+
+ImapCommand imapExamine(std::string_view tag, std::string_view mailboxUtf8) {
+    return imapBuildCommand(tag, "EXAMINE", {mailboxArg(mailboxUtf8, "mailbox")});
+}
+
+ImapCommand imapList(std::string_view tag, std::string_view referenceUtf8,
+                     std::string_view patternUtf8) {
+    return imapBuildCommand(tag, "LIST",
+                            {mailboxArg(referenceUtf8, "reference"),
+                             mailboxArg(patternUtf8, "pattern")});
+}
+
+ImapCommand imapUidSearch(std::string_view tag, const ImapSearchCriteria& c) {
+    if (c.headerName.has_value() != c.headerValue.has_value())
+        throw ImapCommandError("header", "needs both a name and a value");
+    if (c.headerName) requireAtomOnly(*c.headerName, "headerName");
+
+    // Validate every term BEFORE emitting anything, so which field is named in
+    // the refusal depends on the criteria and not on the emission order.
+    const std::pair<const std::optional<std::string>*, const char*> terms[] = {
+        {&c.from, "from"},   {&c.to, "to"},     {&c.subject, "subject"},
+        {&c.text, "text"},   {&c.body, "body"}, {&c.headerValue, "headerValue"},
+    };
+    for (const auto& [slot, field] : terms) {
+        if (!slot->has_value()) continue;
+        imapRejectControlBytes(**slot, field);
+        requireAsciiSearchTerm(**slot, field);
+    }
+
+    Writer w(tag, "UID");
+    w.raw("SEARCH");
+
+    bool any = false;
+    const auto mark = [&]() { any = true; };
+    if (c.since) { requireImapDate(*c.since, "since"); w.raw("SINCE"); w.raw(*c.since); mark(); }
+    if (c.before) { requireImapDate(*c.before, "before"); w.raw("BEFORE"); w.raw(*c.before); mark(); }
+    if (c.unseen) { w.raw("UNSEEN"); mark(); }
+    if (c.seen) { w.raw("SEEN"); mark(); }
+    if (c.flagged) { w.raw("FLAGGED"); mark(); }
+    if (c.largerThanBytes) { w.raw("LARGER"); w.raw(std::to_string(*c.largerThanBytes)); mark(); }
+    if (c.smallerThanBytes) { w.raw("SMALLER"); w.raw(std::to_string(*c.smallerThanBytes)); mark(); }
+    if (c.from) { addTerm(w, "FROM", *c.from, "from"); mark(); }
+    if (c.to) { addTerm(w, "TO", *c.to, "to"); mark(); }
+    if (c.subject) { addTerm(w, "SUBJECT", *c.subject, "subject"); mark(); }
+    if (c.text) { addTerm(w, "TEXT", *c.text, "text"); mark(); }
+    if (c.body) { addTerm(w, "BODY", *c.body, "body"); mark(); }
+    if (c.headerName) {
+        w.raw("HEADER");
+        w.raw(*c.headerName);
+        addTerm(w, "", *c.headerValue, "headerValue");
+        mark();
+    }
+    // With nothing to match, say so. A bare `UID SEARCH` is a syntax error, and
+    // "no criteria" plainly means every message.
+    if (!any) w.raw("ALL");
+    return w.finish();
+}
+
+std::string imapFormatUidSet(const std::vector<ImapUidRange>& ranges) {
+    if (ranges.empty()) throw ImapCommandError("uids", "must not be empty");
+    std::vector<uint64_t> flat;
+    for (const auto& r : ranges) {
+        if (r.low == 0 || r.high == 0) throw ImapCommandError("uids", "must all be 1 or greater");
+        if (r.high < r.low) throw ImapCommandError("uids", "has a range that ends before it starts");
+        // Expanding is bounded in practice because a FETCH set comes from a
+        // SEARCH result; a range wide enough to matter is refused outright
+        // rather than silently turned into millions of entries.
+        if (r.high - r.low > 65535)
+            throw ImapCommandError("uids", "has a range wider than 65536 UIDs");
+        for (uint64_t u = r.low; u <= r.high; ++u) flat.push_back(u);
+    }
+    return imapFormatUidSet(flat);
+}
+
+std::string imapFormatUidSet(const std::vector<uint64_t>& uids) {
+    if (uids.empty()) throw ImapCommandError("uids", "must not be empty");
+    std::vector<uint64_t> v = uids;
+    std::sort(v.begin(), v.end());
+    v.erase(std::unique(v.begin(), v.end()), v.end());
+    if (v.front() == 0) throw ImapCommandError("uids", "must all be 1 or greater");
+
+    std::string out;
+    size_t i = 0;
+    while (i < v.size()) {
+        size_t j = i;
+        while (j + 1 < v.size() && v[j + 1] == v[j] + 1) ++j;
+        if (!out.empty()) out += ',';
+        out += std::to_string(v[i]);
+        // Only collapse a run of three or more: `4:5` is no shorter than `4,5`
+        // and a reader has to stop and check whether the range is inclusive.
+        if (j > i + 1) {
+            out += ':';
+            out += std::to_string(v[j]);
+        } else if (j == i + 1) {
+            out += ',';
+            out += std::to_string(v[j]);
+        }
+        i = j + 1;
+    }
+    return out;
+}
+
+void imapValidateBodyPart(std::string_view spec) {
+    if (spec.empty()) throw ImapCommandError("bodyPart", "must not be empty");
+    for (const char c : spec) {
+        const unsigned char u = static_cast<unsigned char>(c);
+        const bool ok = (u >= 'A' && u <= 'Z') || (u >= 'a' && u <= 'z') || (u >= '0' && u <= '9') ||
+                        c == '.' || c == '[' || c == ']' || c == '<' || c == '>' || c == '(' ||
+                        c == ')' || c == ' ';
+        if (!ok)
+            throw ImapCommandError("bodyPart",
+                                   "may only contain letters, digits and . [ ] < > ( ) and space");
+    }
+    // Brackets are part of the FETCH item we wrap this in, so an unbalanced one
+    // here would close ours early and leave the remainder as protocol.
+    int depth = 0;
+    for (const char c : spec) {
+        if (c == '[') ++depth;
+        if (c == ']') --depth;
+        if (depth < 0) throw ImapCommandError("bodyPart", "has an unbalanced bracket");
+    }
+    if (depth != 0) throw ImapCommandError("bodyPart", "has an unbalanced bracket");
+    depth = 0;
+    for (const char c : spec) {
+        if (c == '(') ++depth;
+        if (c == ')') --depth;
+        if (depth < 0) throw ImapCommandError("bodyPart", "has an unbalanced parenthesis");
+    }
+    if (depth != 0) throw ImapCommandError("bodyPart", "has an unbalanced parenthesis");
+}
+
+namespace {
+ImapCommand uidFetchWith(std::string_view tag, const std::string& set, std::string_view bodyPart) {
+    imapValidateBodyPart(bodyPart);
+    Writer w(tag, "UID");
+    w.raw("FETCH");
+    w.raw(set);
+    // PEEK, always. See the header: the unpeeked form sets \Seen.
+    w.raw("(UID FLAGS INTERNALDATE RFC822.SIZE BODY.PEEK[" + std::string(bodyPart) + "])");
+    return w.finish();
+}
+} // namespace
+
+ImapCommand imapUidFetch(std::string_view tag, const std::vector<uint64_t>& uids,
+                         std::string_view bodyPart) {
+    return uidFetchWith(tag, imapFormatUidSet(uids), bodyPart);
+}
+
+ImapCommand imapUidFetch(std::string_view tag, const std::vector<ImapUidRange>& ranges,
+                         std::string_view bodyPart) {
+    return uidFetchWith(tag, imapFormatUidSet(ranges), bodyPart);
+}
+
+ImapCommand imapLogout(std::string_view tag) { return imapBuildCommand(tag, "LOGOUT", {}); }
+
+} // namespace svapi::runner::net

+ 290 - 0
runner/src/net/imap_commands.hpp

@@ -0,0 +1,290 @@
+#pragma once
+#include <cstddef>
+#include <cstdint>
+#include <optional>
+#include <stdexcept>
+#include <string>
+#include <string_view>
+#include <vector>
+
+/// Building IMAP client commands.
+///
+/// ⚠ THIS IS THE INJECTION BOUNDARY. Mailbox names, search terms, body-part
+/// specifiers and UIDs all arrive from a tenant's JavaScript. IMAP is a
+/// line-oriented protocol in which CRLF ends a command, so a mailbox named
+/// `INBOX"\r\nA001 LOGOUT` is not a mailbox name - it is two commands, and the
+/// second one is the attacker's. There is no parser between us and the server
+/// to catch that: whatever bytes we write ARE the protocol.
+///
+/// The defence is two-layered, and the order matters:
+///
+///   1. REFUSE, do not sanitise. A name carrying CR, LF or NUL is rejected by
+///      name with an error naming the field. Stripping the bytes instead would
+///      silently rewrite the tenant's request into a different one, and the
+///      next person to read the code cannot tell a stripped value from a value
+///      that never had the byte - so the bug comes back the moment someone
+///      "optimises" the strip away.
+///   2. ENCODE what survives, per RFC 3501 section 4.3: atom, quoted string or
+///      octet-counted literal, chosen by what the value actually contains.
+///
+/// A literal is deliberately visible in the API (`ImapCommand::chunks`) rather
+/// than hidden inside a returned string, because a literal is not a longer
+/// command - it is a different exchange. The client must stop after the
+/// `{n}\r\n` and wait for the server's `+` continuation before sending the
+/// octets. A caller that concatenated the chunks and wrote them in one go would
+/// work against every permissive server and deadlock against a strict one,
+/// which is the kind of bug that only appears in production.
+///
+/// Pure and standard-library only: no sockets, no curl, no settings, no
+/// server-layer error types. Every awkward case here is testable without a mail
+/// server, and that is the point.
+namespace svapi::runner::net {
+
+/// Why a command could not be built. Local to this layer on purpose: this file
+/// must not depend on the server's error types, so the caller that owns an HTTP
+/// status decides what one of these maps to.
+class ImapCommandError : public std::invalid_argument {
+public:
+    ImapCommandError(std::string field, const std::string& why)
+        : std::invalid_argument(field + ": " + why), field_(std::move(field)) {}
+
+    /// Which argument was refused, so the message handed to a script names the
+    /// thing the script author can actually change.
+    const std::string& field() const { return field_; }
+
+private:
+    std::string field_;
+};
+
+/// How one argument is written on the wire.
+enum class ImapArgForm {
+    Atom,     ///< bare, no delimiters: the value contains nothing special
+    Quoted,   ///< "..." with \\ and \" escaped; 7-bit, no CR or LF
+    Literal,  ///< {n}\r\n then exactly n octets, after a `+` continuation
+};
+
+/// One encoded argument.
+struct ImapArg {
+    ImapArgForm form = ImapArgForm::Atom;
+    /// What goes on the command line. For a literal this is only the `{n}`
+    /// header, including its CRLF - the octets follow in `payload`.
+    std::string head;
+    /// A literal's octets, exactly `n` of them. Empty for the other forms.
+    std::string payload;
+
+    bool isLiteral() const { return form == ImapArgForm::Literal; }
+};
+
+/// A complete command, split at every point where the client must wait.
+///
+/// `chunks[0]` is written first. Before writing each later chunk the client
+/// MUST have read a `+` continuation response. The last chunk ends with CRLF;
+/// every chunk before it ends with the `{n}\r\n` that asked for the
+/// continuation.
+struct ImapCommand {
+    std::string tag;
+    std::vector<std::string> chunks;
+
+    /// True when this command is a multi-step exchange. A client that ignores
+    /// this will send literal octets the server has not yet agreed to read.
+    bool needsContinuation() const { return chunks.size() > 1; }
+
+    /// Every chunk back to back. For tests and logging ONLY - writing this to a
+    /// socket is exactly the mistake `chunks` exists to prevent.
+    std::string joined() const;
+};
+
+// --- Tags -----------------------------------------------------------------
+
+/// Hands out command tags for one session.
+///
+/// A response is matched to its command by tag and nothing else, so a tag
+/// reused inside a session makes two commands indistinguishable - and the
+/// failure mode is not an error but a silently wrong answer attributed to the
+/// wrong command. Hence monotonic and never reset; a new session gets a new
+/// tagger, not a rewound one.
+class ImapTagger {
+public:
+    explicit ImapTagger(char prefix = 'A');
+
+    /// The next tag, e.g. "A001". Keeps growing past "A9999" rather than
+    /// wrapping, because wrapping is precisely the reuse this prevents.
+    std::string next();
+
+    /// How many tags have been handed out. A client can assert this against the
+    /// number of commands it sent.
+    uint64_t issued() const { return issued_; }
+
+private:
+    char prefix_;
+    uint64_t issued_ = 0;
+};
+
+// --- Argument encoding (RFC 3501 section 4.3) ------------------------------
+
+/// True when `value` cannot be written as a quoted string and needs a literal:
+/// it holds CR, LF, NUL, any other control byte, or an 8-bit byte. RFC 3501's
+/// QUOTED-CHAR is 7-bit and excludes CR and LF outright.
+bool imapNeedsLiteral(std::string_view value);
+
+/// `value` as a quoted string, with `\` and `"` escaped.
+///
+/// Throws `ImapCommandError` when the value cannot legally be quoted, rather
+/// than producing a string that happens to parse as something else. This is the
+/// primitive the escape-attempt tests aim at: a trailing backslash must not be
+/// able to swallow the closing quote.
+std::string imapQuote(std::string_view value, std::string_view field = "value");
+
+/// Pick the narrowest legal form for `value` and encode it.
+///
+/// An empty value is emitted as `""`, not as `{0}`: both are legal, and the
+/// quoted form costs no continuation round trip. What matters is that it is
+/// never emitted as a bare atom, which would shift every following argument one
+/// position left.
+ImapArg imapEncodeArg(std::string_view value, std::string_view field = "value");
+
+/// Refuse a value that may not reach the wire at all.
+///
+/// CR, LF and NUL are the command-injection bytes; they are refused for every
+/// caller-supplied string even though a literal could technically carry them,
+/// because nothing a mailbox read needs contains one and accepting them would
+/// mean the only thing standing between a tenant and an injected command is the
+/// encoder choosing the right form. Throws `ImapCommandError`.
+void imapRejectControlBytes(std::string_view value, std::string_view field);
+
+// --- Modified UTF-7 mailbox names (RFC 3501 section 5.1.3) -----------------
+
+/// UTF-8 in, modified UTF-7 out.
+///
+/// The IMAP variant of UTF-7: `&` is the shift character where UTF-7 uses `+`,
+/// the base64 alphabet's last character is `,` instead of `/` (so a mailbox
+/// name can never contain the hierarchy delimiter by accident), padding `=` is
+/// omitted, and a literal `&` is written `&-`.
+///
+/// Throws `ImapCommandError` on invalid UTF-8 - fail closed. A truncated
+/// sequence is the tail of something, and guessing which something is how a
+/// name turns into a different name.
+std::string toModifiedUtf7(std::string_view utf8, std::string_view field = "mailbox");
+
+/// Modified UTF-7 in, UTF-8 out. Throws `ImapCommandError` on anything that is
+/// not well-formed: an unterminated shift, a base64 run of an impossible
+/// length, non-zero leftover bits, an odd octet count, or an unpaired
+/// surrogate. Strict because this decodes a mailbox name that will be shown to
+/// a user and used as a key.
+std::string fromModifiedUtf7(std::string_view encoded, std::string_view field = "mailbox");
+
+// --- Command builders -----------------------------------------------------
+
+/// Assemble `tag VERB arg arg ...` CRLF from already-encoded arguments.
+///
+/// Exposed because it is where the chunk splitting lives, and chunk splitting
+/// is worth testing directly rather than only through the commands that use it.
+/// `verb` and `tag` are checked to be atoms; they are ours, not a tenant's, but
+/// an unchecked tag would be a free injection point the day one is derived from
+/// input.
+ImapCommand imapBuildCommand(std::string_view tag, std::string_view verb,
+                             const std::vector<ImapArg>& args);
+
+ImapCommand imapCapability(std::string_view tag);
+
+/// Credentials are arguments like any other, so they get the same encoding -
+/// an 8-bit password becomes a literal rather than being mangled into one.
+ImapCommand imapLogin(std::string_view tag, std::string_view user, std::string_view password);
+
+/// SELECT opens a mailbox read-write. Prefer `imapExamine` for a read.
+ImapCommand imapSelect(std::string_view tag, std::string_view mailboxUtf8);
+
+/// EXAMINE is SELECT without the write access, and the difference is not
+/// cosmetic: a FETCH in a SELECTed mailbox sets \Seen, so a read-only mail
+/// surface that used SELECT would silently mark a customer's unread mail as
+/// read. Reads use this.
+ImapCommand imapExamine(std::string_view tag, std::string_view mailboxUtf8);
+
+/// LIST. `reference` is usually empty and `pattern` usually `*` or `%`; both
+/// are encoded, which is why a pattern gets quoted - `*` and `%` are
+/// atom-specials.
+ImapCommand imapList(std::string_view tag, std::string_view referenceUtf8,
+                     std::string_view patternUtf8);
+
+/// The common UID SEARCH criteria. Only fields that are set are emitted, in a
+/// fixed order, so the same criteria always produce the same bytes - a command
+/// whose text depends on map iteration order cannot be asserted on.
+struct ImapSearchCriteria {
+    /// `d-MMM-yyyy`, e.g. `1-Jan-2026`. Validated against that shape; a date
+    /// is the one criterion where a free-form string buys nothing.
+    std::optional<std::string> since;
+    std::optional<std::string> before;
+    std::optional<std::string> from;
+    std::optional<std::string> to;
+    std::optional<std::string> subject;
+    /// TEXT searches headers and body; BODY only the body.
+    std::optional<std::string> text;
+    std::optional<std::string> body;
+    /// HEADER needs both halves or neither.
+    std::optional<std::string> headerName;
+    std::optional<std::string> headerValue;
+    bool unseen = false;
+    bool seen = false;
+    bool flagged = false;
+    std::optional<uint64_t> largerThanBytes;
+    std::optional<uint64_t> smallerThanBytes;
+};
+
+/// UID SEARCH, so the results are UIDs and stay valid across sessions -
+/// sequence numbers renumber when a message is expunged, which makes any
+/// two-step read racy.
+///
+/// ⚠ A criterion value carrying non-ASCII bytes is REFUSED by name, not sent.
+/// An accented term needs `SEARCH CHARSET UTF-8` with the term as an
+/// octet-counted literal, which is a multi-step exchange this one-shot command
+/// path cannot drive; sending the octets unannounced makes the server either
+/// reject the command or match nothing, and zero hits looks exactly like an
+/// empty mailbox. The error says to filter on an ASCII-safe criterion and match
+/// the accented text after fetching. Measured on a live server, after the
+/// optimistic version shipped elsewhere and gave silently wrong answers against
+/// Hungarian mail.
+///
+/// With no criteria at all the command is `UID SEARCH ALL`: an empty criteria
+/// list must never become a bare `UID SEARCH`, which is a syntax error.
+ImapCommand imapUidSearch(std::string_view tag, const ImapSearchCriteria& criteria);
+
+/// An inclusive UID range. `high` may equal `low` for a single UID.
+struct ImapUidRange {
+    uint64_t low = 0;
+    uint64_t high = 0;
+};
+
+/// Format a UID set, e.g. `3,7:9,12`.
+///
+/// UIDs are taken as integers and never as strings, which removes the entire
+/// question of what a hostile UID could contain. Sorted, de-duplicated and
+/// coalesced into ranges so one FETCH of many messages stays a short command.
+/// Throws on an empty set or a zero UID - IMAP UIDs start at 1, so a 0 means
+/// the caller lost a value somewhere.
+std::string imapFormatUidSet(const std::vector<uint64_t>& uids);
+std::string imapFormatUidSet(const std::vector<ImapUidRange>& ranges);
+
+/// A FETCH body-part specifier such as `HEADER`, `TEXT`, `1.2`, or
+/// `HEADER.FIELDS (FROM SUBJECT DATE)`.
+///
+/// This one goes out as raw protocol, not as an encoded argument: the brackets,
+/// parentheses and dots ARE the syntax, so quoting it would change its meaning.
+/// That makes it the sharpest input here, and it is therefore restricted to a
+/// character allowlist - letters, digits, `. [ ] < > ( )`, space - rather than
+/// a blocklist. Throws on anything else.
+void imapValidateBodyPart(std::string_view spec);
+
+/// UID FETCH of UID, FLAGS, INTERNALDATE, RFC822.SIZE and one body part.
+///
+/// `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. The peek form is the only one a read surface may use, and the
+/// difference is invisible in a test that does not assert the exact bytes.
+ImapCommand imapUidFetch(std::string_view tag, const std::vector<uint64_t>& uids,
+                         std::string_view bodyPart);
+ImapCommand imapUidFetch(std::string_view tag, const std::vector<ImapUidRange>& ranges,
+                         std::string_view bodyPart);
+
+ImapCommand imapLogout(std::string_view tag);
+
+} // namespace svapi::runner::net

+ 853 - 0
runner/src/net/imap_fetch.cpp

@@ -0,0 +1,853 @@
+#include "net/imap_fetch.hpp"
+
+#include <algorithm>
+#include <cctype>
+#include <cstdlib>
+#include <tuple>
+
+#include "functions/mime_words.hpp"
+
+namespace svapi::runner::net {
+
+using svapi::functions::ImapReader;
+using svapi::functions::ImapToken;
+using svapi::functions::MimeWords;
+
+namespace {
+
+std::string upper(std::string s) {
+    for (char& c : s) c = static_cast<char>(std::toupper(static_cast<unsigned char>(c)));
+    return s;
+}
+
+std::string lower(std::string s) {
+    for (char& c : s) c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
+    return s;
+}
+
+bool equalsIgnoreCase(const std::string& a, const char* b) { return upper(a) == b; }
+
+/// A value's text, or empty when it is NIL or a list. NIL collapsing to empty
+/// is intentional and is why the structs carry `has*` flags for the numbers:
+/// for a string field "absent" and "empty" mean the same thing to every caller,
+/// but for a size they do not.
+std::string textOf(const ImapValue* v) {
+    return (v != nullptr && v->isText()) ? v->text : std::string();
+}
+
+std::optional<uint64_t> numberOf(const ImapValue* v) {
+    if (v == nullptr || !v->isText() || v->text.empty()) return std::nullopt;
+    uint64_t n = 0;
+    for (const char c : v->text) {
+        if (c < '0' || c > '9') return std::nullopt;
+        // Clamp rather than wrap: a hostile RFC822.SIZE must not become a small
+        // number that a caller then trusts as a buffer size.
+        if (n > (UINT64_MAX - 9) / 10) return std::nullopt;
+        n = n * 10 + static_cast<uint64_t>(c - '0');
+    }
+    return n;
+}
+
+// ---------------------------------------------------------------------------
+// Tokens -> values
+// ---------------------------------------------------------------------------
+
+/// Re-join an atom that the tokenizer split because a FETCH section name may
+/// contain spaces and parentheses: `BODY[HEADER.FIELDS (SUBJECT FROM)]` is ONE
+/// item name, but `[` and `]` are not IMAP delimiters so the tokenizer sees an
+/// atom, a list, and a stray `]`. The item name is the key a caller looks the
+/// returned bytes up by, so leaving it in pieces loses the data entirely.
+///
+/// Only an atom containing `[` with no `]` can start a merge, and the merge
+/// happens only when a closing `]` is actually present later in the line -
+/// otherwise a truncated or hostile line would swallow the whole response.
+std::vector<ImapToken> rejoinSections(const std::vector<ImapToken>& in) {
+    std::vector<ImapToken> out;
+    out.reserve(in.size());
+    for (size_t i = 0; i < in.size(); ++i) {
+        const ImapToken& t = in[i];
+        const bool starts = t.kind == ImapToken::Kind::Atom &&
+                            t.text.find('[') != std::string::npos &&
+                            t.text.find(']') == std::string::npos;
+        if (!starts) {
+            out.push_back(t);
+            continue;
+        }
+        size_t end = in.size();
+        for (size_t j = i + 1; j < in.size(); ++j) {
+            if (in[j].text.find(']') != std::string::npos) {
+                end = j;
+                break;
+            }
+        }
+        if (end == in.size()) {
+            out.push_back(t);
+            continue;
+        }
+        std::string joined = t.text;
+        for (size_t j = i + 1; j <= end; ++j) {
+            const ImapToken& p = in[j];
+            const bool isList = p.kind == ImapToken::Kind::ListOpen ||
+                                p.kind == ImapToken::Kind::ListClose;
+            const bool quoted = p.kind == ImapToken::Kind::Quoted ||
+                                p.kind == ImapToken::Kind::Literal;
+            // A space is re-inserted only where the original had one: not after
+            // `(` or `[`, and not before `)` or the closing `]`. Getting this
+            // wrong yields a section key one space different from the one a
+            // caller looks up, which loses the data exactly as a split name
+            // would - silently.
+            const bool closes = isList ? p.text == ")" : p.text.rfind(']', 0) == 0;
+            const char back = joined.empty() ? '\0' : joined.back();
+            if (!joined.empty() && back != '(' && back != '[' && !closes) joined += ' ';
+            if (quoted) {
+                joined += '"';
+                joined += p.text;
+                joined += '"';
+            } else {
+                joined += p.text;
+            }
+        }
+        out.push_back({ImapToken::Kind::Atom, std::move(joined)});
+        i = end;
+    }
+    return out;
+}
+
+/// Recursive descent, bounded by `maxDepth` - which is what makes the recursion
+/// safe. Without the bound a server can reach a stack overflow with nothing but
+/// open parentheses, and a stack overflow in the runner is not a parse error,
+/// it is the process.
+ImapParse buildSeq(const std::vector<ImapToken>& t, size_t& i, std::vector<ImapValue>& out,
+                   bool inList, size_t depth, size_t maxDepth) {
+    while (i < t.size()) {
+        switch (t[i].kind) {
+            case ImapToken::Kind::ListClose:
+                if (!inList) return ImapParse::Malformed;  // a close with nothing open
+                ++i;
+                return ImapParse::Ok;
+            case ImapToken::Kind::ListOpen: {
+                if (depth + 1 > maxDepth) return ImapParse::Malformed;
+                ++i;
+                ImapValue v;
+                v.kind = ImapValue::Kind::List;
+                const ImapParse r = buildSeq(t, i, v.items, true, depth + 1, maxDepth);
+                if (r != ImapParse::Ok) return r;
+                out.push_back(std::move(v));
+                break;
+            }
+            case ImapToken::Kind::Nil: {
+                ImapValue v;
+                v.kind = ImapValue::Kind::Nil;
+                out.push_back(std::move(v));
+                ++i;
+                break;
+            }
+            case ImapToken::Kind::Atom: {
+                ImapValue v;
+                v.kind = ImapValue::Kind::Atom;
+                v.text = t[i].text;
+                out.push_back(std::move(v));
+                ++i;
+                break;
+            }
+            case ImapToken::Kind::Quoted:
+            case ImapToken::Kind::Literal: {
+                ImapValue v;
+                v.kind = ImapValue::Kind::String;
+                v.text = t[i].text;
+                out.push_back(std::move(v));
+                ++i;
+                break;
+            }
+        }
+    }
+    // Tokens ran out with a list still open. The reader already confirmed the
+    // CRLF arrived, so this is not truncation - it is a response that cannot be
+    // completed by reading further.
+    return inList ? ImapParse::Malformed : ImapParse::Ok;
+}
+
+/// Walk every complete response line in `bytes`, handing each line's top-level
+/// values to `fn`. Stops at the first line that is truncated or malformed.
+///
+/// The read position is tracked here rather than via `ImapReader::consumed()`,
+/// because a reader that returned NeedMore has already advanced past the start
+/// of the line it could not finish, and resuming from there would re-enter the
+/// stream mid-literal.
+template <typename F>
+ImapParse eachLine(std::string_view bytes, size_t& consumed, size_t maxDepth, F&& fn) {
+    // Nothing at all is NeedMore, never Ok: an empty buffer is a caller that
+    // has not read yet, and answering Ok would let it treat "no response" as
+    // "an empty response" - which for a FETCH reads as "the message has no
+    // body".
+    if (bytes.empty()) return ImapParse::NeedMore;
+    size_t pos = 0;
+    while (pos < bytes.size()) {
+        ImapReader rd(bytes.substr(pos));
+        std::vector<ImapToken> toks;
+        const ImapParse r = rd.readLine(toks);
+        if (r != ImapParse::Ok) {
+            consumed = pos;
+            return r;
+        }
+        const std::vector<ImapToken> joined = rejoinSections(toks);
+        std::vector<ImapValue> values;
+        size_t i = 0;
+        const ImapParse b = buildSeq(joined, i, values, false, 0, maxDepth);
+        if (b != ImapParse::Ok) {
+            consumed = pos;
+            return b;
+        }
+        pos += rd.consumed();
+        fn(values);
+    }
+    consumed = pos;
+    return ImapParse::Ok;
+}
+
+// ---------------------------------------------------------------------------
+// MIME parameters, RFC 2231
+// ---------------------------------------------------------------------------
+
+std::map<std::string, std::string> paramsFromValue(const ImapValue* v) {
+    std::map<std::string, std::string> out;
+    if (v == nullptr || !v->isList()) return out;
+    for (size_t i = 0; i + 1 < v->items.size(); i += 2) {
+        const std::string key = lower(textOf(&v->items[i]));
+        if (key.empty()) continue;
+        out[key] = textOf(&v->items[i + 1]);
+    }
+    return out;
+}
+
+int hexDigit(char c) {
+    if (c >= '0' && c <= '9') return c - '0';
+    if (c >= 'a' && c <= 'f') return c - 'a' + 10;
+    if (c >= 'A' && c <= 'F') return c - 'A' + 10;
+    return -1;
+}
+
+/// Percent-decoding for an RFC 2231 extended value. A malformed escape is kept
+/// verbatim rather than dropped, on the same principle as MimeWords::decode: a
+/// filename that survives as gibberish beats one that vanishes.
+std::string percentDecode(const std::string& in) {
+    std::string out;
+    out.reserve(in.size());
+    for (size_t i = 0; i < in.size(); ++i) {
+        if (in[i] == '%' && i + 2 < in.size()) {
+            const int hi = hexDigit(in[i + 1]);
+            const int lo = hexDigit(in[i + 2]);
+            if (hi >= 0 && lo >= 0) {
+                out += static_cast<char>(hi * 16 + lo);
+                i += 2;
+                continue;
+            }
+        }
+        out += in[i];
+    }
+    return out;
+}
+
+/// Collapse one logical MIME parameter out of the wire parameters.
+///
+/// Three spellings reach us for the same thing and all three are real traffic:
+///   filename="rajz.pdf"                         plain
+///   filename*=UTF-8''%C3%A1rajz.pdf             RFC 2231 extended
+///   filename*0*=UTF-8''%C3%A1; filename*1*=.pdf RFC 2231 split
+///   filename="=?UTF-8?Q?=C3=A1rajz.pdf?="       RFC 2047 in a place it does
+///                                               not belong, but widely sent
+///
+/// Segments are ordered NUMERICALLY, not by key: `filename*10*` sorts before
+/// `filename*2*` as a string, which silently scrambles a long filename.
+///
+/// The extended form names its own charset. We percent-decode and then run the
+/// value through RFC 2047 decoding, which covers the common UTF-8 and the
+/// mis-encoded case; a value in some other charset keeps its bytes, which is
+/// why `rawOut` is handed back for every caller that has to write a file.
+std::string collapseParam(const std::map<std::string, std::string>& params,
+                          const std::string& base, std::string& rawOut) {
+    rawOut.clear();
+    std::vector<std::tuple<long, bool, std::string>> segs;
+    bool sawSegment = false;
+    for (const auto& [key, value] : params) {
+        if (key.rfind(base, 0) != 0 || key.size() == base.size()) continue;
+        if (key[base.size()] != '*') continue;
+        std::string rest = key.substr(base.size() + 1);
+        bool ext = false;
+        if (!rest.empty() && rest.back() == '*') {
+            ext = true;
+            rest.pop_back();
+        }
+        long idx = 0;
+        if (!rest.empty()) {
+            if (rest.find_first_not_of("0123456789") != std::string::npos) continue;
+            idx = std::strtol(rest.c_str(), nullptr, 10);
+        } else if (!ext) {
+            continue;  // `base*` with neither index nor extended marker
+        }
+        segs.emplace_back(idx, ext, value);
+        sawSegment = true;
+    }
+    if (!sawSegment) {
+        const auto it = params.find(base);
+        if (it == params.end()) return std::string();
+        rawOut = it->second;
+        return MimeWords::decode(rawOut);
+    }
+    std::sort(segs.begin(), segs.end(), [](const auto& a, const auto& b) {
+        return std::get<0>(a) < std::get<0>(b);
+    });
+    std::string decoded;
+    bool first = true;
+    for (const auto& [idx, ext, value] : segs) {
+        (void)idx;
+        rawOut += value;
+        std::string piece = value;
+        if (ext) {
+            if (first) {
+                // charset'language'value - both fields may be empty, and the
+                // value itself may legitimately contain apostrophes, so only
+                // the first two are stripped.
+                const size_t a = piece.find('\'');
+                if (a != std::string::npos) {
+                    const size_t b = piece.find('\'', a + 1);
+                    if (b != std::string::npos) piece = piece.substr(b + 1);
+                }
+            }
+            piece = percentDecode(piece);
+        }
+        decoded += piece;
+        first = false;
+    }
+    return MimeWords::decode(decoded);
+}
+
+// ---------------------------------------------------------------------------
+// BODYSTRUCTURE
+// ---------------------------------------------------------------------------
+
+void applyDisposition(ImapBodyPart& p, const ImapValue* dsp) {
+    if (dsp == nullptr || !dsp->isList()) return;
+    p.disposition = upper(textOf(dsp->at(0)));
+    p.dispositionParams = paramsFromValue(dsp->at(1));
+}
+
+ImapBodyPart buildPart(const ImapValue& v, size_t depth);
+
+ImapBodyPart buildMultipart(const ImapValue& v, size_t depth) {
+    ImapBodyPart p;
+    p.multipart = true;
+    p.type = "MULTIPART";
+    size_t i = 0;
+    while (const ImapValue* child = v.at(i)) {
+        if (!child->isList()) break;
+        p.children.push_back(buildPart(*child, depth + 1));
+        ++i;
+    }
+    p.subtype = upper(textOf(v.at(i)));
+    ++i;
+    // body-ext-mpart: param list, then disposition. Absent on a server that
+    // answers BODY rather than BODYSTRUCTURE, which is why nothing here may
+    // require it.
+    p.params = paramsFromValue(v.at(i));
+    applyDisposition(p, v.at(i + 1));
+    return p;
+}
+
+ImapBodyPart buildPart(const ImapValue& v, size_t depth) {
+    ImapBodyPart p;
+    if (!v.isList()) return p;
+    if (depth > kMaxSexpDepth) return p;  // belt and braces; buildSeq already capped
+    if (const ImapValue* first = v.at(0); first != nullptr && first->isList())
+        return buildMultipart(v, depth);
+
+    p.type = upper(textOf(v.at(0)));
+    p.subtype = upper(textOf(v.at(1)));
+    p.params = paramsFromValue(v.at(2));
+    p.contentId = textOf(v.at(3));
+    p.description = MimeWords::decode(textOf(v.at(4)));
+    p.encoding = upper(textOf(v.at(5)));
+    if (const auto n = numberOf(v.at(6))) {
+        p.octets = *n;
+        p.hasOctets = true;
+    }
+
+    size_t ext = 7;
+    if (p.type == "TEXT") {
+        if (const auto n = numberOf(v.at(7))) {
+            p.lines = *n;
+            p.hasLines = true;
+        }
+        ext = 8;
+    } else if (p.type == "MESSAGE" && p.subtype == "RFC822") {
+        // media-message is the only 1part shape carrying a whole message:
+        // envelope, then the encapsulated BODY, then its line count.
+        if (const ImapValue* env = v.at(7); env != nullptr && env->isList())
+            p.envelope = envelopeFromValue(*env);
+        if (const ImapValue* inner = v.at(8); inner != nullptr && inner->isList())
+            p.children.push_back(buildPart(*inner, depth + 1));
+        if (const auto n = numberOf(v.at(9))) {
+            p.lines = *n;
+            p.hasLines = true;
+        }
+        ext = 10;
+    }
+
+    // body-ext-1part begins with the MD5, so the disposition is one further on.
+    applyDisposition(p, v.at(ext + 1));
+
+    std::string raw;
+    p.name = collapseParam(p.params, "name", raw);
+    p.nameRaw = raw;
+    p.charset = p.params.count("charset") != 0 ? p.params.at("charset") : std::string();
+
+    // The disposition's filename wins over the type's name parameter: the
+    // former is the one defined to carry a filename, the latter is a legacy
+    // habit, and a message that sends both and disagrees means the disposition.
+    std::string fnRaw;
+    std::string fn = collapseParam(p.dispositionParams, "filename", fnRaw);
+    if (fn.empty() && fnRaw.empty()) {
+        fn = p.name;
+        fnRaw = p.nameRaw;
+    }
+    p.filename = fn;
+    p.filenameRaw = fnRaw;
+    return p;
+}
+
+void numberNode(ImapBodyPart& p, const std::string& number);
+
+/// Number the body of ONE message. `prefix` is empty for the message that was
+/// fetched, and `"<n>."` for a message encapsulated at part <n>.
+///
+/// RFC 3501 6.4.5, and the two rules that are not the obvious tree walk:
+///
+///   * A message with no multipart body still has a part, and it is "1". So a
+///     plain text/plain mail is BODY[1], not BODY[] - and a caller that assumes
+///     the top level is always a list of parts fetches nothing.
+///   * A message/rfc822's encapsulated multipart does NOT add a level. Part 3
+///     holding a multipart/mixed numbers its children 3.1 and 3.2, not 3.1.1
+///     and 3.1.2. This is the one most likely to be got wrong, because the C++
+///     tree genuinely does have an extra node there.
+void numberMessageBody(ImapBodyPart& body, const std::string& prefix) {
+    if (body.multipart) {
+        // A multipart CONTAINER has no number of its own; it is addressed as
+        // BODY[TEXT] (or <prefix>TEXT). Empty therefore means "fetch my
+        // children instead of me" rather than "unknown".
+        body.number.clear();
+        for (size_t i = 0; i < body.children.size(); ++i)
+            numberNode(body.children[i], prefix + std::to_string(i + 1));
+        return;
+    }
+    body.number = prefix + "1";
+    if (body.type == "MESSAGE" && body.subtype == "RFC822" && !body.children.empty())
+        numberMessageBody(body.children[0], body.number + ".");
+}
+
+void numberNode(ImapBodyPart& p, const std::string& number) {
+    p.number = number;
+    if (p.multipart) {
+        for (size_t i = 0; i < p.children.size(); ++i)
+            numberNode(p.children[i], number + "." + std::to_string(i + 1));
+        return;
+    }
+    if (p.type == "MESSAGE" && p.subtype == "RFC822" && !p.children.empty())
+        numberMessageBody(p.children[0], number + ".");
+}
+
+// ---------------------------------------------------------------------------
+// FETCH items
+// ---------------------------------------------------------------------------
+
+/// The section inside `BODY[...]`, uppercased, or nullopt when the atom is not
+/// a sectioned body item.
+///
+/// Normalises BODY.PEEK[x] to the same key as BODY[x] and drops a partial
+/// fetch's `<offset>` suffix. See the comment on ImapFetchRecord::bodyParts for
+/// why the PEEK spelling matters.
+std::optional<std::string> sectionOf(const std::string& nameUpper) {
+    const bool isBody = nameUpper.rfind("BODY[", 0) == 0;
+    const bool isPeek = nameUpper.rfind("BODY.PEEK[", 0) == 0;
+    if (!isBody && !isPeek) return std::nullopt;
+    const size_t open = nameUpper.find('[');
+    const size_t close = nameUpper.rfind(']');
+    if (open == std::string::npos || close == std::string::npos || close < open)
+        return std::nullopt;
+    return nameUpper.substr(open + 1, close - open - 1);
+}
+
+void applyFetchItems(const ImapValue& list, ImapFetchRecord& rec) {
+    for (size_t i = 0; i < list.items.size(); ++i) {
+        const ImapValue& nameVal = list.items[i];
+        if (!nameVal.isText()) continue;  // a stray value where a name belongs
+        const std::string name = upper(nameVal.text);
+        const ImapValue* val = (i + 1 < list.items.size()) ? &list.items[i + 1] : nullptr;
+
+        if (const auto section = sectionOf(name)) {
+            if (val != nullptr) {
+                // A NIL body part is a real answer (the server has no such
+                // section) and stores as empty, which is the same thing to a
+                // caller reading bytes.
+                rec.bodyParts[*section] = val->isText() ? val->text : std::string();
+                ++i;
+            }
+            continue;
+        }
+        if (name == "UID") {
+            if (const auto n = numberOf(val)) {
+                rec.uid = *n;
+                rec.hasUid = true;
+            }
+            if (val != nullptr) ++i;
+            continue;
+        }
+        if (name == "FLAGS") {
+            if (val != nullptr && val->isList()) {
+                for (const ImapValue& f : val->items)
+                    if (f.isText()) rec.flags.push_back(f.text);
+            }
+            if (val != nullptr) ++i;
+            continue;
+        }
+        if (name == "INTERNALDATE") {
+            rec.internalDate = textOf(val);
+            if (val != nullptr) ++i;
+            continue;
+        }
+        if (name == "RFC822.SIZE") {
+            if (const auto n = numberOf(val)) {
+                rec.rfc822Size = *n;
+                rec.hasRfc822Size = true;
+            }
+            if (val != nullptr) ++i;
+            continue;
+        }
+        if (name == "ENVELOPE") {
+            if (val != nullptr && val->isList()) rec.envelope = envelopeFromValue(*val);
+            if (val != nullptr) ++i;
+            continue;
+        }
+        if (name == "BODYSTRUCTURE" || name == "BODY") {
+            // A bare BODY with no section IS the body structure - the
+            // non-extensible form of BODYSTRUCTURE. Only the bracketed
+            // spellings carry data, and those were handled above.
+            if (val != nullptr && val->isList()) {
+                ImapBodyPart root = buildPart(*val, 0);
+                numberMessageBody(root, std::string());
+                rec.bodyStructure = std::move(root);
+            }
+            if (val != nullptr) ++i;
+            continue;
+        }
+        if (name == "RFC822" || name == "RFC822.HEADER" || name == "RFC822.TEXT") {
+            // Equivalent to BODY[], BODY[HEADER] and BODY[TEXT]. Folded onto
+            // the same keys so a caller need not know which spelling the
+            // server, or our own command, happened to use.
+            const std::string key = name == "RFC822" ? std::string()
+                                    : name == "RFC822.HEADER" ? std::string("HEADER")
+                                                              : std::string("TEXT");
+            if (val != nullptr) {
+                rec.bodyParts[key] = val->isText() ? val->text : std::string();
+                ++i;
+            }
+            continue;
+        }
+        // Unknown: skip the name and exactly one value. Servers volunteer
+        // MODSEQ, X-GM-MSGID and others unasked; refusing the response over one
+        // of them would make the whole mailbox unreadable on that server.
+        rec.unknownItems.push_back(nameVal.text);
+        if (val != nullptr) ++i;
+    }
+}
+
+bool isUntagged(const std::vector<ImapValue>& v) {
+    return !v.empty() && v[0].isText() && v[0].text == "*";
+}
+
+}  // namespace
+
+// ---------------------------------------------------------------------------
+
+std::optional<uint64_t> ImapValue::numberAt(size_t i) const { return numberOf(at(i)); }
+
+ImapSexp parseResponseLine(std::string_view bytes, size_t maxDepth) {
+    ImapSexp out;
+    ImapReader rd(bytes);
+    std::vector<ImapToken> toks;
+    const ImapParse r = rd.readLine(toks);
+    if (r != ImapParse::Ok) {
+        out.status = r;
+        return out;
+    }
+    const std::vector<ImapToken> joined = rejoinSections(toks);
+    size_t i = 0;
+    out.status = buildSeq(joined, i, out.values, false, 0, maxDepth);
+    if (out.status == ImapParse::Ok) out.consumed = rd.consumed();
+    else out.values.clear();
+    return out;
+}
+
+ImapListResult parseListResponse(std::string_view bytes) {
+    ImapListResult out;
+    out.status = eachLine(bytes, out.consumed, kMaxSexpDepth, [&](const std::vector<ImapValue>& v) {
+        if (!isUntagged(v) || v.size() < 2 || !v[1].isText()) return;
+        if (!equalsIgnoreCase(v[1].text, "LIST") && !equalsIgnoreCase(v[1].text, "LSUB")) return;
+        if (v.size() < 5 || !v[2].isList()) return;
+        ImapMailbox m;
+        for (const ImapValue& f : v[2].items)
+            if (f.isText()) m.flags.push_back(f.text);
+        m.delimiter = textOf(&v[3]);
+        m.nameRaw = textOf(&v[4]);
+        out.mailboxes.push_back(std::move(m));
+    });
+    if (out.status == ImapParse::Malformed) out.mailboxes.clear();
+    return out;
+}
+
+ImapSearchResult parseSearchResponse(std::string_view bytes) {
+    ImapSearchResult out;
+    out.status = eachLine(bytes, out.consumed, kMaxSexpDepth, [&](const std::vector<ImapValue>& v) {
+        if (!isUntagged(v) || v.size() < 2 || !v[1].isText()) return;
+        if (!equalsIgnoreCase(v[1].text, "SEARCH")) return;
+        for (size_t i = 2; i < v.size(); ++i)
+            if (const auto n = numberOf(&v[i])) out.uids.push_back(*n);
+    });
+    if (out.status == ImapParse::Malformed) out.uids.clear();
+    return out;
+}
+
+ImapEnvelope envelopeFromValue(const ImapValue& v) {
+    ImapEnvelope e;
+    if (!v.isList()) return e;
+    e.date = textOf(v.at(0));
+    e.subjectRaw = textOf(v.at(1));
+    e.subject = MimeWords::decode(e.subjectRaw);
+
+    const auto addrs = [](const ImapValue* list) {
+        std::vector<ImapAddress> out;
+        if (list == nullptr || !list->isList()) return out;
+        for (const ImapValue& a : list->items) {
+            if (!a.isList()) continue;
+            ImapAddress addr;
+            addr.nameRaw = textOf(a.at(0));
+            addr.name = MimeWords::decode(addr.nameRaw);
+            addr.adl = textOf(a.at(1));
+            addr.mailbox = textOf(a.at(2));
+            const ImapValue* host = a.at(3);
+            addr.host = textOf(host);
+            // A NIL host is a group marker, not an address. Building
+            // mailbox@host anyway is how "undisclosed-recipients@" and
+            // "Group Name@" end up being treated as deliverable.
+            addr.groupMarker = (host == nullptr || host->isNil() || addr.host.empty());
+            if (!addr.groupMarker && !addr.mailbox.empty())
+                addr.address = addr.mailbox + "@" + addr.host;
+            out.push_back(std::move(addr));
+        }
+        return out;
+    };
+
+    e.from = addrs(v.at(2));
+    e.sender = addrs(v.at(3));
+    e.replyTo = addrs(v.at(4));
+    e.to = addrs(v.at(5));
+    e.cc = addrs(v.at(6));
+    e.bcc = addrs(v.at(7));
+    e.inReplyTo = textOf(v.at(8));
+    e.messageId = textOf(v.at(9));
+    return e;
+}
+
+ImapEnvelopeResult parseEnvelopeResponse(std::string_view bytes) {
+    const ImapFetchResult f = parseFetchResponse(bytes);
+    ImapEnvelopeResult out;
+    out.status = f.status;
+    out.consumed = f.consumed;
+    for (const ImapFetchRecord& r : f.messages)
+        if (r.envelope) {
+            out.envelope = r.envelope;
+            break;
+        }
+    return out;
+}
+
+ImapBodyPart bodyPartFromValue(const ImapValue& v, const std::string& prefix) {
+    ImapBodyPart p = buildPart(v, 0);
+    numberMessageBody(p, prefix);
+    return p;
+}
+
+ImapBodyStructureResult parseBodyStructureResponse(std::string_view bytes) {
+    const ImapFetchResult f = parseFetchResponse(bytes);
+    ImapBodyStructureResult out;
+    out.status = f.status;
+    out.consumed = f.consumed;
+    for (const ImapFetchRecord& r : f.messages)
+        if (r.bodyStructure) {
+            out.root = r.bodyStructure;
+            break;
+        }
+    return out;
+}
+
+ImapFetchResult parseFetchResponse(std::string_view bytes) {
+    ImapFetchResult out;
+    out.status = eachLine(bytes, out.consumed, kMaxSexpDepth, [&](const std::vector<ImapValue>& v) {
+        if (!isUntagged(v) || v.size() < 4) return;
+        if (!v[2].isText() || !equalsIgnoreCase(v[2].text, "FETCH")) return;
+        if (!v[3].isList()) return;
+        ImapFetchRecord rec;
+        if (const auto n = numberOf(&v[1])) rec.seq = *n;
+        applyFetchItems(v[3], rec);
+        out.messages.push_back(std::move(rec));
+    });
+    if (out.status == ImapParse::Malformed) out.messages.clear();
+    return out;
+}
+
+const ImapFetchRecord* findByUid(const std::vector<ImapFetchRecord>& messages, uint64_t uid) {
+    for (const ImapFetchRecord& r : messages)
+        if (r.hasUid && r.uid == uid) return &r;
+    return nullptr;
+}
+
+namespace {
+
+ImapAttachmentRef attachmentOf(const ImapBodyPart& p) {
+    ImapAttachmentRef a;
+    a.number = p.number;
+    a.filename = p.filename;
+    a.filenameRaw = p.filenameRaw;
+    a.type = p.type;
+    a.subtype = p.subtype;
+    a.encoding = p.encoding;
+    a.disposition = p.disposition;
+    a.octets = p.octets;
+    return a;
+}
+
+void selectWalk(const ImapBodyPart& p, ImapBodySelection& out, ImapBodyChoice& plain,
+                ImapBodyChoice& html) {
+    if (p.multipart) {
+        for (const ImapBodyPart& c : p.children) selectWalk(c, out, plain, html);
+        return;
+    }
+    if (p.type == "MESSAGE" && p.subtype == "RFC822") {
+        // Listed, never descended into - see selectBody's contract.
+        out.attachments.push_back(attachmentOf(p));
+        return;
+    }
+    const bool attached = !p.filename.empty() || !p.filenameRaw.empty() ||
+                          p.disposition == "ATTACHMENT";
+    const bool isText = p.type == "TEXT";
+    if (!attached && isText) {
+        ImapBodyChoice* slot = nullptr;
+        if (p.subtype == "PLAIN" && !plain.found) slot = &plain;
+        else if (p.subtype == "HTML" && !html.found) slot = &html;
+        if (slot != nullptr) {
+            slot->found = true;
+            slot->number = p.number;
+            slot->subtype = p.subtype;
+            slot->charset = p.charset;
+            slot->encoding = p.encoding;
+            slot->octets = p.octets;
+            return;
+        }
+    }
+    // Everything a caller did not get as the body is listed: an inline image
+    // referenced by Content-ID has no filename and no ATTACHMENT disposition,
+    // and dropping it would lose a part the caller may well want. Listing it is
+    // recoverable; losing it is not.
+    if (attached || !isText) out.attachments.push_back(attachmentOf(p));
+}
+
+}  // namespace
+
+ImapBodySelection selectBody(const ImapBodyPart& root) {
+    ImapBodySelection out;
+    ImapBodyChoice plain;
+    ImapBodyChoice html;
+    selectWalk(root, out, plain, html);
+    if (plain.found) {
+        out.text = plain;
+    } else if (html.found) {
+        out.text = html;
+        out.isHtmlFallback = true;
+    }
+    return out;
+}
+
+// ---------------------------------------------------------------------------
+
+nlohmann::json toJson(const ImapAddress& a) {
+    return nlohmann::json{{"name", a.name},
+                          {"name_raw", a.nameRaw},
+                          {"mailbox", a.mailbox},
+                          {"host", a.host},
+                          {"address", a.address},
+                          {"group_marker", a.groupMarker}};
+}
+
+nlohmann::json toJson(const ImapEnvelope& e) {
+    const auto list = [](const std::vector<ImapAddress>& v) {
+        nlohmann::json j = nlohmann::json::array();
+        for (const ImapAddress& a : v) j.push_back(toJson(a));
+        return j;
+    };
+    return nlohmann::json{{"date", e.date},
+                          {"subject", e.subject},
+                          {"subject_raw", e.subjectRaw},
+                          {"from", list(e.from)},
+                          {"sender", list(e.sender)},
+                          {"reply_to", list(e.replyTo)},
+                          {"to", list(e.to)},
+                          {"cc", list(e.cc)},
+                          {"bcc", list(e.bcc)},
+                          {"in_reply_to", e.inReplyTo},
+                          {"message_id", e.messageId}};
+}
+
+nlohmann::json toJson(const ImapBodyPart& p) {
+    nlohmann::json j{{"number", p.number},
+                     {"type", p.type},
+                     {"subtype", p.subtype},
+                     {"charset", p.charset},
+                     {"encoding", p.encoding},
+                     {"content_id", p.contentId},
+                     {"description", p.description},
+                     {"disposition", p.disposition},
+                     {"filename", p.filename},
+                     {"filename_raw", p.filenameRaw},
+                     {"multipart", p.multipart},
+                     {"params", p.params}};
+    if (p.hasOctets) j["octets"] = p.octets;
+    if (p.hasLines) j["lines"] = p.lines;
+    if (p.envelope) j["envelope"] = toJson(*p.envelope);
+    if (!p.children.empty()) {
+        nlohmann::json kids = nlohmann::json::array();
+        for (const ImapBodyPart& c : p.children) kids.push_back(toJson(c));
+        j["parts"] = std::move(kids);
+    }
+    return j;
+}
+
+nlohmann::json toJson(const ImapFetchRecord& r) {
+    nlohmann::json j{{"seq", r.seq},
+                     {"flags", r.flags},
+                     {"internal_date", r.internalDate}};
+    if (r.hasUid) j["uid"] = r.uid;
+    if (r.hasRfc822Size) j["size"] = r.rfc822Size;
+    if (r.envelope) j["envelope"] = toJson(*r.envelope);
+    if (r.bodyStructure) j["body_structure"] = toJson(*r.bodyStructure);
+    // Section NAMES only. The bytes are deliberately not projected: one part
+    // can be megabytes and the JS heap it would land in is 64 MiB.
+    nlohmann::json sections = nlohmann::json::array();
+    for (const auto& [key, value] : r.bodyParts) {
+        (void)value;
+        sections.push_back(key);
+    }
+    j["body_sections"] = std::move(sections);
+    if (!r.unknownItems.empty()) j["unknown_items"] = r.unknownItems;
+    return j;
+}
+
+}  // namespace svapi::runner::net

+ 398 - 0
runner/src/net/imap_fetch.hpp

@@ -0,0 +1,398 @@
+#pragma once
+#include <cstdint>
+#include <map>
+#include <optional>
+#include <string>
+#include <string_view>
+#include <vector>
+
+#include <nlohmann/json.hpp>
+
+#include "functions/imap_reader.hpp"
+
+/// Interpreting IMAP server responses: tokens in, structs out.
+///
+/// `functions/imap_reader.hpp` answers "where does this token end", which is
+/// the byte-counting problem. This file answers "what does it MEAN", which is
+/// the grammar problem, and the two are kept apart because they fail
+/// differently: a tokenizer bug corrupts the stream position and poisons the
+/// connection, while a grammar bug only mis-reads one message.
+///
+/// Everything here is pure. No sockets, no curl, no command construction - a
+/// response is a `string_view` and the answer is a struct, so every awkward
+/// shape a real server emits can be pinned down as a string literal in a test.
+///
+/// ⚠ A SERVER'S RESPONSE IS HOSTILE INPUT. We did not write the server, it may
+/// be an old one, a proxy, or a man in the middle, and the bytes arrive before
+/// anything has authenticated them as sane. So: truncation reports `NeedMore`
+/// and never reads past the end, nonsense reports `Malformed` and never throws,
+/// an item we do not recognise is IGNORED rather than failing the whole
+/// response, and nesting is capped (`kMaxSexpDepth`) because the alternative is
+/// a stack overflow a server can trigger with a few hundred open parentheses.
+namespace svapi::runner::net {
+
+using svapi::functions::ImapParse;
+
+/// How deep a parenthesised response may nest before we call it malformed.
+///
+/// This is a safety cap, not a grammar rule: real BODYSTRUCTUREs run perhaps
+/// four or five deep (multipart/mixed holding a multipart/alternative holding a
+/// forwarded message). The recursion here is bounded BY this number, so the cap
+/// is what makes the recursive descent safe rather than merely tidy.
+inline constexpr size_t kMaxSexpDepth = 24;
+
+// ---------------------------------------------------------------------------
+// The s-expression layer
+// ---------------------------------------------------------------------------
+
+/// One node of a parenthesised IMAP response.
+///
+/// `Atom` and `String` are kept apart for the same reason the reader keeps
+/// quoted and literal apart: an atom is protocol vocabulary (FETCH, \Seen,
+/// 1234) while a string is data. `Nil` is its own kind because NIL is a VALUE
+/// meaning absent, and code that sees it as the three-letter text will store a
+/// subject literally reading "NIL".
+struct ImapValue {
+    enum class Kind { Atom, String, Nil, List };
+
+    Kind kind = Kind::Nil;
+    std::string text;              ///< Atom/String content; empty for Nil and List
+    std::vector<ImapValue> items;  ///< List children
+
+    bool isList() const { return kind == Kind::List; }
+    bool isNil() const { return kind == Kind::Nil; }
+    /// Atom or String: anything carrying readable text. Callers almost always
+    /// want this rather than the exact kind, because a server may send a
+    /// subtype quoted or bare and both are legal.
+    bool isText() const { return kind == Kind::Atom || kind == Kind::String; }
+
+    /// Index-safe accessors. Every BODYSTRUCTURE field is positional, so
+    /// reading one means indexing a list whose length a server chose - and a
+    /// bare `items[i]` on a short list is the whole class of bug this layer
+    /// exists to make impossible. `at()` returns nullptr past the end.
+    const ImapValue* at(size_t i) const { return i < items.size() ? &items[i] : nullptr; }
+    std::string textAt(size_t i) const {
+        const ImapValue* v = at(i);
+        return (v != nullptr && v->isText()) ? v->text : std::string();
+    }
+    std::optional<uint64_t> numberAt(size_t i) const;
+};
+
+/// One logical response line, tokenized and shaped.
+struct ImapSexp {
+    ImapParse status = ImapParse::NeedMore;
+    std::vector<ImapValue> values;  ///< top-level values, in order
+    size_t consumed = 0;            ///< bytes of input this line used
+};
+
+/// Parse ONE logical response line (a line plus every literal it carries) from
+/// the front of `bytes`.
+///
+/// A list left open when the line ends is `Malformed`, not `NeedMore`: the
+/// reader already told us the terminating CRLF arrived, and IMAP has no
+/// continuation of parenthesised data across response lines. Only the reader
+/// can legitimately say "read more", because only it knows it is mid-literal.
+ImapSexp parseResponseLine(std::string_view bytes, size_t maxDepth = kMaxSexpDepth);
+
+// ---------------------------------------------------------------------------
+// LIST / LSUB
+// ---------------------------------------------------------------------------
+
+/// One mailbox from a LIST or LSUB response.
+struct ImapMailbox {
+    std::vector<std::string> flags;  ///< as sent, e.g. "\HasNoChildren"
+    /// The hierarchy delimiter, or empty when the server sent NIL (a flat
+    /// namespace). Empty therefore means "no delimiter", never "unknown".
+    std::string delimiter;
+    /// THE NAME AS IT ARRIVED, still in modified UTF-7 if the server is not
+    /// running UTF8=ACCEPT. Decoding it is deliberately not done here: it is a
+    /// charset transform with its own edge cases and its own file, and a
+    /// half-decoded name is worse than an honestly encoded one. A caller that
+    /// wants to display the name decodes it; a caller that wants to SELECT the
+    /// mailbox must use exactly these bytes.
+    std::string nameRaw;
+};
+
+struct ImapListResult {
+    ImapParse status = ImapParse::NeedMore;
+    std::vector<ImapMailbox> mailboxes;
+    size_t consumed = 0;
+};
+
+/// LIST and LSUB share one grammar, so they share one parser. Lines that are
+/// neither (the tagged completion, an untagged OK, a CAPABILITY the server
+/// volunteered) are skipped rather than rejected.
+ImapListResult parseListResponse(std::string_view bytes);
+
+// ---------------------------------------------------------------------------
+// UID SEARCH
+// ---------------------------------------------------------------------------
+
+struct ImapSearchResult {
+    ImapParse status = ImapParse::NeedMore;
+    /// The numbers from `* SEARCH ...`. With UID SEARCH these are UIDs; with a
+    /// plain SEARCH they are sequence numbers. The response does not say which,
+    /// so this struct cannot either - the caller knows what it asked for.
+    std::vector<uint64_t> uids;
+    size_t consumed = 0;
+};
+
+/// `* SEARCH 1 3 7` and the empty `* SEARCH` (a legal no-match answer, which is
+/// why an empty list with status Ok is a real result and not a parse failure).
+///
+/// ESEARCH (RFC 4731) is deliberately NOT handled: it is a different grammar
+/// returned only when the command carried a RETURN clause, and we never send
+/// one. A server emitting it unasked leaves `uids` empty rather than being
+/// mis-read.
+ImapSearchResult parseSearchResponse(std::string_view bytes);
+
+// ---------------------------------------------------------------------------
+// ENVELOPE
+// ---------------------------------------------------------------------------
+
+/// One IMAP address, the 4-tuple (name, adl, mailbox, host).
+struct ImapAddress {
+    /// The display name, RFC 2047 decoded. `nameRaw` keeps the bytes as sent
+    /// because decoding is lossy in both directions: an unknown charset comes
+    /// back as gibberish rather than nothing, and a value that was never
+    /// encoded but happens to contain "=?" would be mangled. Anything that has
+    /// to round-trip, be compared against another message's header, or be
+    /// shown when the decode looks wrong needs the original.
+    std::string name;
+    std::string nameRaw;
+    std::string adl;      ///< source route, obsolete; kept because it is in the wire tuple
+    std::string mailbox;  ///< local part, or the group name on a group start marker
+    std::string host;     ///< domain, or empty for a group marker
+    /// mailbox + "@" + host. Empty for a group marker, since there is no
+    /// address to send to.
+    std::string address;
+    /// A NIL host means this entry is a GROUP MARKER, not an address: mailbox
+    /// holds the group name on the way in and is itself NIL on the way out.
+    /// Treating one as an address produces mail to "undisclosed-recipients@",
+    /// which is how that string ends up in a To: line.
+    bool groupMarker = false;
+};
+
+struct ImapEnvelope {
+    std::string date;        ///< as sent; parsing RFC 5322 dates is not this file's job
+    std::string subject;     ///< RFC 2047 decoded
+    std::string subjectRaw;  ///< as sent
+    std::vector<ImapAddress> from;
+    std::vector<ImapAddress> sender;
+    std::vector<ImapAddress> replyTo;
+    std::vector<ImapAddress> to;
+    std::vector<ImapAddress> cc;
+    std::vector<ImapAddress> bcc;
+    std::string inReplyTo;
+    std::string messageId;
+};
+
+/// Shape an already-parsed ENVELOPE list. Exposed because a BODYSTRUCTURE for
+/// message/rfc822 carries an envelope inside it, so this has to be callable
+/// from the body-structure walk as well as from a FETCH item.
+ImapEnvelope envelopeFromValue(const ImapValue& v);
+
+/// Parse a complete `* n FETCH (ENVELOPE (...))` response for convenience.
+struct ImapEnvelopeResult {
+    ImapParse status = ImapParse::NeedMore;
+    std::optional<ImapEnvelope> envelope;
+    size_t consumed = 0;
+};
+ImapEnvelopeResult parseEnvelopeResponse(std::string_view bytes);
+
+// ---------------------------------------------------------------------------
+// BODYSTRUCTURE
+// ---------------------------------------------------------------------------
+
+/// One MIME part from a BODYSTRUCTURE, with its children.
+struct ImapBodyPart {
+    /// THE IMAP PART NUMBER - the "1", "1.2", "2.1" path that a later
+    /// `BODY.PEEK[1.2]` must name. This is the single most valuable field here
+    /// and the easiest to get wrong, because the numbering is NOT the obvious
+    /// tree position. See `assignPartNumbers` in the .cpp for the rules and
+    /// RFC 3501 section 6.4.5 for the authority.
+    ///
+    /// Empty for a multipart CONTAINER, which has no number of its own: the
+    /// top-level multipart of a message is addressed as BODY[TEXT], not
+    /// BODY[0]. So an empty number means "do not fetch this node, fetch its
+    /// children".
+    std::string number;
+
+    std::string type;     ///< uppercased, e.g. "TEXT", "MULTIPART", "APPLICATION"
+    std::string subtype;  ///< uppercased, e.g. "PLAIN", "MIXED", "RFC822"
+
+    /// Content-Type parameters, keys lowercased. `charset` and `name` are
+    /// lifted out because they are the two every caller wants.
+    std::map<std::string, std::string> params;
+    std::string charset;
+    std::string name;     ///< the `name` parameter, decoded
+    std::string nameRaw;
+
+    std::string contentId;     ///< body-fld-id, with its angle brackets as sent
+    std::string description;   ///< body-fld-desc, RFC 2047 decoded
+    std::string encoding;      ///< uppercased Content-Transfer-Encoding
+
+    uint64_t octets = 0;       ///< encoded size; meaningless unless hasOctets
+    bool hasOctets = false;
+    uint64_t lines = 0;        ///< text/* and message/rfc822 only
+    bool hasLines = false;
+
+    /// Content-Disposition from the body extension data, uppercased, e.g.
+    /// "ATTACHMENT" or "INLINE". Empty when the server sent no extension data
+    /// at all - which is why absence can never be read as "inline".
+    std::string disposition;
+    std::map<std::string, std::string> dispositionParams;
+
+    /// The filename, from the disposition's `filename` or the type's `name`,
+    /// with RFC 2047 encoded words and RFC 2231 continuations resolved as far
+    /// as we reasonably can. `filenameRaw` is the untouched winner, because a
+    /// filename is used to write a file and a mis-decode must stay inspectable.
+    std::string filename;
+    std::string filenameRaw;
+
+    bool multipart = false;
+    std::vector<ImapBodyPart> children;
+
+    /// The envelope of an encapsulated message, present only for
+    /// message/rfc822. The encapsulated BODY appears as the single entry in
+    /// `children`, which keeps the real nesting visible: that child is a
+    /// multipart container (number empty) or the message's one part.
+    std::optional<ImapEnvelope> envelope;
+};
+
+struct ImapBodyStructureResult {
+    ImapParse status = ImapParse::NeedMore;
+    std::optional<ImapBodyPart> root;
+    size_t consumed = 0;
+};
+
+/// Shape an already-parsed BODYSTRUCTURE (or BODY) list, then number its parts.
+///
+/// `prefix` is for an encapsulated message and is normally left empty.
+ImapBodyPart bodyPartFromValue(const ImapValue& v, const std::string& prefix = std::string());
+
+/// Parse a complete `* n FETCH (BODYSTRUCTURE (...))` response.
+ImapBodyStructureResult parseBodyStructureResponse(std::string_view bytes);
+
+// ---------------------------------------------------------------------------
+// Picking the parts a caller actually wants
+// ---------------------------------------------------------------------------
+
+/// A body part worth fetching, reduced to what a fetch needs.
+struct ImapBodyChoice {
+    bool found = false;
+    std::string number;    ///< what to put in BODY.PEEK[...]
+    std::string subtype;   ///< "PLAIN" or "HTML"
+    std::string charset;
+    std::string encoding;
+    uint64_t octets = 0;
+};
+
+struct ImapAttachmentRef {
+    std::string number;
+    std::string filename;
+    std::string filenameRaw;
+    std::string type;
+    std::string subtype;
+    std::string encoding;
+    std::string disposition;
+    uint64_t octets = 0;
+};
+
+struct ImapBodySelection {
+    /// text/plain if there is one, otherwise text/html.
+    ImapBodyChoice text;
+    /// True when `text` is the html fallback, so a caller knows it must strip
+    /// markup rather than display the bytes as written.
+    bool isHtmlFallback = false;
+    std::vector<ImapAttachmentRef> attachments;
+};
+
+/// Pick the readable body and list the attachments.
+///
+/// A message/rfc822 part is listed as an attachment and NOT descended into when
+/// choosing the body: a forwarded message's text is the forwarded message's
+/// body, not this one's, and a caller that shows it has quietly replaced the
+/// mail it was asked about. Its subtree is still numbered, so a caller that
+/// genuinely wants the inner text can walk the tree and fetch it by number.
+ImapBodySelection selectBody(const ImapBodyPart& root);
+
+// ---------------------------------------------------------------------------
+// FETCH
+// ---------------------------------------------------------------------------
+
+/// One message from a FETCH response.
+struct ImapFetchRecord {
+    uint64_t seq = 0;  ///< the message sequence number the response was keyed by
+    /// The UID. A sequence number is only valid for the lifetime of one
+    /// selected-mailbox session, so nothing outside a session may be keyed by
+    /// it; `hasUid` is false when the server returned no UID item, and a caller
+    /// that needs stable identity must treat that as unusable rather than
+    /// falling back to `seq`.
+    uint64_t uid = 0;
+    bool hasUid = false;
+
+    std::vector<std::string> flags;
+    std::string internalDate;  ///< raw IMAP date-time
+    uint64_t rfc822Size = 0;
+    bool hasRfc822Size = false;
+    std::optional<ImapEnvelope> envelope;
+    std::optional<ImapBodyPart> bodyStructure;
+
+    /// Body-part data, keyed by the SECTION inside the brackets, uppercased:
+    /// "" for BODY[], "TEXT", "HEADER", "1.2", "2.MIME".
+    ///
+    /// ⚠ THE PEEK DISAPPEARS. A fetch of BODY.PEEK[1] comes back labelled
+    /// BODY[1] - the .PEEK is a command-side instruction ("do not set \Seen"),
+    /// never part of the response. Code that keys the response by the string it
+    /// sent finds nothing and reports an empty body for a message that arrived
+    /// intact. Both spellings are therefore normalised to the same key here,
+    /// and a partial fetch's `<offset>` suffix is stripped, so BODY[1]<0> and
+    /// BODY[1] land on "1" too.
+    std::map<std::string, std::string> bodyParts;
+
+    /// Items we do not understand, recorded by name and otherwise ignored.
+    ///
+    /// Ignoring is the requirement: servers volunteer MODSEQ, X-GM-MSGID,
+    /// X-GM-LABELS and more without being asked, and failing the whole response
+    /// over one unknown item would make the mailbox unreadable on that server.
+    /// Recording them is what makes the ignoring visible instead of silent.
+    std::vector<std::string> unknownItems;
+};
+
+struct ImapFetchResult {
+    ImapParse status = ImapParse::NeedMore;
+    /// Complete records, in arrival order. On NeedMore these are the messages
+    /// that parsed fully, so a caller can keep them and resume at `consumed`
+    /// rather than re-parsing the whole buffer.
+    std::vector<ImapFetchRecord> messages;
+    size_t consumed = 0;
+};
+
+/// Parse every `* n FETCH (...)` in `bytes`.
+///
+/// Non-FETCH lines are skipped: a tagged completion, an untagged EXISTS, a
+/// RECENT, an unsolicited EXPUNGE. Only a line that cannot be IMAP at all is
+/// Malformed.
+ImapFetchResult parseFetchResponse(std::string_view bytes);
+
+/// Find a record by UID. Returns nullptr when absent, because "the server did
+/// not return this UID" is an ordinary outcome of a fetch against a mailbox
+/// that changed under us, not an error.
+const ImapFetchRecord* findByUid(const std::vector<ImapFetchRecord>& messages, uint64_t uid);
+
+// ---------------------------------------------------------------------------
+// JSON shapes
+// ---------------------------------------------------------------------------
+
+/// These exist because the eventual consumer is JavaScript inside the runner,
+/// and shaping the JSON here keeps the host-side surface declarative - the same
+/// reason the rest of the mail surface is pure. They are a projection, not the
+/// source of truth: body-part BYTES are deliberately absent, since a part can
+/// be megabytes and a JS heap is 64 MiB.
+nlohmann::json toJson(const ImapAddress& a);
+nlohmann::json toJson(const ImapEnvelope& e);
+nlohmann::json toJson(const ImapBodyPart& p);
+nlohmann::json toJson(const ImapFetchRecord& r);
+
+}  // namespace svapi::runner::net

+ 97 - 0
runner/src/net/mail_budget.hpp

@@ -0,0 +1,97 @@
+#pragma once
+#include <algorithm>
+#include <cstdint>
+
+/// How long a mail call made from inside a function may take.
+///
+/// Same enforcement problem as `functions/embed_budget.hpp`, and deliberately
+/// the same shape: a blocking host call cannot be interrupted, because the run's
+/// wall budget is enforced by a QuickJS interrupt handler that fires between
+/// bytecode operations and the engine never regains control while a socket call
+/// is in flight. Handing the client timeouts that already fit the budget IS the
+/// enforcement.
+///
+/// Mail needs ONE thing embeddings did not: a whole-session ceiling. An
+/// embedding call is a single request/response, so bounding connect and read
+/// bounds the call. A mailbox read is several round trips on one connection
+/// (greeting, LOGIN, EXAMINE, UID SEARCH, one or more UID FETCH), and a read
+/// timeout bounds each quiet period, NOT their sum - so a server that answers
+/// every command just inside the read timeout can hold a runtime far past the
+/// run's budget without ever tripping it. `totalMs` is the cap on the whole
+/// conversation and is what the caller must also enforce between round trips.
+///
+/// Header-only and pure: no clock, no sockets, no settings, no curl. Unit-test
+/// the arithmetic here rather than against a server that has to be slow.
+namespace svapi::runner::net {
+
+/// Everything with a say in one mail session's timeouts. Milliseconds in,
+/// seconds out for the per-phase values, because that is what the client takes.
+struct MailBudgetRequest {
+    /// What is left of the run's wall budget. 0 or less means none, and the
+    /// caller must refuse the call rather than make it with a floor applied.
+    int64_t remainingBudgetMs = 0;
+    /// The operator's configured timeouts, in seconds. 0 means "not stated".
+    int64_t configuredConnectSec = 0;
+    int64_t configuredReadSec = 0;
+    /// A per-call bound from the script. 0 means none. Narrowing only: it can
+    /// ask for less than the budget, never more.
+    int64_t callTimeoutMs = 0;
+};
+
+struct MailBudget {
+    /// What to give the client. Both are at least 1, because 0 means "no
+    /// timeout" and an unbounded host call is the bug this file prevents.
+    int64_t connectSec = 1;
+    int64_t readSec = 1;
+    /// The ceiling on the ENTIRE session, including every round trip. Always
+    /// the available time exactly, never rounded up: this is the number that
+    /// has to fit inside the run's budget.
+    int64_t totalMs = 0;
+    /// True when the script's own timeout was the binding constraint, so a
+    /// timeout can be reported as the script's choice rather than as the run
+    /// running out of time. The two want different error codes.
+    bool boundByCall = false;
+};
+
+/// Split the available time between connecting and reading, and state the
+/// whole-session ceiling.
+///
+/// Guarantees `connectSec + readSec` does not exceed the available time
+/// whenever that time is at least 2 seconds. Below that the 1-second floor on
+/// each phase dominates and the worst case is 2 seconds of per-phase allowance
+/// - but `totalMs` still carries the true budget, so a caller that enforces it
+/// between round trips stays bounded regardless. Stated rather than glossed
+/// over, as in the embedding case.
+///
+/// Connect gets at most HALF the available time: a reachable server connects in
+/// well under a second, so a large connect allowance buys nothing and only
+/// starves the phase where a slow-but-working server actually spends its time.
+inline MailBudget resolveMailBudget(const MailBudgetRequest& in) {
+    MailBudget out;
+
+    int64_t availableMs = in.remainingBudgetMs > 0 ? in.remainingBudgetMs : 0;
+    if (in.callTimeoutMs > 0 && in.callTimeoutMs < availableMs) {
+        availableMs = in.callTimeoutMs;
+        out.boundByCall = true;
+    }
+    out.totalMs = availableMs;
+
+    // Round UP: a 1500 ms budget should allow a 2-second total rather than
+    // being truncated to 1, which would cut a call that had time left.
+    int64_t availableSec = (availableMs + 999) / 1000;
+    if (availableSec < 1) availableSec = 1;
+
+    const int64_t connectCap = std::max<int64_t>(1, availableSec / 2);
+    out.connectSec = in.configuredConnectSec > 0
+                         ? std::min(in.configuredConnectSec, connectCap)
+                         : connectCap;
+    if (out.connectSec < 1) out.connectSec = 1;
+
+    const int64_t readRoom = std::max<int64_t>(1, availableSec - out.connectSec);
+    out.readSec = in.configuredReadSec > 0 ? std::min(in.configuredReadSec, readRoom) : readRoom;
+    if (out.readSec < 1) out.readSec = 1;
+
+    return out;
+}
+
+} // namespace svapi::runner::net

+ 320 - 0
runner/src/net/mail_session.cpp

@@ -0,0 +1,320 @@
+#include "net/mail_session.hpp"
+
+#include <curl/curl.h>
+
+#include <chrono>
+#include <cstring>
+
+#include "net/xfer_abort.hpp"
+
+namespace svapi::runner::net {
+namespace {
+
+int64_t defaultNowMs() {
+    return std::chrono::duration_cast<std::chrono::milliseconds>(
+               std::chrono::steady_clock::now().time_since_epoch())
+        .count();
+}
+
+/// Where a transfer's bytes land, plus everything the abort decision needs.
+/// The callbacks are C function pointers, so this is how they reach state.
+struct TransferState {
+    std::string* out = nullptr;
+    int64_t maxBytes = 0;
+    int64_t deadlineMs = 0;
+    std::function<int64_t()> nowMs;
+    AbortReason abort = AbortReason::None;
+};
+
+size_t writeToString(char* ptr, size_t size, size_t nmemb, void* userdata) {
+    auto* st = static_cast<TransferState*>(userdata);
+    const size_t n = size * nmemb;
+    if (st->out == nullptr) return n;
+    // The cap is enforced here as well as in the progress callback because a
+    // response can arrive inside a single callback invocation, before the
+    // progress callback is ever consulted. Returning short of `n` is how a
+    // write callback tells curl to abort.
+    if (st->maxBytes > 0 && static_cast<int64_t>(st->out->size() + n) > st->maxBytes) {
+        st->abort = AbortReason::TooLarge;
+        return 0;
+    }
+    st->out->append(ptr, n);
+    return n;
+}
+
+int progressDecision(void* userdata, curl_off_t dltotal, curl_off_t dlnow, curl_off_t ultotal,
+                     curl_off_t ulnow) {
+    (void)dltotal;
+    (void)ultotal;
+    auto* st = static_cast<TransferState*>(userdata);
+    const int64_t moved = static_cast<int64_t>(dlnow > ulnow ? dlnow : ulnow);
+    const int64_t now = st->nowMs ? st->nowMs() : defaultNowMs();
+    const AbortReason r = shouldAbortTransfer(st->deadlineMs, now, moved, st->maxBytes);
+    if (r == AbortReason::None) return 0;
+    st->abort = r;
+    return 1;  // non-zero aborts the transfer
+}
+
+/// Everything that is the same for IMAP and SMTP, in one place so the two
+/// cannot drift in their security posture.
+/// The port a scheme lands on when the account does not state one. Needed
+/// explicitly because CURLOPT_RESOLVE keys on host AND port, so a pin written
+/// with port 0 would silently never match and curl would resolve the name
+/// itself - defeating the guard rather than failing loudly.
+uint16_t effectivePort(const MailAccount& account, const char* protocols) {
+    if (account.port != 0) return account.port;
+    if (std::strcmp(protocols, "imaps") == 0) return 993;
+    if (std::strcmp(protocols, "imap") == 0) return 143;
+    if (std::strcmp(protocols, "smtps") == 0) return 465;
+    // 587 (submission) rather than 25: 25 is for server-to-server relay and is
+    // blocked outbound by most networks, so it is never the right default for a
+    // client sending through a provider.
+    return 587;
+}
+
+void applyCommonOptions(CURL* h, const MailAccount& account, const MailTransferOptions& options,
+                        const char* protocols, char* errbuf, TransferState* state,
+                        curl_slist** resolveOut) {
+    curl_easy_setopt(h, CURLOPT_ERRORBUFFER, errbuf);
+
+    // Mandatory in a thread pool: without it curl uses SIGALRM for name
+    // resolution timeouts, which is unsafe off the main thread and can longjmp
+    // out of a worker. A single-threaded test never shows this.
+    curl_easy_setopt(h, CURLOPT_NOSIGNAL, 1L);
+
+    // Belt and braces with the build-time disable list: that list bounds the
+    // binary, this bounds the call, and this is the one that catches a URL
+    // which got past validation. One scheme, not a family.
+    curl_easy_setopt(h, CURLOPT_PROTOCOLS_STR, protocols);
+
+    curl_easy_setopt(h, CURLOPT_SSL_VERIFYPEER, 1L);
+    curl_easy_setopt(h, CURLOPT_SSL_VERIFYHOST, 2L);
+    if (account.tls)
+        curl_easy_setopt(h, CURLOPT_USE_SSL, (long)CURLUSESSL_ALL);
+    else if (account.startTls)
+        // CURLUSESSL_ALL on a plaintext port means STARTTLS is REQUIRED, not
+        // attempted: a server that does not offer it fails the call rather than
+        // silently continuing in the clear with the credentials still to come.
+        curl_easy_setopt(h, CURLOPT_USE_SSL, (long)CURLUSESSL_ALL);
+
+    if (!account.user.empty()) curl_easy_setopt(h, CURLOPT_USERNAME, account.user.c_str());
+    if (!account.password.empty())
+        curl_easy_setopt(h, CURLOPT_PASSWORD, account.password.c_str());
+
+    curl_easy_setopt(h, CURLOPT_CONNECTTIMEOUT, (long)options.budget.connectSec);
+    // The whole-conversation ceiling. The per-phase read timeout bounds a quiet
+    // period and not the sum of them, so this is what keeps a server that
+    // answers slowly but steadily from holding a pooled runtime past the run's
+    // budget.
+    if (options.budget.totalMs > 0)
+        curl_easy_setopt(h, CURLOPT_TIMEOUT_MS, (long)options.budget.totalMs);
+
+    curl_easy_setopt(h, CURLOPT_XFERINFOFUNCTION, progressDecision);
+    curl_easy_setopt(h, CURLOPT_XFERINFODATA, state);
+    curl_easy_setopt(h, CURLOPT_NOPROGRESS, 0L);
+
+    // The SSRF guard already resolved this name and classified every address it
+    // returned. Pinning those addresses means one resolution and one
+    // classification; letting curl resolve again IS the rebinding window.
+    if (!options.pinnedAddresses.empty()) {
+        std::string entry = account.host;
+        entry += ":";
+        entry += std::to_string(effectivePort(account, protocols));
+        for (size_t i = 0; i < options.pinnedAddresses.size(); ++i) {
+            entry += (i == 0) ? ":" : ",";
+            entry += options.pinnedAddresses[i];
+        }
+        *resolveOut = curl_slist_append(nullptr, entry.c_str());
+        curl_easy_setopt(h, CURLOPT_RESOLVE, *resolveOut);
+    }
+}
+
+std::string urlFor(const char* scheme, const MailAccount& account, const std::string& path) {
+    std::string url = scheme;
+    url += "://";
+    url += account.host;
+    if (account.port != 0) {
+        url += ":";
+        url += std::to_string(account.port);
+    }
+    if (!path.empty()) {
+        url += "/";
+        url += path;
+    }
+    return url;
+}
+
+MailFailure classify(CURL* h, CURLcode rc, const char* errbuf, const TransferState& state,
+                     bool sideEffecting) {
+    long code = 0;
+    curl_easy_getinfo(h, CURLINFO_RESPONSE_CODE, &code);
+
+    if (rc == CURLE_ABORTED_BY_CALLBACK || rc == CURLE_WRITE_ERROR) {
+        // Our own callback stopped this, so the specific reason is known and
+        // must be reported instead of curl's generic one. "Too large" and
+        // "out of time" have different remedies, and a caller told the wrong
+        // one acts on the wrong thing.
+        if (state.abort == AbortReason::TooLarge)
+            return MailFailure{413, "mail_too_large",
+                               "the mail response exceeded the size this run may load", false};
+        if (state.abort == AbortReason::Deadline)
+            return MailFailure{504, "mail_timeout",
+                               "the mail operation ran out of its time budget", false};
+    }
+    return mailFailureFor(static_cast<int>(rc), code, errbuf, sideEffecting);
+}
+
+} // namespace
+
+std::string mailGlobalInit() {
+    const curl_version_info_data* info = curl_version_info(CURLVERSION_NOW);
+    if (info == nullptr) return "libcurl did not report its version information";
+    // Fail closed at boot. A curl without this flag is not safe to drive from a
+    // thread pool, and discovering that from a crash under load is far more
+    // expensive than refusing to start.
+    if ((info->features & CURL_VERSION_THREADSAFE) == 0)
+        return "libcurl was not built thread-safe (CURL_VERSION_THREADSAFE is absent), so the "
+               "mail surface cannot be served safely from the runner's thread pool";
+    if (curl_global_init(CURL_GLOBAL_DEFAULT) != CURLE_OK)
+        return "curl_global_init failed";
+    return {};
+}
+
+void mailGlobalCleanup() { curl_global_cleanup(); }
+
+struct ImapSession::Impl {
+    CURL* handle = nullptr;
+    curl_slist* resolve = nullptr;
+    char errbuf[CURL_ERROR_SIZE] = {0};
+    MailAccount account;
+    MailTransferOptions options;
+    TransferState state;
+
+    ~Impl() {
+        if (handle != nullptr) curl_easy_cleanup(handle);
+        if (resolve != nullptr) curl_slist_free_all(resolve);
+    }
+};
+
+ImapSession::ImapSession() : impl_(std::make_unique<Impl>()) {}
+ImapSession::~ImapSession() = default;
+
+AbortReason ImapSession::lastAbort() const { return impl_->state.abort; }
+
+MailFailure ImapSession::open(const MailAccount& account, const MailTransferOptions& options) {
+    impl_->account = account;
+    impl_->options = options;
+    impl_->handle = curl_easy_init();
+    if (impl_->handle == nullptr)
+        return MailFailure{503, "mail_unavailable", "could not create a mail client handle", false};
+
+    impl_->state.maxBytes = options.maxBytes;
+    impl_->state.nowMs = options.nowMs;
+    const int64_t now = options.nowMs ? options.nowMs() : defaultNowMs();
+    impl_->state.deadlineMs = options.budget.totalMs > 0 ? now + options.budget.totalMs : 0;
+
+    applyCommonOptions(impl_->handle, account, options, account.tls ? "imaps" : "imap",
+                       impl_->errbuf, &impl_->state, &impl_->resolve);
+    curl_easy_setopt(impl_->handle, CURLOPT_WRITEFUNCTION, writeToString);
+    curl_easy_setopt(impl_->handle, CURLOPT_WRITEDATA, &impl_->state);
+    return MailFailure{};
+}
+
+MailFailure ImapSession::command(const std::string& mailbox, const std::string& command,
+                                 std::string& responseOut) {
+    if (impl_->handle == nullptr)
+        return MailFailure{500, "mail_not_open", "the mail session was not opened", false};
+
+    responseOut.clear();
+    impl_->state.out = &responseOut;
+    impl_->state.abort = AbortReason::None;
+    impl_->errbuf[0] = '\0';
+
+    const std::string url = urlFor(impl_->account.tls ? "imaps" : "imap", impl_->account, mailbox);
+    curl_easy_setopt(impl_->handle, CURLOPT_URL, url.c_str());
+    curl_easy_setopt(impl_->handle, CURLOPT_CUSTOMREQUEST, command.c_str());
+
+    const CURLcode rc = curl_easy_perform(impl_->handle);
+    return classify(impl_->handle, rc, impl_->errbuf, impl_->state, false);
+}
+
+namespace {
+
+/// Feeds the rendered message to curl. Deliberately NOT dot-stuffing: curl does
+/// that itself, and a second pass would corrupt any line beginning with a
+/// period - including the single "." that would otherwise end the message early.
+struct UploadState {
+    const std::string* body = nullptr;
+    size_t offset = 0;
+};
+
+size_t readFromString(char* buffer, size_t size, size_t nitems, void* userdata) {
+    auto* st = static_cast<UploadState*>(userdata);
+    if (st->body == nullptr) return 0;
+    const size_t room = size * nitems;
+    const size_t left = st->body->size() - st->offset;
+    const size_t n = left < room ? left : room;
+    if (n > 0) {
+        std::memcpy(buffer, st->body->data() + st->offset, n);
+        st->offset += n;
+    }
+    return n;
+}
+
+} // namespace
+
+MailFailure smtpSend(const MailAccount& account, const MailTransferOptions& options,
+                     const MailEnvelope& envelope, const std::string& message) {
+    if (envelope.sender.empty())
+        return MailFailure{422, "mail_no_sender", "an envelope sender is required", false};
+    if (envelope.recipients.empty())
+        return MailFailure{422, "mail_no_recipient", "at least one recipient is required", false};
+
+    CURL* h = curl_easy_init();
+    if (h == nullptr)
+        return MailFailure{503, "mail_unavailable", "could not create a mail client handle", false};
+
+    char errbuf[CURL_ERROR_SIZE] = {0};
+    curl_slist* resolve = nullptr;
+    curl_slist* rcpts = nullptr;
+    std::string discard;
+    TransferState state;
+    state.out = &discard;
+    // The server's replies are small; the cap guards against a server that
+    // answers a send with an unbounded stream rather than against a real
+    // payload, so it is fixed rather than taken from the caller's read cap.
+    state.maxBytes = 64 * 1024;
+    state.nowMs = options.nowMs;
+    const int64_t now = options.nowMs ? options.nowMs() : defaultNowMs();
+    state.deadlineMs = options.budget.totalMs > 0 ? now + options.budget.totalMs : 0;
+
+    applyCommonOptions(h, account, options, account.tls ? "smtps" : "smtp", errbuf, &state,
+                       &resolve);
+
+    const std::string url = urlFor(account.tls ? "smtps" : "smtp", account, std::string());
+    curl_easy_setopt(h, CURLOPT_URL, url.c_str());
+    curl_easy_setopt(h, CURLOPT_MAIL_FROM, envelope.sender.c_str());
+    for (const std::string& r : envelope.recipients) rcpts = curl_slist_append(rcpts, r.c_str());
+    curl_easy_setopt(h, CURLOPT_MAIL_RCPT, rcpts);
+
+    UploadState upload;
+    upload.body = &message;
+    curl_easy_setopt(h, CURLOPT_UPLOAD, 1L);
+    curl_easy_setopt(h, CURLOPT_READFUNCTION, readFromString);
+    curl_easy_setopt(h, CURLOPT_READDATA, &upload);
+    curl_easy_setopt(h, CURLOPT_INFILESIZE_LARGE, (curl_off_t)message.size());
+    curl_easy_setopt(h, CURLOPT_WRITEFUNCTION, writeToString);
+    curl_easy_setopt(h, CURLOPT_WRITEDATA, &state);
+
+    const CURLcode rc = curl_easy_perform(h);
+    // sideEffecting: true. Past this point nothing is retryable, because the
+    // message may already have been accepted and a duplicate cannot be recalled.
+    MailFailure out = classify(h, rc, errbuf, state, true);
+
+    if (rcpts != nullptr) curl_slist_free_all(rcpts);
+    if (resolve != nullptr) curl_slist_free_all(resolve);
+    curl_easy_cleanup(h);
+    return out;
+}
+
+} // namespace svapi::runner::net

+ 128 - 0
runner/src/net/mail_session.hpp

@@ -0,0 +1,128 @@
+#pragma once
+#include <cstdint>
+#include <functional>
+#include <memory>
+#include <string>
+#include <vector>
+
+#include "net/curl_errors.hpp"
+#include "net/mail_budget.hpp"
+#include "net/xfer_abort.hpp"
+
+/// The curl-backed mail transport: an IMAP session and an SMTP send.
+///
+/// Everything above this line is pure and tested without a network
+/// (`imap_commands`, `imap_fetch`, `mime_build`, `mail_budget`, `xfer_abort`).
+/// This file is the only part that opens a socket, and it is deliberately thin
+/// for that reason: it drives curl and hands bytes to the parsers.
+namespace svapi::runner::net {
+
+/// Call ONCE from the runner's main, before any worker thread starts.
+///
+/// `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. It also verifies that libcurl was built thread-safe and
+/// REFUSES to continue otherwise, in the same spirit as the runner refusing to
+/// start with no token on a non-loopback bind: fail closed, at boot, where it
+/// is cheap. Returns an empty string on success, or the reason to abort.
+std::string mailGlobalInit();
+void mailGlobalCleanup();
+
+/// Where to connect and who to be. Credentials come from project secrets and
+/// nowhere else; this struct is the only way they enter the transport.
+struct MailAccount {
+    std::string host;
+    uint16_t port = 0;        ///< 0 means the scheme's default.
+    std::string user;
+    std::string password;
+    /// Implicit TLS (imaps/smtps) when true, which is the default and the only
+    /// mode we offer without an explicit opt-out. STARTTLS on a plaintext port
+    /// is the `startTls` variant; a wholly unencrypted session is possible only
+    /// by setting both to false, which the host layer must refuse to do on a
+    /// non-loopback host.
+    bool tls = true;
+    bool startTls = false;
+};
+
+/// The per-call bounds. `pinnedAddresses` is what makes the SSRF guard's
+/// decision binding: the guard resolved the name and classified EVERY address
+/// it returned, and these are the ones it approved. Handing them to curl means
+/// one resolution and one classification, where letting curl re-resolve would
+/// reopen the rebinding window the guard exists to close.
+struct MailTransferOptions {
+    MailBudget budget;
+    /// Largest response this run may load, in bytes. 0 means no cap, which no
+    /// tenant call should ever pass.
+    int64_t maxBytes = 0;
+    std::vector<std::string> pinnedAddresses;
+    /// Monotonic milliseconds, injected so the abort decision is testable.
+    std::function<int64_t()> nowMs;
+};
+
+/// One IMAP conversation on ONE connection.
+///
+/// One handle per (run, account), destroyed with the session. No sharing and no
+/// CURLSH: a handle carries connection state and credentials, so reusing one
+/// across tenants is a cross-tenant leak, and a fresh handle per command would
+/// mean a TCP connect, a TLS handshake and a LOGIN for every command - slow,
+/// and the behaviour that gets an account throttled or locked.
+class ImapSession {
+public:
+    ImapSession();
+    ~ImapSession();
+    ImapSession(const ImapSession&) = delete;
+    ImapSession& operator=(const ImapSession&) = delete;
+
+    /// Prepares the handle. Does not connect: curl connects on the first
+    /// command, so a credential error surfaces there rather than here.
+    MailFailure open(const MailAccount& account, const MailTransferOptions& options);
+
+    /// Runs one IMAP command through CURLOPT_CUSTOMREQUEST against `mailbox`,
+    /// returning the raw response bytes for the parsers above.
+    ///
+    /// CUSTOMREQUEST rather than curl's `;UID=<n>` URL form, and this is not a
+    /// style preference: the URL form ALWAYS sets \Seen on the fetched message.
+    /// Working around that by removing the flag afterwards is worse than the
+    /// disease - it removes a flag it did not necessarily 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. Measured in a sibling
+    /// implementation against a live server. One round trip with BODY.PEEK[]
+    /// touches no flag at all.
+    ///
+    /// `mailbox` is placed in the URL path, which is what makes curl issue the
+    /// SELECT. It must already be modified-UTF-7 encoded and URL-escaped by the
+    /// caller; this function does not encode it, because guessing which of
+    /// those two a name has already been through is how one gets applied twice.
+    MailFailure command(const std::string& mailbox, const std::string& command,
+                        std::string& responseOut);
+
+    /// The reason our own progress callback stopped a transfer, if it did.
+    /// Consulted when curl reports CURLE_ABORTED_BY_CALLBACK so the caller can
+    /// report "too large" rather than a misleading timeout.
+    AbortReason lastAbort() const;
+
+private:
+    struct Impl;
+    std::unique_ptr<Impl> impl_;
+};
+
+/// What goes on the wire for a send, kept apart from the message headers.
+///
+/// This is the RFC 5321 envelope, NOT the RFC 5322 headers, and conflating the
+/// two is the classic bug: `recipients` here MUST include every Bcc address,
+/// while the rendered message must carry no Bcc header at all.
+struct MailEnvelope {
+    std::string sender;
+    std::vector<std::string> recipients;
+};
+
+/// Send one message. `message` is the rendered RFC 5322 bytes, NOT dot-stuffed:
+/// curl does that itself, and doing it twice corrupts any line beginning with
+/// a period.
+///
+/// Classified as side-effecting throughout, so no failure from the moment the
+/// conversation could have reached delivery is reported as retryable.
+MailFailure smtpSend(const MailAccount& account, const MailTransferOptions& options,
+                     const MailEnvelope& envelope, const std::string& message);
+
+} // namespace svapi::runner::net

+ 465 - 0
runner/src/net/mime_build.cpp

@@ -0,0 +1,465 @@
+#include "net/mime_build.hpp"
+
+#include "functions/mime_base64.hpp"
+#include "functions/mime_words.hpp"
+
+#include <algorithm>
+
+namespace svapi::runner::net {
+
+using svapi::functions::MimeWords;
+
+namespace {
+
+constexpr char kHexUpper[] = "0123456789ABCDEF";
+
+/// RFC 5322 recommends no header line longer than 78 characters excluding the
+/// CRLF. The 998 limit is the one a server enforces; 78 is the one that keeps a
+/// raw message readable, and nothing costs anything by honouring it.
+constexpr std::size_t kHeaderWidth = 78;
+
+/// Quoted-printable allows 76 characters per line INCLUDING a trailing soft
+/// break, so 75 is the content budget.
+constexpr std::size_t kQpContentWidth = 75;
+
+constexpr std::size_t kBase64Width = 76;
+
+bool isFoldWhitespace(char c) { return c == ' ' || c == '\t' || c == '\r' || c == '\n'; }
+
+/// The one check this file exists to make. A CR or an LF in a value that
+/// reaches a header lets the caller write headers of its own - or end the
+/// header block and write a body - so it is refused rather than cleaned.
+void rejectBreaks(const std::string& field, const std::string& value) {
+    if (value.find('\r') != std::string::npos || value.find('\n') != std::string::npos)
+        throw MailBuildError(field, "must not contain CR or LF (header injection)");
+}
+
+/// Whether a header is one this builder owns. Accepting a caller's Content-Type
+/// would produce a message with two of them, and accepting a Bcc would undo
+/// the entire point of keeping the envelope separate.
+bool isReservedHeader(const std::string& name) {
+    std::string lower;
+    lower.reserve(name.size());
+    for (const unsigned char c : name)
+        lower.push_back(static_cast<char>(c >= 'A' && c <= 'Z' ? c + 32 : c));
+    return lower == "bcc" || lower == "mime-version" || lower == "content-type" ||
+           lower == "content-transfer-encoding" || lower == "content-disposition" ||
+           lower == "from" || lower == "to" || lower == "cc" || lower == "subject" ||
+           lower == "reply-to" || lower == "date" || lower == "message-id" ||
+           lower == "in-reply-to" || lower == "references";
+}
+
+/// Fold one header onto as many lines as it needs.
+///
+/// Folds only at whitespace between tokens, which is what keeps an encoded word
+/// intact: an `=?UTF-8?B?...?=` word contains no whitespace, so it is one
+/// token and cannot be split. Breaking one would leave both halves as literal
+/// text in the recipient's client. Any folding whitespace already in the value
+/// (MimeWords::encode folds a long value itself) is re-derived here so a single
+/// policy decides every line.
+///
+/// The FIRST token folds too, which is not decoration: RFC 2047 caps an
+/// encoded word at 75 characters without knowing what field name will precede
+/// it, so `Subject: ` plus a maximal word is 84 and over the line width before
+/// anything of ours is at fault. Moving it to a continuation line is the only
+/// fix available that does not split the word. A single token wider than the
+/// line even on its own is emitted over-long rather than mangled; it is still
+/// far under the 998 hard limit.
+std::string foldHeader(const std::string& name, const std::string& value) {
+    std::string out = name + ":";
+    std::size_t lineLen = out.size();
+    std::size_t i = 0;
+    while (i < value.size()) {
+        while (i < value.size() && isFoldWhitespace(value[i])) ++i;
+        if (i >= value.size()) break;
+        std::size_t j = i;
+        while (j < value.size() && !isFoldWhitespace(value[j])) ++j;
+        const std::string token = value.substr(i, j - i);
+        i = j;
+        if (lineLen > 1 && lineLen + 1 + token.size() > kHeaderWidth) {
+            out += "\r\n ";
+            lineLen = 1;
+        } else {
+            out += ' ';
+            lineLen += 1;
+        }
+        out += token;
+        lineLen += token.size();
+    }
+    return out + "\r\n";
+}
+
+/// Quoted-printable rather than base64 for text that is mostly ASCII, and the
+/// threshold is deliberately generous.
+///
+/// Quoted-printable costs 2 extra characters per escaped byte; base64 costs a
+/// third of the WHOLE body. On size alone they cross at about 18% escaped
+/// bytes, which would put an ordinary Hungarian sentence - a few accents among
+/// dozens of plain letters, around 20% of its bytes - on the wrong side of a
+/// line drawn there. Readability of the raw message is worth real money when a
+/// delivery complaint has to be diagnosed from a log, so the switch is at a
+/// third: the worst case inside that band is about 22% larger than base64
+/// would have been, and it is bounded. Past a third the body is effectively
+/// binary, there is nothing left to read, and base64 wins outright.
+bool preferQuotedPrintable(const std::string& text) {
+    std::size_t needsEscape = 0;
+    for (const unsigned char c : text) {
+        const bool literal = (c >= 33 && c <= 126 && c != '=') || c == ' ' || c == '\t' ||
+                             c == '\r' || c == '\n';
+        if (!literal) ++needsEscape;
+    }
+    return needsEscape * 3 <= text.size();
+}
+
+std::string quotedPrintable(const std::string& in) {
+    std::string out;
+    out.reserve(in.size() + in.size() / 4);
+    std::size_t lineLen = 0;
+
+    // Insert a soft break if `width` more characters would not fit. Called
+    // BEFORE writing, so a line never has to be edited afterwards.
+    const auto room = [&](std::size_t width) {
+        if (lineLen + width > kQpContentWidth) {
+            out += "=\r\n";
+            lineLen = 0;
+        }
+    };
+
+    for (std::size_t i = 0; i < in.size(); ++i) {
+        const unsigned char c = static_cast<unsigned char>(in[i]);
+
+        if (c == '\r' || c == '\n') {
+            // Any of CR, LF and CRLF in the input means one line break, and
+            // every line ending we emit is CRLF.
+            if (c == '\r' && i + 1 < in.size() && in[i + 1] == '\n') ++i;
+            out += "\r\n";
+            lineLen = 0;
+            continue;
+        }
+
+        if (c == ' ' || c == '\t') {
+            const bool trailing =
+                (i + 1 == in.size()) || in[i + 1] == '\r' || in[i + 1] == '\n';
+            if (trailing) {
+                // Whitespace at the end of a line MUST be encoded: transports
+                // are allowed to strip it, and a decoder would then produce
+                // different bytes than were sent.
+                room(3);
+                out += (c == ' ' ? "=20" : "=09");
+                lineLen += 3;
+            } else {
+                // Reserve 4: enough that the following character - at most 3
+                // wide - still fits on this line, so a literal space can never
+                // end up as the last character before a soft break, where it
+                // is just as strippable.
+                room(4);
+                out += static_cast<char>(c);
+                lineLen += 1;
+            }
+            continue;
+        }
+
+        if (c == '.') {
+            room(1);
+            if (lineLen == 0) {
+                // A line consisting of a single period ends the SMTP DATA
+                // phase. The bytes here are deliberately not dot-stuffed (the
+                // transport does that), so instead no line is ever allowed to
+                // BEGIN with a period: `=2E` decodes back to one and cannot be
+                // mistaken for the terminator by any layer, stuffing or not.
+                out += "=2E";
+                lineLen += 3;
+            } else {
+                out += '.';
+                lineLen += 1;
+            }
+            continue;
+        }
+
+        if (c >= 33 && c <= 126 && c != '=') {
+            room(1);
+            out += static_cast<char>(c);
+            lineLen += 1;
+            continue;
+        }
+
+        room(3);
+        out += '=';
+        out += kHexUpper[c >> 4];
+        out += kHexUpper[c & 0x0F];
+        lineLen += 3;
+    }
+
+    // A part body ends on a line ending, so the boundary that follows starts at
+    // the beginning of a line.
+    const bool endsWithCrlf = out.size() >= 2 && out.compare(out.size() - 2, 2, "\r\n") == 0;
+    if (!out.empty() && !endsWithCrlf) out += "\r\n";
+    return out;
+}
+
+std::string base64Lines(const std::string& raw) {
+    const std::string encoded = svapi::functions::mimeBase64Encode(raw);
+    std::string out;
+    out.reserve(encoded.size() + encoded.size() / kBase64Width * 2 + 2);
+    for (std::size_t i = 0; i < encoded.size(); i += kBase64Width) {
+        out += encoded.substr(i, kBase64Width);
+        out += "\r\n";
+    }
+    return out;
+}
+
+/// One MIME entity: its own headers and its already-encoded body.
+struct Part {
+    std::vector<std::pair<std::string, std::string>> headers;
+    std::string body;
+};
+
+std::string renderPart(const Part& part) {
+    std::string out;
+    for (const auto& [name, value] : part.headers) out += foldHeader(name, value);
+    out += "\r\n";
+    out += part.body;
+    return out;
+}
+
+Part textPart(const std::string& contentType, const std::string& text) {
+    Part part;
+    if (preferQuotedPrintable(text)) {
+        part.headers.emplace_back("Content-Type", contentType + "; charset=UTF-8");
+        part.headers.emplace_back("Content-Transfer-Encoding", "quoted-printable");
+        part.body = quotedPrintable(text);
+    } else {
+        part.headers.emplace_back("Content-Type", contentType + "; charset=UTF-8");
+        part.headers.emplace_back("Content-Transfer-Encoding", "base64");
+        part.body = base64Lines(text);
+    }
+    return part;
+}
+
+Part attachmentPart(const MailAttachment& attachment) {
+    const std::string type =
+        attachment.contentType.empty() ? "application/octet-stream" : attachment.contentType;
+    Part part;
+    // A filename is a MIME PARAMETER value, and RFC 2047 encoded words are not
+    // permitted in one (RFC 2047 section 5): a reader that finds
+    // `=?UTF-8?B?...?=` there is required to show it literally, so the user
+    // sees the encoding instead of the name. Parameters carry their charset
+    // themselves, via RFC 2231 `filename*=UTF-8''...`, which is what
+    // MimeWords::encodeParameter emits - together with a plain ASCII fallback
+    // for readers that never implemented 2231.
+    part.headers.emplace_back("Content-Type",
+                              type + "; " + MimeWords::encodeParameter("name", attachment.filename));
+    // Always base64: the content is arbitrary bytes. Quoted-printable cannot
+    // represent them cheaply (every byte over 126 triples) and a NUL or a lone
+    // CR would have to be escaped anyway.
+    part.headers.emplace_back("Content-Transfer-Encoding", "base64");
+    part.headers.emplace_back(
+        "Content-Disposition",
+        "attachment; " + MimeWords::encodeParameter("filename", attachment.filename));
+    part.body = base64Lines(attachment.content);
+    return part;
+}
+
+std::string multipartBody(const std::string& boundary, const std::vector<Part>& parts) {
+    // No preamble: nothing reads it, and every byte of it is a byte a test has
+    // to assert about.
+    std::string out;
+    for (const Part& part : parts) {
+        out += "--" + boundary + "\r\n";
+        out += renderPart(part);
+    }
+    out += "--" + boundary + "--\r\n";
+    return out;
+}
+
+/// Pick a boundary that does not occur anywhere in `content`.
+///
+/// A boundary that appears inside a part truncates the message at that point,
+/// and the result is a delivered mail that is missing its attachment, not an
+/// error anyone sees. Cheap to check, so it is checked - and the check is
+/// substring-anywhere rather than only at the start of a line, because being
+/// conservative here costs one regeneration and being precise costs a reader
+/// disagreeing with us about where a line starts.
+std::string pickBoundary(uint64_t seed, const std::string& content, unsigned& attempt) {
+    for (unsigned tries = 0; tries < 64; ++tries, ++attempt) {
+        const std::string candidate = mailBoundary(seed, attempt);
+        if (content.find(candidate) == std::string::npos) {
+            ++attempt;
+            return candidate;
+        }
+    }
+    throw MailBuildError("boundary", "no boundary could be found that the content does not contain");
+}
+
+/// The bare envelope address, validated. SMTP takes an address and nothing
+/// else, so whitespace or brackets surviving the extraction mean the input was
+/// not an address at all and the command would be malformed.
+std::string envelopeOf(const std::string& field, const std::string& address) {
+    rejectBreaks(field, address);
+    const std::string bare = MimeWords::envelopeAddress(address);
+    if (bare.empty()) throw MailBuildError(field, "is empty");
+    for (const unsigned char c : bare) {
+        if (c <= ' ' || c == '<' || c == '>' || c == 0x7F)
+            throw MailBuildError(field, "is not a bare address: " + bare);
+    }
+    return bare;
+}
+
+std::string addressList(const std::string& field, const std::vector<std::string>& addresses) {
+    std::string out;
+    for (const std::string& address : addresses) {
+        rejectBreaks(field, address);
+        if (!out.empty()) out += ", ";
+        out += MimeWords::encodeAddress(address);
+    }
+    return out;
+}
+
+} // namespace
+
+std::string mailBoundary(uint64_t seed, unsigned attempt) {
+    // splitmix64, so one seed yields a well-distributed sequence of candidates
+    // without pulling in <random> or depending on a library's generator
+    // staying bit-identical across versions - which the determinism of these
+    // bytes relies on.
+    uint64_t x = seed + 0x9E3779B97F4A7C15ULL * (static_cast<uint64_t>(attempt) + 1);
+    x ^= x >> 30;
+    x *= 0xBF58476D1CE4E5B9ULL;
+    x ^= x >> 27;
+    x *= 0x94D049BB133111EBULL;
+    x ^= x >> 31;
+
+    std::string hex(16, '0');
+    for (int i = 15; i >= 0; --i) {
+        hex[static_cast<std::size_t>(i)] = kHexUpper[x & 0x0F];
+        x >>= 4;
+    }
+    return "=_svapi_" + hex;
+}
+
+BuiltMail buildMail(const MailMessage& msg, uint64_t boundarySeed) {
+    BuiltMail built;
+
+    built.envelopeFrom = envelopeOf("from", msg.from);
+
+    const auto addRecipients = [&](const std::string& field,
+                                   const std::vector<std::string>& addresses) {
+        for (const std::string& address : addresses) {
+            const std::string bare = envelopeOf(field, address);
+            if (std::find(built.envelopeRecipients.begin(), built.envelopeRecipients.end(),
+                          bare) == built.envelopeRecipients.end())
+                built.envelopeRecipients.push_back(bare);
+        }
+    };
+    addRecipients("to", msg.to);
+    addRecipients("cc", msg.cc);
+    addRecipients("bcc", msg.bcc);
+    if (built.envelopeRecipients.empty())
+        throw MailBuildError("to", "at least one recipient is required");
+
+    rejectBreaks("subject", msg.subject);
+    rejectBreaks("messageId", msg.messageId);
+    rejectBreaks("date", msg.date);
+    rejectBreaks("inReplyTo", msg.inReplyTo);
+    rejectBreaks("references", msg.references);
+
+    std::vector<std::pair<std::string, std::string>> headers;
+    if (!msg.date.empty()) headers.emplace_back("Date", msg.date);
+    headers.emplace_back("From", MimeWords::encodeAddress(msg.from));
+    if (!msg.to.empty()) headers.emplace_back("To", addressList("to", msg.to));
+    if (!msg.cc.empty()) headers.emplace_back("Cc", addressList("cc", msg.cc));
+    if (!msg.replyTo.empty()) {
+        rejectBreaks("replyTo", msg.replyTo);
+        headers.emplace_back("Reply-To", MimeWords::encodeAddress(msg.replyTo));
+    }
+    // Bcc is absent by construction: it is never put into `headers` at all,
+    // rather than added and removed later, so no future edit can reinstate it
+    // by accident.
+    headers.emplace_back("Subject", MimeWords::encode(msg.subject));
+    if (!msg.messageId.empty()) headers.emplace_back("Message-ID", msg.messageId);
+    if (!msg.inReplyTo.empty()) headers.emplace_back("In-Reply-To", msg.inReplyTo);
+    if (!msg.references.empty()) headers.emplace_back("References", msg.references);
+
+    for (const MailHeader& header : msg.headers) {
+        if (header.name.empty()) throw MailBuildError("header", "name is empty");
+        rejectBreaks("header name", header.name);
+        rejectBreaks("header value", header.value);
+        for (const unsigned char c : header.name) {
+            // RFC 5322 field names are printable ASCII without a colon. A
+            // colon would make the rest of the name parse as a value, which is
+            // injection by another route.
+            if (c < 33 || c > 126 || c == ':')
+                throw MailBuildError("header name", "invalid character in " + header.name);
+        }
+        if (isReservedHeader(header.name))
+            throw MailBuildError("header name", header.name + " is set by the builder");
+        headers.emplace_back(header.name, MimeWords::encode(header.value));
+    }
+
+    for (const MailAttachment& attachment : msg.attachments) {
+        if (attachment.filename.empty()) throw MailBuildError("attachment", "filename is empty");
+        rejectBreaks("attachment filename", attachment.filename);
+        rejectBreaks("attachment contentType", attachment.contentType);
+        if (attachment.contentType.find(';') != std::string::npos)
+            throw MailBuildError("attachment contentType",
+                                 "must not carry parameters: " + attachment.contentType);
+    }
+
+    // Body structure. A single part is emitted as a single part: a
+    // multipart wrapper around one entity is legal but every reader has to
+    // unwrap it, and it makes the message harder to read and to test.
+    Part body = textPart("text/plain", msg.text);
+    if (!msg.html.empty() && msg.text.empty()) {
+        body = textPart("text/html", msg.html);
+    } else if (!msg.html.empty()) {
+        const std::vector<Part> alternatives = {textPart("text/plain", msg.text),
+                                                textPart("text/html", msg.html)};
+        std::string content;
+        for (const Part& part : alternatives) content += renderPart(part);
+
+        unsigned attempt = 0;
+        const std::string boundary = pickBoundary(boundarySeed, content, attempt);
+        built.boundaries.push_back(boundary);
+
+        Part wrapper;
+        wrapper.headers.emplace_back("Content-Type",
+                                     "multipart/alternative; boundary=\"" + boundary + "\"");
+        wrapper.body = multipartBody(boundary, alternatives);
+        body = wrapper;
+    }
+
+    if (!msg.attachments.empty()) {
+        // The text (or the alternative set) is the FIRST part of the mixed
+        // wrapper: a reader shows the leading part as the message and the rest
+        // as attachments, and a reader that shows parts in order would
+        // otherwise put the body after the files.
+        std::vector<Part> mixed = {body};
+        for (const MailAttachment& attachment : msg.attachments)
+            mixed.push_back(attachmentPart(attachment));
+
+        std::string content;
+        for (const Part& part : mixed) content += renderPart(part);
+        for (const std::string& inner : built.boundaries) content += inner;
+
+        unsigned attempt = 0;
+        const std::string boundary = pickBoundary(boundarySeed, content, attempt);
+        // Outermost first.
+        built.boundaries.insert(built.boundaries.begin(), boundary);
+
+        Part wrapper;
+        wrapper.headers.emplace_back("Content-Type",
+                                     "multipart/mixed; boundary=\"" + boundary + "\"");
+        wrapper.body = multipartBody(boundary, mixed);
+        body = wrapper;
+    }
+
+    headers.emplace_back("MIME-Version", "1.0");
+    for (const auto& partHeader : body.headers) headers.push_back(partHeader);
+
+    for (const auto& [name, value] : headers) built.data += foldHeader(name, value);
+    built.data += "\r\n";
+    built.data += body.body;
+    return built;
+}
+
+} // namespace svapi::runner::net

+ 138 - 0
runner/src/net/mime_build.hpp

@@ -0,0 +1,138 @@
+#pragma once
+#include <cstdint>
+#include <stdexcept>
+#include <string>
+#include <vector>
+
+/// Assembling an outgoing message: a structured description in, the exact bytes
+/// that go after SMTP DATA out, plus the envelope as its own value.
+///
+/// Pure. No sockets, no curl, no clock, no settings, no randomness of its own.
+/// Everything that makes a message non-deterministic is a parameter, so the
+/// bytes are reproducible and the tests can assert on them exactly.
+///
+/// THE ENVELOPE AND THE HEADERS ARE DIFFERENT THINGS, and conflating them is
+/// the classic bug in this area. RFC 5321 MAIL FROM / RCPT TO decide where the
+/// message actually goes; the RFC 5322 From/To/Cc headers are display text that
+/// a sender is free to make say anything. They are returned separately here
+/// precisely so no caller can derive one from the other by re-parsing: Bcc
+/// recipients exist ONLY in the envelope, and a Bcc that reaches a header is a
+/// disclosure of one recipient to another.
+///
+/// THIS IS THE INJECTION BOUNDARY. Every field that can reach a header is
+/// refused if it contains CR or LF, by name, rather than being sanitised: a
+/// caller that silently gets a different message than it asked for cannot tell
+/// that it tried to inject, and stripping a newline out of an address usually
+/// means the address itself was already wrong.
+namespace svapi::runner::net {
+
+/// Refused input. Never a partially built message: a broken message is
+/// delivered and then puzzled over, while a refusal is read.
+class MailBuildError : public std::runtime_error {
+public:
+    MailBuildError(std::string field, const std::string& why)
+        : std::runtime_error(field + ": " + why), field_(std::move(field)) {}
+
+    /// Which input was at fault, for a caller that wants to report it without
+    /// matching on message text.
+    const std::string& field() const noexcept { return field_; }
+
+private:
+    std::string field_;
+};
+
+struct MailAttachment {
+    /// Shown to the recipient. May be non-ASCII; see the RFC 2231 note in the
+    /// implementation for why a filename is not an encoded-word problem.
+    std::string filename;
+    /// Empty becomes application/octet-stream, which is what an unknown type
+    /// means and is safer than guessing from the extension.
+    std::string contentType;
+    /// Raw bytes, NOT base64. Binary is expected and NUL is fine.
+    std::string content;
+};
+
+/// An extra header, supplied in full by the caller. Structural headers
+/// (MIME-Version, Content-*, and Bcc) are refused here rather than merged -
+/// two Content-Type headers is not a message any reader agrees about.
+struct MailHeader {
+    std::string name;
+    std::string value;
+};
+
+struct MailMessage {
+    /// `a@b` or `Display Name <a@b>`. The display name is encoded if needed;
+    /// the address inside the angle brackets goes out verbatim.
+    std::string from;
+    std::vector<std::string> to;
+    std::vector<std::string> cc;
+    /// Envelope recipients that appear in NO header.
+    std::vector<std::string> bcc;
+    /// Optional, single address.
+    std::string replyTo;
+    std::string subject;
+    /// The text/plain body. UTF-8.
+    std::string text;
+    /// Optional text/html alternative. Non-empty selects multipart/alternative.
+    std::string html;
+    std::vector<MailAttachment> attachments;
+    std::vector<MailHeader> headers;
+
+    /// All optional and all emitted verbatim when set. There is no clock in
+    /// this layer, so an empty `date` or `messageId` means the header is simply
+    /// absent and the submission server stamps its own - which RFC 5321
+    /// permits and every submission service does. A sender that wants control
+    /// of either supplies it.
+    std::string messageId;
+    std::string date;
+    std::string inReplyTo;
+    std::string references;
+};
+
+struct BuiltMail {
+    /// The bare address for MAIL FROM: no display name, no angle brackets, no
+    /// encoding. Handing SMTP the display-name form produces a malformed
+    /// command and the server drops the connection.
+    std::string envelopeFrom;
+    /// The bare addresses for RCPT TO, in to/cc/bcc order, deduplicated -
+    /// a repeated RCPT TO risks a second delivery and counts twice against a
+    /// provider's rate limit.
+    std::vector<std::string> envelopeRecipients;
+
+    /// The message itself: headers, a blank line, body. CRLF everywhere.
+    ///
+    /// NOT DOT-STUFFED, deliberately. libcurl's SMTP transport stuffs the
+    /// payload it is given, so stuffing here would deliver every line
+    /// beginning with a period with an extra one. The caller MUST NOT stuff
+    /// either unless it speaks raw SMTP itself. A line consisting of a single
+    /// period terminates the DATA phase early, truncating the message and
+    /// turning the remainder into garbage commands, so the body encoders here
+    /// additionally never emit a bare `.` line in the first place: see the
+    /// `=2E` note in the implementation. That protection is independent of
+    /// stuffing and holds whichever layer does it.
+    std::string data;
+
+    /// The boundaries actually used, outermost first. Returned because a test
+    /// (and a bug report) needs to know which candidate survived the collision
+    /// check. Empty for a single-part message.
+    std::vector<std::string> boundaries;
+};
+
+/// A boundary candidate derived from `seed` and `attempt`. Exposed because
+/// `buildMail` regenerates on collision, and the only way to test that is to
+/// put the first candidate into the body on purpose.
+///
+/// `=_` can never occur in either body encoding used here (quoted-printable
+/// emits `=` only as `=XX` or at a line end, base64 has neither character), so
+/// a collision is effectively impossible - which is exactly why the check must
+/// be tested rather than trusted.
+std::string mailBoundary(uint64_t seed, unsigned attempt);
+
+/// Render `msg`, or throw `MailBuildError`.
+///
+/// `boundarySeed` is the only source of variation: the same message and seed
+/// always produce identical bytes. A real sender passes something unpredictable
+/// per message; a test passes a constant.
+BuiltMail buildMail(const MailMessage& msg, uint64_t boundarySeed);
+
+} // namespace svapi::runner::net

+ 43 - 0
runner/src/net/xfer_abort.hpp

@@ -0,0 +1,43 @@
+#pragma once
+#include <cstdint>
+
+/// The decision a progress callback makes, as a pure function.
+///
+/// libcurl calls a progress callback periodically during a transfer and aborts
+/// the transfer if it returns non-zero. That callback is the ONLY way to stop a
+/// transfer that is making slow progress, because the per-phase connect and
+/// read timeouts bound quiet periods and not the sum of them: a server that
+/// dribbles one byte inside every read timeout never trips either.
+///
+/// The decision lives here, separate from the callback, because a callback that
+/// contains the logic can only be tested by arranging a real slow server. As a
+/// pure function of (deadline, now, bytes so far, cap) every edge is an
+/// ordinary unit test.
+namespace svapi::runner::net {
+
+enum class AbortReason {
+    None,
+    /// The session's whole-conversation budget is spent. Reported as a timeout.
+    Deadline,
+    /// The transfer is larger than this run may load. Reported as too large,
+    /// NOT as a timeout: the remedies differ, and a caller told "timeout" for
+    /// an oversized mailbox will retry forever.
+    TooLarge,
+};
+
+/// `capBytes` of 0 means no size cap. `deadlineMs` of 0 means no deadline,
+/// which a caller should never pass for a tenant run - it is accepted only so
+/// that an internal, already-bounded call can opt out explicitly.
+///
+/// The comparison is `>=` on the deadline so that a budget of exactly zero
+/// remaining aborts rather than being allowed one more callback interval, and
+/// `>` on the size so that a transfer of exactly the cap is permitted. A file
+/// of exactly the limit is within the limit; a deadline of exactly now is not.
+inline AbortReason shouldAbortTransfer(int64_t deadlineMs, int64_t nowMs, int64_t bytesSoFar,
+                                       int64_t capBytes) {
+    if (capBytes > 0 && bytesSoFar > capBytes) return AbortReason::TooLarge;
+    if (deadlineMs > 0 && nowMs >= deadlineMs) return AbortReason::Deadline;
+    return AbortReason::None;
+}
+
+} // namespace svapi::runner::net

+ 268 - 0
runner/tests/fake_mail_server.hpp

@@ -0,0 +1,268 @@
+#pragma once
+#include <arpa/inet.h>
+#include <netinet/in.h>
+#include <sys/socket.h>
+#include <unistd.h>
+
+#include <atomic>
+#include <mutex>
+#include <string>
+#include <thread>
+#include <vector>
+
+/// In-process fake IMAP and SMTP servers for the mail transport tests.
+///
+/// Committed rather than written by hand each time: the facts about what curl
+/// actually puts on the wire, and what its callbacks actually receive, were
+/// established with a throwaway harness, and the next person needs to be able
+/// to re-establish something similar without rebuilding one.
+///
+/// A plain TCP listener on an EPHEMERAL port, in process. Ephemeral rather than
+/// a chosen number because a fixed port collides with whatever else is
+/// listening - twice during this feature's development a test reached a stale
+/// server from an earlier run and "passed" against the wrong process.
+///
+/// CREDENTIALS ARE NEVER LOGGED. `received()` masks the argument of LOGIN and
+/// of SMTP AUTH before storing it. An earlier version of this harness recorded
+/// the password in plaintext in its transcript, which is exactly the kind of
+/// thing that survives in a CI log forever.
+namespace svapi::testing {
+
+class FakeLineServer {
+public:
+    FakeLineServer() = default;
+    virtual ~FakeLineServer() { stop(); }
+
+    bool start() {
+        fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
+        if (fd_ < 0) return false;
+        int yes = 1;
+        ::setsockopt(fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
+        sockaddr_in addr{};
+        addr.sin_family = AF_INET;
+        addr.sin_addr.s_addr = ::htonl(INADDR_LOOPBACK);
+        addr.sin_port = 0;  // ephemeral
+        if (::bind(fd_, reinterpret_cast<sockaddr*>(&addr), sizeof(addr)) != 0) return false;
+        if (::listen(fd_, 4) != 0) return false;
+        sockaddr_in bound{};
+        socklen_t len = sizeof(bound);
+        if (::getsockname(fd_, reinterpret_cast<sockaddr*>(&bound), &len) != 0) return false;
+        port_ = ::ntohs(bound.sin_port);
+        running_ = true;
+        thread_ = std::thread([this] { acceptLoop(); });
+        return true;
+    }
+
+    void stop() {
+        running_ = false;
+        if (fd_ >= 0) {
+            ::shutdown(fd_, SHUT_RDWR);
+            ::close(fd_);
+            fd_ = -1;
+        }
+        if (thread_.joinable()) thread_.join();
+    }
+
+    uint16_t port() const { return port_; }
+
+    std::vector<std::string> received() const {
+        std::lock_guard<std::mutex> lock(mutex_);
+        return received_;
+    }
+
+protected:
+    /// Answer one client line. Return the bytes to send back, which may be
+    /// several IMAP/SMTP lines at once.
+    virtual std::string respond(const std::string& line, bool& closeAfter) = 0;
+    /// Sent as soon as a client connects.
+    virtual std::string greeting() = 0;
+
+    /// Strip anything that must not reach a log. Subclasses extend this.
+    virtual std::string mask(const std::string& line) const { return line; }
+
+    void record(const std::string& line) {
+        std::lock_guard<std::mutex> lock(mutex_);
+        received_.push_back(mask(line));
+    }
+
+private:
+    void acceptLoop() {
+        while (running_) {
+            int client = ::accept(fd_, nullptr, nullptr);
+            if (client < 0) return;
+            serve(client);
+            ::close(client);
+        }
+    }
+
+    void serve(int client) {
+        const std::string hello = greeting();
+        if (!hello.empty()) ::send(client, hello.data(), hello.size(), 0);
+
+        std::string buffer;
+        char chunk[4096];
+        while (running_) {
+            const ssize_t n = ::recv(client, chunk, sizeof(chunk), 0);
+            if (n <= 0) return;
+            buffer.append(chunk, static_cast<size_t>(n));
+
+            size_t nl;
+            while ((nl = buffer.find("\r\n")) != std::string::npos) {
+                const std::string line = buffer.substr(0, nl);
+                buffer.erase(0, nl + 2);
+                record(line);
+                bool closeAfter = false;
+                const std::string reply = respond(line, closeAfter);
+                if (!reply.empty()) ::send(client, reply.data(), reply.size(), 0);
+                if (closeAfter) return;
+            }
+        }
+    }
+
+    int fd_ = -1;
+    uint16_t port_ = 0;
+    std::atomic<bool> running_{false};
+    std::thread thread_;
+    mutable std::mutex mutex_;
+    std::vector<std::string> received_;
+};
+
+/// A fake IMAP server answering just enough for a mailbox read.
+class FakeImapServer : public FakeLineServer {
+public:
+    /// What a UID FETCH returns as the message body.
+    std::string messageBody = "From: a@example.com\r\nSubject: hello\r\n\r\nbody text\r\n";
+    /// Untagged lines emitted on SELECT/EXAMINE. These exist so a test can
+    /// observe WHERE they end up: whether curl hands a custom request's caller
+    /// the SELECT chatter as well as the command's own response.
+    std::string selectUntagged =
+        "* 3 EXISTS\r\n* FLAGS (\\Seen \\Answered)\r\n* OK [UIDVALIDITY 1] Ok\r\n";
+
+protected:
+    std::string greeting() override { return "* OK [CAPABILITY IMAP4rev1] fake ready\r\n"; }
+
+    std::string mask(const std::string& line) const override {
+        // "A002 LOGIN user secret" must never be recorded verbatim.
+        const size_t at = upperFind(line, " LOGIN ");
+        if (at == std::string::npos) return line;
+        return line.substr(0, at) + " LOGIN <masked>";
+    }
+
+    std::string respond(const std::string& line, bool& closeAfter) override {
+        const std::string tag = line.substr(0, line.find(' '));
+        const std::string rest = line.size() > tag.size() ? line.substr(tag.size() + 1) : "";
+
+        if (upperFind(rest, "CAPABILITY") == 0)
+            return "* CAPABILITY IMAP4rev1\r\n" + tag + " OK done\r\n";
+        if (upperFind(rest, "LOGIN") == 0) return tag + " OK logged in\r\n";
+        if (upperFind(rest, "SELECT") == 0 || upperFind(rest, "EXAMINE") == 0)
+            return selectUntagged + tag + " OK [READ-ONLY] selected\r\n";
+        if (upperFind(rest, "UID FETCH") == 0) {
+            // The response to a BODY.PEEK[] fetch comes back labelled BODY[],
+            // without the .PEEK. A parser that looks for the string it sent
+            // will not find it, which is a real and easily missed trap.
+            std::string out = "* 1 FETCH (UID 7 BODY[] {" + std::to_string(messageBody.size()) +
+                              "}\r\n" + messageBody + ")\r\n";
+            return out + tag + " OK fetched\r\n";
+        }
+        if (upperFind(rest, "UID SEARCH") == 0)
+            return "* SEARCH 7 9 11\r\n" + tag + " OK searched\r\n";
+        if (upperFind(rest, "LIST") == 0)
+            return "* LIST (\\HasNoChildren) \"/\" INBOX\r\n" + tag + " OK listed\r\n";
+        if (upperFind(rest, "LOGOUT") == 0) {
+            closeAfter = true;
+            return "* BYE\r\n" + tag + " OK logged out\r\n";
+        }
+        return tag + " BAD unknown command\r\n";
+    }
+
+private:
+    static size_t upperFind(const std::string& haystack, const std::string& needle) {
+        std::string up;
+        up.reserve(haystack.size());
+        for (char c : haystack) up.push_back(static_cast<char>(::toupper(c)));
+        return up.find(needle);
+    }
+};
+
+/// A fake SMTP server accepting one message.
+class FakeSmtpServer : public FakeLineServer {
+public:
+    /// The message body as received, after the DATA phase.
+    std::string dataReceived() const {
+        std::lock_guard<std::mutex> lock(dataMutex_);
+        return data_;
+    }
+    /// What to answer the DATA terminator with, so a test can drive a refusal.
+    std::string dataOutcome = "250 2.0.0 Ok: queued\r\n";
+
+protected:
+    std::string greeting() override { return "220 fake.example.com ESMTP ready\r\n"; }
+
+    std::string mask(const std::string& line) const override {
+        if (line.rfind("AUTH", 0) == 0) return "AUTH <masked>";
+        // During the DATA phase the lines are the message, not commands, and
+        // the message is the test's own fixture - but an AUTH continuation
+        // response is a bare base64 blob with no keyword, so anything arriving
+        // while awaiting one is masked too.
+        if (awaitingAuthResponse_) return "<masked auth response>";
+        return line;
+    }
+
+    std::string respond(const std::string& line, bool& closeAfter) override {
+        if (inData_) {
+            if (line == ".") {
+                inData_ = false;
+                return dataOutcome;
+            }
+            // UN-STUFF, because a real receiver does. curl stuffs the payload
+            // it is given, so a body line of "." arrives as ".." and a
+            // receiver that stored it verbatim would make a correct client
+            // look like it had double-stuffed. Measured: curl does stuff.
+            std::string content = line;
+            if (content.size() > 1 && content[0] == '.') content.erase(0, 1);
+            std::lock_guard<std::mutex> lock(dataMutex_);
+            data_ += content;
+            data_ += "\r\n";
+            return "";
+        }
+        if (awaitingAuthResponse_) {
+            awaitingAuthResponse_ = false;
+            return "235 2.7.0 Authentication successful\r\n";
+        }
+        if (line.rfind("EHLO", 0) == 0 || line.rfind("HELO", 0) == 0)
+            return "250-fake.example.com\r\n250-SIZE 35882577\r\n250-AUTH PLAIN LOGIN\r\n250 "
+                   "8BITMIME\r\n";
+        if (line.rfind("AUTH", 0) == 0) {
+            // A bare "AUTH PLAIN" with no initial response must be answered
+            // with a 334 challenge, NOT with a 235 success. Answering 235 here
+            // made an earlier harness report a working login for a client that
+            // had not actually sent credentials.
+            const bool hasInitialResponse = line.find(' ', 5) != std::string::npos;
+            if (!hasInitialResponse) {
+                awaitingAuthResponse_ = true;
+                return "334 \r\n";
+            }
+            return "235 2.7.0 Authentication successful\r\n";
+        }
+        if (line.rfind("MAIL FROM", 0) == 0) return "250 2.1.0 Ok\r\n";
+        if (line.rfind("RCPT TO", 0) == 0) return "250 2.1.5 Ok\r\n";
+        if (line.rfind("DATA", 0) == 0) {
+            inData_ = true;
+            return "354 End data with <CR><LF>.<CR><LF>\r\n";
+        }
+        if (line.rfind("QUIT", 0) == 0) {
+            closeAfter = true;
+            return "221 2.0.0 Bye\r\n";
+        }
+        return "500 5.5.1 Unrecognized\r\n";
+    }
+
+private:
+    bool inData_ = false;
+    bool awaitingAuthResponse_ = false;
+    mutable std::mutex dataMutex_;
+    std::string data_;
+};
+
+} // namespace svapi::testing

+ 598 - 0
runner/tests/imap_commands_test.cpp

@@ -0,0 +1,598 @@
+// Building IMAP commands from tenant-supplied values.
+//
+// This is a protocol-injection boundary, so most of what follows is adversarial:
+// a mailbox name or a search term comes from a script, CRLF ends an IMAP
+// command, and there is no parser between us and the server to catch a value
+// that is secretly two commands. Every assertion is on the EXACT bytes,
+// trailing CRLF included - a test that checked for a substring would pass
+// against a command with an extra command appended to it.
+#include <gtest/gtest.h>
+
+#include <functional>
+#include <set>
+#include <string>
+#include <vector>
+
+#include "net/imap_commands.hpp"
+
+using namespace svapi::runner::net;
+
+namespace {
+
+/// The whole exchange as one string. Only safe in a test: see the header note
+/// on why a client must never write this.
+std::string wire(const ImapCommand& c) { return c.joined(); }
+
+/// The field a refusal named, so a test can assert the script author is told
+/// which of its arguments was the problem.
+std::string refusedField(const std::function<void()>& fn) {
+    try {
+        fn();
+    } catch (const ImapCommandError& e) {
+        return e.field();
+    }
+    return "<no error>";
+}
+
+} // namespace
+
+// --- Quoting and escaping -------------------------------------------------
+
+TEST(ImapQuote, WrapsAPlainValueInQuotes) {
+    EXPECT_EQ(imapQuote("Sent Items"), "\"Sent Items\"");
+}
+
+TEST(ImapQuote, EscapesBothTheQuoteAndTheBackslash) {
+    EXPECT_EQ(imapQuote("a\"b"), "\"a\\\"b\"");
+    EXPECT_EQ(imapQuote("a\\b"), "\"a\\\\b\"");
+}
+
+TEST(ImapQuote, ATrailingBackslashCannotEscapeTheClosingQuote) {
+    // The classic quote-break: if only `"` were escaped, this would emit
+    // "...\" and the closing quote would be consumed as an escape, running the
+    // remainder of the command as protocol.
+    EXPECT_EQ(imapQuote("evil\\"), "\"evil\\\\\"");
+}
+
+TEST(ImapQuote, RefusesAValueThatCannotLegallyBeQuoted) {
+    EXPECT_THROW(imapQuote("a\rb"), ImapCommandError);
+    EXPECT_THROW(imapQuote("a\nb"), ImapCommandError);
+    EXPECT_THROW(imapQuote(std::string("a\0b", 3)), ImapCommandError);
+    EXPECT_THROW(imapQuote("Szem\xc3\xa9t"), ImapCommandError) << "8-bit is literal territory";
+}
+
+TEST(ImapQuote, EmptyIsTheEmptyQuotedString) {
+    EXPECT_EQ(imapQuote(""), "\"\"");
+}
+
+// --- Choosing the form ----------------------------------------------------
+
+TEST(ImapEncodeArg, APlainWordGoesOutAsABareAtom) {
+    const ImapArg a = imapEncodeArg("INBOX");
+    EXPECT_EQ(a.form, ImapArgForm::Atom);
+    EXPECT_EQ(a.head, "INBOX");
+    EXPECT_TRUE(a.payload.empty());
+}
+
+TEST(ImapEncodeArg, AtomSpecialsForceAQuotedString) {
+    for (const char* v : {"Sent Items", "a(b", "a)b", "a{b", "a%b", "a*b", "a]b"}) {
+        const ImapArg a = imapEncodeArg(v);
+        EXPECT_EQ(a.form, ImapArgForm::Quoted) << v << " must not go out as an atom";
+    }
+}
+
+TEST(ImapEncodeArg, AnEmptyValueIsQuotedNeverABareAtom) {
+    // A bare empty atom would vanish and shift every following argument one
+    // position left, which is a different command, not a malformed one.
+    const ImapArg a = imapEncodeArg("");
+    EXPECT_EQ(a.form, ImapArgForm::Quoted);
+    EXPECT_EQ(a.head, "\"\"");
+}
+
+TEST(ImapEncodeArg, EightBitBytesForceALiteral) {
+    const ImapArg a = imapEncodeArg("Be\xc3\xa9rkezett");
+    EXPECT_EQ(a.form, ImapArgForm::Literal);
+    EXPECT_TRUE(a.isLiteral());
+}
+
+TEST(ImapEncodeArg, TheLiteralCountIsOctetsNotCharacters) {
+    // "Beérkezett" is 10 characters and 11 octets in UTF-8. A count of 10 would
+    // leave one byte of the name on the wire as the start of the next command,
+    // which is an injection primitive and not merely a parse error.
+    const std::string name = "Be\xc3\xa9rkezett";
+    ASSERT_EQ(name.size(), 11u);
+    const ImapArg a = imapEncodeArg(name);
+    EXPECT_EQ(a.head, "{11}\r\n");
+    EXPECT_EQ(a.payload, name);
+    EXPECT_EQ(a.payload.size(), 11u);
+}
+
+TEST(ImapEncodeArg, ALiteralCountMatchesThePayloadForEveryAccentedName) {
+    for (const char* v : {"Szem\xc3\xa9t", "Be\xc3\xa9rkezett", "\xc3\x81rv\xc3\xadzt\xc5\xb1r\xc5\x91",
+                          "\xf0\x9f\x93\xac"}) {
+        const ImapArg a = imapEncodeArg(v);
+        ASSERT_EQ(a.form, ImapArgForm::Literal) << v;
+        EXPECT_EQ(a.head, "{" + std::to_string(std::string(v).size()) + "}\r\n");
+        EXPECT_EQ(a.payload, std::string(v));
+    }
+}
+
+TEST(ImapEncodeArg, ALiteralSplitsTheCommandIntoAWaitingExchange) {
+    // The literal is visible in the API because it changes the exchange: the
+    // client must stop after `{n}\r\n` and wait for the server's `+`.
+    const ImapCommand c =
+        imapBuildCommand("A001", "LOGIN", {imapEncodeArg("bob"), imapEncodeArg("p\xc3\xa1ssw")});
+    ASSERT_TRUE(c.needsContinuation());
+    ASSERT_EQ(c.chunks.size(), 2u);
+    EXPECT_EQ(c.chunks[0], "A001 LOGIN bob {6}\r\n");
+    EXPECT_EQ(c.chunks[1], "p\xc3\xa1ssw\r\n");
+}
+
+TEST(ImapEncodeArg, ACommandWithNoLiteralIsASingleChunk) {
+    const ImapCommand c = imapCapability("A001");
+    EXPECT_FALSE(c.needsContinuation());
+    ASSERT_EQ(c.chunks.size(), 1u);
+}
+
+// --- Modified UTF-7 -------------------------------------------------------
+
+TEST(ModifiedUtf7, PrintableAsciiPassesThroughUnchanged) {
+    EXPECT_EQ(toModifiedUtf7("INBOX"), "INBOX");
+    EXPECT_EQ(toModifiedUtf7("INBOX/Sent Items"), "INBOX/Sent Items");
+}
+
+TEST(ModifiedUtf7, ALiteralAmpersandBecomesAmpersandDash) {
+    EXPECT_EQ(toModifiedUtf7("R&D"), "R&-D");
+    EXPECT_EQ(fromModifiedUtf7("R&-D"), "R&D");
+}
+
+TEST(ModifiedUtf7, EncodesTheKnownRfcExample) {
+    // RFC 3501 section 5.1.3's own example, which is the only external fixed
+    // point available without a server.
+    EXPECT_EQ(toModifiedUtf7("~peter/mail/\xe5\x8f\xb0\xe5\x8c\x97/\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e"),
+              "~peter/mail/&U,BTFw-/&ZeVnLIqe-");
+    EXPECT_EQ(fromModifiedUtf7("~peter/mail/&U,BTFw-/&ZeVnLIqe-"),
+              "~peter/mail/\xe5\x8f\xb0\xe5\x8c\x97/\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e");
+}
+
+TEST(ModifiedUtf7, UsesCommaRatherThanSlashInTheBase64Alphabet) {
+    // The substitution that keeps an encoded name from ever containing the
+    // hierarchy delimiter. "台北" encodes to a run holding that 63rd character.
+    const std::string enc = toModifiedUtf7("\xe5\x8f\xb0\xe5\x8c\x97");
+    EXPECT_EQ(enc, "&U,BTFw-");
+    EXPECT_EQ(enc.find('/'), std::string::npos) << "a / here would read as a mailbox separator";
+}
+
+TEST(ModifiedUtf7, RoundTripsAccentedHungarianMailboxNames) {
+    for (const char* name : {"Be\xc3\xa9rkezett",
+                             "Szem\xc3\xa9t",
+                             "Elk\xc3\xbcld\xc3\xb6tt elemek",
+                             "Piszkozatok/V\xc3\xa1zlat",
+                             "\xc3\x81rv\xc3\xadzt\xc5\xb1r\xc5\x91 t\xc3\xbckr\xc3\xb6"
+                             "f\xc3\xbar\xc3\xb3g\xc3\xa9p"}) {
+        const std::string enc = toModifiedUtf7(name);
+        EXPECT_EQ(fromModifiedUtf7(enc), std::string(name)) << "via " << enc;
+    }
+}
+
+TEST(ModifiedUtf7, AnAccentedNameEncodesToPureAscii) {
+    // The point of the encoding: the bytes that reach the wire are 7-bit, so
+    // the mailbox argument never needs a literal.
+    const std::string enc = toModifiedUtf7("Be\xc3\xa9rkezett");
+    EXPECT_EQ(enc, "Be&AOk-rkezett");
+    for (const char c : enc) EXPECT_LT(static_cast<unsigned char>(c), 0x80u);
+}
+
+TEST(ModifiedUtf7, RoundTripsCharactersOutsideTheBasicPlane) {
+    const char* mailbox = "\xf0\x9f\x93\xac Inbox";   // U+1F4EC, a surrogate pair in UTF-16
+    const std::string enc = toModifiedUtf7(mailbox);
+    EXPECT_EQ(enc, "&2D3c7A- Inbox");
+    EXPECT_EQ(fromModifiedUtf7(enc), std::string(mailbox));
+}
+
+TEST(ModifiedUtf7, AdjacentNonAsciiRunsShareOneShiftSequence) {
+    // Two shifts where one would do is still correct, but it means a name has
+    // more than one encoding and so cannot be compared as a key.
+    EXPECT_EQ(toModifiedUtf7("\xc3\xa9\xc3\xa1"), "&AOkA4Q-");
+}
+
+TEST(ModifiedUtf7, RefusesInvalidUtf8RatherThanGuessing) {
+    EXPECT_THROW(toModifiedUtf7("\xc3"), ImapCommandError) << "truncated sequence";
+    EXPECT_THROW(toModifiedUtf7("\xc0\xa6"), ImapCommandError) << "overlong '&' must not slip in";
+    EXPECT_THROW(toModifiedUtf7("\xed\xa0\x80"), ImapCommandError) << "lone surrogate";
+    EXPECT_THROW(toModifiedUtf7("\x80\x80"), ImapCommandError) << "stray continuation bytes";
+}
+
+TEST(ModifiedUtf7, DecodeRefusesMalformedInput) {
+    EXPECT_THROW(fromModifiedUtf7("&AOk"), ImapCommandError) << "unterminated shift";
+    EXPECT_THROW(fromModifiedUtf7("&-x&"), ImapCommandError) << "trailing bare shift";
+    EXPECT_THROW(fromModifiedUtf7("&A-"), ImapCommandError) << "base64 run of length 1";
+    EXPECT_THROW(fromModifiedUtf7("&2D0-"), ImapCommandError) << "unpaired high surrogate";
+    EXPECT_THROW(fromModifiedUtf7("&3Ww-"), ImapCommandError) << "unpaired low surrogate";
+    EXPECT_THROW(fromModifiedUtf7("&AOkA-"), ImapCommandError) << "odd number of UTF-16 octets";
+}
+
+TEST(ModifiedUtf7, DecodeRefusesNonCanonicalTrailingBits) {
+    // "&AOk-" is the canonical encoding of U+00E9. A run whose leftover bits
+    // are not zero decodes to the same name, so accepting it would mean one
+    // mailbox has two spellings.
+    EXPECT_EQ(fromModifiedUtf7("&AOk-"), "\xc3\xa9");
+    EXPECT_THROW(fromModifiedUtf7("&AOl-"), ImapCommandError);
+}
+
+// --- Tags -----------------------------------------------------------------
+
+TEST(ImapTagger, ProducesMonotonicallyIncreasingTags) {
+    ImapTagger t;
+    EXPECT_EQ(t.next(), "A001");
+    EXPECT_EQ(t.next(), "A002");
+    EXPECT_EQ(t.next(), "A003");
+    EXPECT_EQ(t.issued(), 3u);
+}
+
+TEST(ImapTagger, NeverRepeatsATagWithinASession) {
+    // A response is matched to a command by tag alone, so a repeat does not
+    // produce an error - it produces a right-looking answer attributed to the
+    // wrong command.
+    ImapTagger t;
+    std::set<std::string> seen;
+    for (int i = 0; i < 20000; ++i) EXPECT_TRUE(seen.insert(t.next()).second);
+    EXPECT_EQ(seen.size(), 20000u);
+}
+
+TEST(ImapTagger, GrowsPastThePaddedWidthRatherThanWrapping) {
+    // The padding is cosmetic; the counter is not bounded by it.
+    ImapTagger t;
+    for (int i = 0; i < 999; ++i) t.next();
+    EXPECT_EQ(t.next(), "A1000");
+}
+
+// --- Command builders: exact wire text ------------------------------------
+
+TEST(ImapCommands, CapabilityIsTaggedAndCrlfTerminated) {
+    EXPECT_EQ(wire(imapCapability("A001")), "A001 CAPABILITY\r\n");
+}
+
+TEST(ImapCommands, LogoutIsTaggedAndCrlfTerminated) {
+    EXPECT_EQ(wire(imapLogout("A009")), "A009 LOGOUT\r\n");
+}
+
+TEST(ImapCommands, LoginEncodesBothCredentials) {
+    EXPECT_EQ(wire(imapLogin("A002", "bob", "secret")), "A002 LOGIN bob secret\r\n");
+    EXPECT_EQ(wire(imapLogin("A002", "bob@example.hu", "p@ss w0rd")),
+              "A002 LOGIN bob@example.hu \"p@ss w0rd\"\r\n");
+    EXPECT_EQ(wire(imapLogin("A002", "bob", "")), "A002 LOGIN bob \"\"\r\n");
+}
+
+TEST(ImapCommands, ExamineIsUsedForReadsBecauseItDoesNotSetSeen) {
+    // SELECT and EXAMINE differ only in write access, and that difference is
+    // whether a later FETCH marks a customer's mail read. A read surface must
+    // emit EXAMINE, and only asserting the exact verb catches a regression.
+    EXPECT_EQ(wire(imapExamine("A003", "INBOX")), "A003 EXAMINE INBOX\r\n");
+    EXPECT_EQ(wire(imapSelect("A003", "INBOX")), "A003 SELECT INBOX\r\n");
+}
+
+TEST(ImapCommands, ExamineEncodesAnAccentedMailboxNameAsModifiedUtf7) {
+    EXPECT_EQ(wire(imapExamine("A003", "Be\xc3\xa9rkezett")), "A003 EXAMINE Be&AOk-rkezett\r\n");
+    EXPECT_EQ(wire(imapExamine("A003", "Szem\xc3\xa9t")), "A003 EXAMINE Szem&AOk-t\r\n");
+}
+
+TEST(ImapCommands, AMailboxNameWithASpaceIsQuotedAfterEncoding) {
+    // Two shift runs, because ASCII letters sit between the two accents: a run
+    // ends at the first directly-encodable character.
+    EXPECT_EQ(wire(imapExamine("A003", "Elk\xc3\xbcld\xc3\xb6tt elemek")),
+              "A003 EXAMINE \"Elk&APw-ld&APY-tt elemek\"\r\n");
+}
+
+TEST(ImapCommands, AnEncodedMailboxNameNeverNeedsALiteral) {
+    // Because modified UTF-7 output is 7-bit, which is the practical payoff of
+    // encoding rather than sending UTF-8 octets.
+    EXPECT_FALSE(imapExamine("A003", "\xc3\x81rv\xc3\xadzt\xc5\xb1r\xc5\x91").needsContinuation());
+}
+
+TEST(ImapCommands, ListEncodesTheReferenceAndThePattern) {
+    EXPECT_EQ(wire(imapList("A004", "", "*")), "A004 LIST \"\" \"*\"\r\n");
+    EXPECT_EQ(wire(imapList("A004", "", "%")), "A004 LIST \"\" \"%\"\r\n");
+    EXPECT_EQ(wire(imapList("A004", "INBOX", "%")), "A004 LIST INBOX \"%\"\r\n");
+    EXPECT_EQ(wire(imapList("A004", "Be\xc3\xa9rkezett", "*")),
+              "A004 LIST Be&AOk-rkezett \"*\"\r\n");
+}
+
+TEST(ImapCommands, UidSearchWithNoCriteriaSearchesEverything) {
+    EXPECT_EQ(wire(imapUidSearch("A005", {})), "A005 UID SEARCH ALL\r\n");
+}
+
+TEST(ImapCommands, UidSearchEmitsCriteriaInAFixedOrder) {
+    ImapSearchCriteria c;
+    c.since = "1-Jan-2026";
+    c.unseen = true;
+    c.from = "billing@example.com";
+    c.subject = "invoice 2026";
+    EXPECT_EQ(wire(imapUidSearch("A005", c)),
+              "A005 UID SEARCH SINCE 1-Jan-2026 UNSEEN FROM billing@example.com "
+              "SUBJECT \"invoice 2026\"\r\n");
+}
+
+TEST(ImapCommands, UidSearchSupportsTheCommonCriteria) {
+    ImapSearchCriteria c;
+    c.before = "31-Dec-2025";
+    c.seen = true;
+    c.flagged = true;
+    c.largerThanBytes = 1024;
+    c.smallerThanBytes = 1048576;
+    c.to = "me@example.hu";
+    c.text = "overdue";
+    c.body = "wire transfer";
+    c.headerName = "X-Mailer";
+    c.headerValue = "Outlook";
+    EXPECT_EQ(wire(imapUidSearch("A005", c)),
+              "A005 UID SEARCH BEFORE 31-Dec-2025 SEEN FLAGGED LARGER 1024 SMALLER 1048576 "
+              "TO me@example.hu TEXT overdue BODY \"wire transfer\" "
+              "HEADER X-Mailer Outlook\r\n");
+}
+
+TEST(ImapCommands, UidSearchRefusesAnImplausibleDate) {
+    ImapSearchCriteria c;
+    c.since = "2026-01-01";
+    EXPECT_THROW(imapUidSearch("A005", c), ImapCommandError);
+    c.since = "1-Januar-2026";
+    EXPECT_THROW(imapUidSearch("A005", c), ImapCommandError);
+    c.since = "1-Jan-26";
+    EXPECT_THROW(imapUidSearch("A005", c), ImapCommandError);
+}
+
+TEST(ImapCommands, UidSearchNeedsBothHalvesOfAHeaderCriterion) {
+    ImapSearchCriteria c;
+    c.headerName = "X-Mailer";
+    EXPECT_THROW(imapUidSearch("A005", c), ImapCommandError);
+    c = {};
+    c.headerValue = "Outlook";
+    EXPECT_THROW(imapUidSearch("A005", c), ImapCommandError);
+}
+
+// --- Non-ASCII SEARCH is refused, not sent --------------------------------
+//
+// Measured on a live server. A non-ASCII term needs CHARSET UTF-8 plus a
+// literal continuation this one-shot path does not drive; sent unannounced the
+// server either rejects the command or matches nothing, and zero hits is
+// indistinguishable from an empty mailbox. The optimistic version shipped
+// elsewhere and gave silently wrong answers against Hungarian mail.
+
+TEST(ImapSearchNonAscii, AnAccentedSubjectTermIsRefusedByName) {
+    ImapSearchCriteria c;
+    c.subject = "Be\xc3\xa9rkezett";
+    EXPECT_THROW(imapUidSearch("A005", c), ImapCommandError);
+    EXPECT_EQ(refusedField([&] { imapUidSearch("A005", c); }), "subject");
+}
+
+TEST(ImapSearchNonAscii, TheRefusalSaysWhatToDoInstead) {
+    ImapSearchCriteria c;
+    c.subject = "Szem\xc3\xa9t";
+    try {
+        imapUidSearch("A005", c);
+        FAIL() << "an accented search term must not be sent";
+    } catch (const ImapCommandError& e) {
+        const std::string msg = e.what();
+        EXPECT_NE(msg.find("non-ASCII"), std::string::npos);
+        EXPECT_NE(msg.find("after fetching"), std::string::npos)
+            << "the caller has to be told the workaround: " << msg;
+    }
+}
+
+TEST(ImapSearchNonAscii, APureAsciiTermOfTheSameShapeStillBuildsNormally) {
+    ImapSearchCriteria c;
+    c.subject = "Beerkezett";
+    EXPECT_EQ(wire(imapUidSearch("A005", c)), "A005 UID SEARCH SUBJECT Beerkezett\r\n");
+}
+
+TEST(ImapSearchNonAscii, EveryTermFieldIsCheckedNotJustSubject) {
+    for (const char* field : {"from", "to", "subject", "text", "body", "headerValue"}) {
+        ImapSearchCriteria c;
+        const std::string accented = "k\xc3\xbcld\xc5\x91";
+        if (std::string(field) == "from") c.from = accented;
+        if (std::string(field) == "to") c.to = accented;
+        if (std::string(field) == "subject") c.subject = accented;
+        if (std::string(field) == "text") c.text = accented;
+        if (std::string(field) == "body") c.body = accented;
+        if (std::string(field) == "headerValue") {
+            c.headerName = "Subject";
+            c.headerValue = accented;
+        }
+        EXPECT_EQ(refusedField([&] { imapUidSearch("A005", c); }), field);
+    }
+}
+
+TEST(ImapSearchNonAscii, TheAccentsAreNotStrippedOrTransliterated) {
+    // "Beerkezett" is a different search from "Beérkezett"; substituting one
+    // for the other is the same silently wrong answer in a nicer costume.
+    ImapSearchCriteria c;
+    c.subject = "Be\xc3\xa9rkezett";
+    EXPECT_THROW(imapUidSearch("A005", c), ImapCommandError);
+}
+
+TEST(ImapSearchNonAscii, MailboxNamesAreUnaffectedAndStillEncode) {
+    // The refusal is about SEARCH criteria only. A mailbox name has a defined
+    // 7-bit encoding, so it keeps working.
+    EXPECT_EQ(wire(imapExamine("A003", "Be\xc3\xa9rkezett")), "A003 EXAMINE Be&AOk-rkezett\r\n");
+}
+
+// --- UID sets -------------------------------------------------------------
+
+TEST(ImapUidSet, FormatsASingleUid) {
+    EXPECT_EQ(imapFormatUidSet(std::vector<uint64_t>{7}), "7");
+}
+
+TEST(ImapUidSet, SortsDeduplicatesAndCoalescesRuns) {
+    EXPECT_EQ(imapFormatUidSet(std::vector<uint64_t>{12, 3, 8, 7, 9, 3}), "3,7:9,12");
+}
+
+TEST(ImapUidSet, LeavesAPairExpandedBecauseARangeSavesNothing) {
+    EXPECT_EQ(imapFormatUidSet(std::vector<uint64_t>{4, 5}), "4,5");
+}
+
+TEST(ImapUidSet, AcceptsExplicitRanges) {
+    EXPECT_EQ(imapFormatUidSet(std::vector<ImapUidRange>{{1, 3}, {10, 10}}), "1:3,10");
+}
+
+TEST(ImapUidSet, RefusesAnEmptySetAndAZeroUid) {
+    EXPECT_THROW(imapFormatUidSet(std::vector<uint64_t>{}), ImapCommandError);
+    EXPECT_THROW(imapFormatUidSet(std::vector<uint64_t>{0, 1}), ImapCommandError)
+        << "IMAP UIDs start at 1, so a 0 means the caller lost a value";
+    EXPECT_THROW(imapFormatUidSet(std::vector<ImapUidRange>{{5, 4}}), ImapCommandError);
+    EXPECT_THROW(imapFormatUidSet(std::vector<ImapUidRange>{{1, 1000000}}), ImapCommandError);
+}
+
+// --- UID FETCH ------------------------------------------------------------
+
+TEST(ImapUidFetch, UsesBodyPeekSoAReadDoesNotMarkMailSeen) {
+    // BODY[...] sets \Seen as a side effect. Asserting the exact bytes is the
+    // only way this stays true.
+    const std::string w = wire(imapUidFetch("A006", std::vector<uint64_t>{7}, "HEADER"));
+    EXPECT_EQ(w, "A006 UID FETCH 7 (UID FLAGS INTERNALDATE RFC822.SIZE BODY.PEEK[HEADER])\r\n");
+    EXPECT_EQ(w.find("BODY["), std::string::npos) << "an unpeeked BODY[ would mark mail read";
+}
+
+TEST(ImapUidFetch, CarriesABodyPartSpecifier) {
+    EXPECT_EQ(wire(imapUidFetch("A006", std::vector<uint64_t>{1, 2, 3}, "TEXT")),
+              "A006 UID FETCH 1:3 (UID FLAGS INTERNALDATE RFC822.SIZE BODY.PEEK[TEXT])\r\n");
+    EXPECT_EQ(wire(imapUidFetch("A006", std::vector<uint64_t>{5}, "2.1")),
+              "A006 UID FETCH 5 (UID FLAGS INTERNALDATE RFC822.SIZE BODY.PEEK[2.1])\r\n");
+    EXPECT_EQ(wire(imapUidFetch("A006", std::vector<uint64_t>{5}, "HEADER.FIELDS (FROM SUBJECT)")),
+              "A006 UID FETCH 5 (UID FLAGS INTERNALDATE RFC822.SIZE "
+              "BODY.PEEK[HEADER.FIELDS (FROM SUBJECT)])\r\n");
+}
+
+TEST(ImapUidFetch, RefusesABodyPartOutsideTheAllowlist) {
+    // This argument is raw protocol by necessity - the brackets ARE the syntax
+    // - so it is the sharpest input here and is allowlisted, not blocklisted.
+    for (const char* spec : {"HEADER\r\nA001 LOGOUT", "HEADER\"", "HEADER\\", "", "HEA{DER",
+                             "HEADER;", "HEADER\x01"}) {
+        EXPECT_THROW(imapUidFetch("A006", std::vector<uint64_t>{1}, spec), ImapCommandError)
+            << "accepted body part: " << spec;
+    }
+}
+
+TEST(ImapUidFetch, RefusesAnUnbalancedBracketOrParenthesis) {
+    // An unbalanced bracket would close the one we wrap it in and leave the
+    // remainder of the item list as protocol.
+    EXPECT_THROW(imapValidateBodyPart("TEXT]"), ImapCommandError);
+    EXPECT_THROW(imapValidateBodyPart("TEXT["), ImapCommandError);
+    EXPECT_THROW(imapValidateBodyPart("HEADER.FIELDS (FROM"), ImapCommandError);
+    EXPECT_THROW(imapValidateBodyPart("HEADER.FIELDS FROM)"), ImapCommandError);
+    EXPECT_NO_THROW(imapValidateBodyPart("HEADER.FIELDS (FROM TO DATE)"));
+    EXPECT_NO_THROW(imapValidateBodyPart("1.2.MIME"));
+}
+
+// --- Adversarial: a value that is secretly a second command ---------------
+
+TEST(ImapInjection, ACrlfInAMailboxNameIsRefusedByName) {
+    EXPECT_EQ(refusedField([] { imapExamine("A001", "INBOX\r\nA002 LOGOUT"); }), "mailbox");
+    EXPECT_EQ(refusedField([] { imapSelect("A001", "INBOX\r\nA002 LOGOUT"); }), "mailbox");
+    EXPECT_EQ(refusedField([] { imapList("A001", "\r\n", "*"); }), "reference");
+    EXPECT_EQ(refusedField([] { imapList("A001", "", "*\r\n"); }), "pattern");
+}
+
+TEST(ImapInjection, ABareCrOrLfIsRefusedToo) {
+    // Some servers tolerate a bare LF as a command terminator, so neither byte
+    // may travel on its own either.
+    EXPECT_THROW(imapExamine("A001", "INBOX\rX"), ImapCommandError);
+    EXPECT_THROW(imapExamine("A001", "INBOX\nX"), ImapCommandError);
+}
+
+TEST(ImapInjection, AnEmbeddedSecondCommandNeverReachesTheWire) {
+    // The payload that makes the risk concrete: if it were accepted, the server
+    // would read A001's EXAMINE and then obey the attacker's LOGOUT.
+    const char* evil = "INBOX\"\r\nA001 LOGOUT\r\n";
+    EXPECT_THROW(imapExamine("A001", evil), ImapCommandError);
+    ImapSearchCriteria c;
+    c.subject = evil;
+    EXPECT_THROW(imapUidSearch("A001", c), ImapCommandError);
+    EXPECT_THROW(imapLogin("A001", "bob", evil), ImapCommandError);
+    EXPECT_THROW(imapLogin("A001", evil, "pw"), ImapCommandError);
+}
+
+TEST(ImapInjection, NoBuiltCommandEverContainsAnInteriorCrlf) {
+    // The structural property behind all of the above: the only CRLF in a chunk
+    // is the one that ends it, and for a literal chunk the one in its `{n}`
+    // header. Anything else is a second command.
+    ImapSearchCriteria c;
+    c.from = "a@b.c";
+    c.subject = "hello world";
+    const ImapCommand cmds[] = {
+        imapCapability("A001"),
+        imapLogin("A002", "bob", "p\xc3\xa1ss"),
+        imapExamine("A003", "Be\xc3\xa9rkezett"),
+        imapList("A004", "", "*"),
+        imapUidSearch("A005", c),
+        imapUidFetch("A006", std::vector<uint64_t>{1, 2}, "HEADER"),
+        imapLogout("A007"),
+    };
+    for (const auto& cmd : cmds) {
+        for (const auto& chunk : cmd.chunks) {
+            ASSERT_GE(chunk.size(), 2u);
+            EXPECT_EQ(chunk.substr(chunk.size() - 2), "\r\n") << chunk;
+            EXPECT_EQ(chunk.substr(0, chunk.size() - 2).find("\r\n"), std::string::npos)
+                << "interior CRLF in: " << chunk;
+        }
+    }
+}
+
+TEST(ImapInjection, AQuoteEscapeAttemptCannotBreakOutOfAQuotedString) {
+    // `a\" b` is an attempt to make the escape consume the closing quote. The
+    // name survives as data: every backslash is itself escaped.
+    EXPECT_EQ(wire(imapExamine("A001", "a\\\" b")), "A001 EXAMINE \"a\\\\\\\" b\"\r\n");
+    ImapSearchCriteria c;
+    c.subject = "x\" OR \"y";
+    EXPECT_EQ(wire(imapUidSearch("A001", c)),
+              "A001 UID SEARCH SUBJECT \"x\\\" OR \\\"y\"\r\n");
+}
+
+TEST(ImapInjection, ANulByteIsRefusedEverywhere) {
+    const std::string nul("IN\0BOX", 6);
+    EXPECT_EQ(refusedField([&] { imapExamine("A001", nul); }), "mailbox");
+    ImapSearchCriteria c;
+    c.subject = nul;
+    EXPECT_THROW(imapUidSearch("A001", c), ImapCommandError);
+    EXPECT_THROW(imapLogin("A001", "bob", nul), ImapCommandError);
+}
+
+TEST(ImapInjection, AFakeLiteralHeaderInAValueIsJustData) {
+    // A name claiming a length that would overrun: if `{5}` were taken as
+    // protocol the server would read the following 5 octets as a literal and
+    // the rest of the name as a command. It is quoted instead, because `{` is
+    // an atom-special.
+    EXPECT_EQ(wire(imapExamine("A001", "{5}")), "A001 EXAMINE \"{5}\"\r\n");
+    EXPECT_EQ(wire(imapExamine("A001", "x {999999}")), "A001 EXAMINE \"x {999999}\"\r\n");
+    ImapSearchCriteria c;
+    c.subject = "{1000000}";
+    EXPECT_EQ(wire(imapUidSearch("A001", c)), "A001 UID SEARCH SUBJECT \"{1000000}\"\r\n");
+}
+
+TEST(ImapInjection, AGenuineLiteralCountCannotUnderstateItsPayload) {
+    // The counterpart: when we DO emit a literal, the count is the payload's
+    // byte length exactly. An understated count leaves the tail on the wire as
+    // the next command, which is the same injection by another route.
+    const std::string pw = "p\xc3\xa1ssw\xc3\xb3rd";
+    const ImapCommand c = imapLogin("A001", "bob", pw);
+    ASSERT_TRUE(c.needsContinuation());
+    EXPECT_EQ(c.chunks[0], "A001 LOGIN bob {" + std::to_string(pw.size()) + "}\r\n");
+    EXPECT_EQ(c.chunks[1], pw + "\r\n");
+    EXPECT_EQ(c.chunks[1].size(), pw.size() + 2);
+}
+
+TEST(ImapInjection, ATagThatIsNotAnAtomIsRefused) {
+    // The tags are ours today, but an unchecked tag is a free injection point
+    // the moment one is ever derived from input.
+    EXPECT_THROW(imapBuildCommand("A001 LOGOUT\r\nA002", "NOOP", {}), ImapCommandError);
+    EXPECT_THROW(imapBuildCommand("", "NOOP", {}), ImapCommandError);
+    EXPECT_THROW(imapBuildCommand("A 1", "NOOP", {}), ImapCommandError);
+}
+
+TEST(ImapInjection, AHeaderFieldNameMustBeAnAtom) {
+    ImapSearchCriteria c;
+    c.headerName = "X-Mailer\r\nA001 LOGOUT";
+    c.headerValue = "x";
+    EXPECT_EQ(refusedField([&] { imapUidSearch("A001", c); }), "headerName");
+    c.headerName = "X Mailer";
+    EXPECT_THROW(imapUidSearch("A001", c), ImapCommandError);
+}

+ 826 - 0
runner/tests/imap_fetch_test.cpp

@@ -0,0 +1,826 @@
+// Interpreting IMAP server responses.
+//
+// Every fixture here is REAL-SHAPED wire bytes with explicit \r\n, because the
+// bugs this file is guarding against all live in the shapes a server actually
+// sends: a literal whose count includes a CRLF, a BODY.PEEK that comes back
+// without the .PEEK, a message/rfc822 whose part numbering is not its tree
+// position. A convenient invented format tests none of that.
+//
+// ⚠ EVERY {N} BELOW IS AN EXACT BYTE COUNT. If one of these tests fails after
+// an edit to a fixture, suspect the count before suspecting the parser - the
+// reader is byte-counted and will happily take the wrong span as data.
+#include <gtest/gtest.h>
+
+#include <string>
+
+#include "net/imap_fetch.hpp"
+
+using svapi::functions::ImapParse;
+using namespace svapi::runner::net;
+
+namespace {
+
+// --- Fixtures --------------------------------------------------------------
+
+// A plain text/plain mail. Note the BODYSTRUCTURE is NOT a list of parts.
+const std::string kSinglePart =
+    "* 1 FETCH (UID 101 FLAGS (\\Seen) INTERNALDATE \"08-Oct-2026 11:22:33 +0200\" "
+    "RFC822.SIZE 4217 BODYSTRUCTURE (\"TEXT\" \"PLAIN\" (\"CHARSET\" \"utf-8\") "
+    "NIL NIL \"7BIT\" 1152 23))\r\n"
+    "A001 OK FETCH completed\r\n";
+
+const std::string kAlternative =
+    "* 2 FETCH (UID 102 BODYSTRUCTURE ((\"TEXT\" \"PLAIN\" (\"CHARSET\" \"utf-8\") "
+    "NIL NIL \"QUOTED-PRINTABLE\" 403 12)(\"TEXT\" \"HTML\" (\"CHARSET\" \"utf-8\") "
+    "NIL NIL \"QUOTED-PRINTABLE\" 1890 31) \"ALTERNATIVE\" (\"BOUNDARY\" \"=_b1\") "
+    "NIL NIL))\r\n";
+
+// text/html only, so the html fallback is the only readable body there is.
+const std::string kHtmlOnly =
+    "* 3 FETCH (UID 103 BODYSTRUCTURE ((\"TEXT\" \"HTML\" (\"CHARSET\" \"utf-8\") "
+    "NIL NIL \"BASE64\" 2048 40) \"ALTERNATIVE\" (\"BOUNDARY\" \"=_b2\") NIL NIL))\r\n";
+
+// multipart/mixed with a PDF whose filename arrives RFC 2047 encoded. Index of
+// the single-part fields after the octets: md5, then the disposition.
+const std::string kPdfAttachment =
+    "* 4 FETCH (UID 104 BODYSTRUCTURE ((\"TEXT\" \"PLAIN\" (\"CHARSET\" \"utf-8\") "
+    "NIL NIL \"8BIT\" 211 7)(\"APPLICATION\" \"PDF\" (\"NAME\" \"arajanlat.pdf\") "
+    "NIL NIL \"BASE64\" 98234 NIL (\"ATTACHMENT\" "
+    "(\"FILENAME\" \"=?UTF-8?Q?=C3=A1raj=C3=A1nlat.pdf?=\")) NIL) "
+    "\"MIXED\" (\"BOUNDARY\" \"=_m1\") NIL NIL))\r\n";
+
+// The envelope of the forwarded messages below. Kept small: this test is about
+// part numbering, and the envelope only has to be well formed.
+#define FWD_ENV                                                                 \
+    "(\"Wed, 07 Oct 2026 08:00:00 +0200\" \"Fwd: teszt\" "                      \
+    "((NIL NIL \"a\" \"pelda.hu\")) ((NIL NIL \"a\" \"pelda.hu\")) NIL "        \
+    "((NIL NIL \"b\" \"pelda.hu\")) NIL NIL NIL \"<f1@pelda.hu>\")"
+
+// The worked example from RFC 3501 section 6.4.5, which is the authority on
+// part numbering and contains both traps: a nested multipart (part 4, whose
+// children are 4.1 and 4.2) and a message/rfc822 whose encapsulated multipart
+// adds NO level (part 3, whose children are 3.1 and 3.2, not 3.1.1 and 3.1.2).
+const std::string kRfcExample =
+    "* 9 FETCH (UID 909 BODYSTRUCTURE ("
+    "(\"TEXT\" \"PLAIN\" (\"CHARSET\" \"us-ascii\") NIL NIL \"7BIT\" 100 5)"
+    "(\"APPLICATION\" \"OCTET-STREAM\" NIL NIL NIL \"BASE64\" 2000 NIL NIL NIL)"
+    "(\"MESSAGE\" \"RFC822\" NIL NIL NIL \"7BIT\" 4000 " FWD_ENV " ("
+    "(\"TEXT\" \"PLAIN\" (\"CHARSET\" \"us-ascii\") NIL NIL \"7BIT\" 300 9)"
+    "(\"APPLICATION\" \"OCTET-STREAM\" NIL NIL NIL \"BASE64\" 500 NIL NIL NIL)"
+    " \"MIXED\") 90 NIL NIL NIL)"
+    "("
+    "(\"IMAGE\" \"GIF\" NIL NIL NIL \"BASE64\" 700 NIL NIL NIL)"
+    "(\"MESSAGE\" \"RFC822\" NIL NIL NIL \"7BIT\" 8000 " FWD_ENV " ("
+    "(\"TEXT\" \"PLAIN\" (\"CHARSET\" \"us-ascii\") NIL NIL \"7BIT\" 400 11)"
+    "((\"IMAGE\" \"GIF\" NIL NIL NIL \"BASE64\" 600 NIL NIL NIL) \"MIXED\")"
+    " \"MIXED\") 120 NIL NIL NIL)"
+    " \"MIXED\")"
+    " \"MIXED\"))\r\n";
+
+// A Hungarian subject that cannot travel as ASCII, base64 in UTF-8, plus a
+// display name in ISO-8859-1 Q - both spellings are ordinary European traffic.
+// The last To: entry is a GROUP MARKER: a NIL host, which is not an address.
+const std::string kEnvelopeLine =
+    "* 5 FETCH (UID 505 ENVELOPE (\"Thu, 08 Oct 2026 10:11:12 +0200\" "
+    "\"=?UTF-8?B?w5xkdsO2emzDvG5rIGEgcmVuZHN6ZXJiZW4=?=\" "
+    "((\"=?ISO-8859-1?Q?Szont=E1gh_Ferenc?=\" NIL \"ferenc\" \"pelda.hu\")) "
+    "((\"=?ISO-8859-1?Q?Szont=E1gh_Ferenc?=\" NIL \"ferenc\" \"pelda.hu\")) "
+    "NIL "
+    "((\"Anna\" NIL \"anna\" \"pelda.hu\")(NIL NIL \"undisclosed-recipients\" NIL)) "
+    "NIL NIL \"<parent@pelda.hu>\" \"<msg1@pelda.hu>\"))\r\n";
+
+// {28} is exactly "Szia Ferenc!" CRLF CRLF "Üdv: Anna" CRLF, with Ü as its two
+// UTF-8 bytes. The literal carries CRLFs, which is why a line-based parser
+// cannot read this response at all.
+const std::string kBodyLiteral =
+    "* 7 FETCH (UID 707 BODY[TEXT] {28}\r\n"
+    "Szia Ferenc!\r\n\r\nÜdv: Anna\r\n"
+    " FLAGS (\\Seen))\r\n";
+
+}  // namespace
+
+// ---------------------------------------------------------------------------
+// The s-expression layer
+// ---------------------------------------------------------------------------
+
+TEST(ImapSexp, ShapesAFlatResponseLineIntoValues) {
+    const ImapSexp s = parseResponseLine("* 12 EXISTS\r\n");
+    ASSERT_EQ(s.status, ImapParse::Ok);
+    ASSERT_EQ(s.values.size(), 3u);
+    EXPECT_EQ(s.values[0].text, "*");
+    EXPECT_EQ(s.values[1].text, "12");
+    EXPECT_EQ(s.values[2].text, "EXISTS");
+    EXPECT_EQ(s.consumed, 13u);
+}
+
+TEST(ImapSexp, NestsParenthesisedDataRecursively) {
+    const ImapSexp s = parseResponseLine("* 1 FETCH (A (B (C)) D)\r\n");
+    ASSERT_EQ(s.status, ImapParse::Ok);
+    ASSERT_EQ(s.values.size(), 4u);
+    ASSERT_TRUE(s.values[3].isList());
+    ASSERT_EQ(s.values[3].items.size(), 3u);
+    ASSERT_TRUE(s.values[3].items[1].isList());
+    ASSERT_TRUE(s.values[3].items[1].items[1].isList());
+    EXPECT_EQ(s.values[3].items[1].items[1].items[0].text, "C");
+}
+
+TEST(ImapSexp, KeepsNilDistinctFromTheQuotedStringNIL) {
+    // A sender literally named NIL is the bug this distinction prevents.
+    const ImapSexp s = parseResponseLine("* 1 X (NIL \"NIL\")\r\n");
+    ASSERT_EQ(s.status, ImapParse::Ok);
+    ASSERT_EQ(s.values.size(), 4u);
+    ASSERT_TRUE(s.values[3].isList());
+    EXPECT_TRUE(s.values[3].items[0].isNil());
+    EXPECT_FALSE(s.values[3].items[1].isNil());
+    EXPECT_EQ(s.values[3].items[1].text, "NIL");
+}
+
+TEST(ImapSexp, IndexingPastTheEndOfAListIsSafeAndEmpty) {
+    const ImapSexp s = parseResponseLine("* 1 X (\"TEXT\")\r\n");
+    ASSERT_EQ(s.status, ImapParse::Ok);
+    ASSERT_EQ(s.values.size(), 4u);
+    const ImapValue& list = s.values[3];
+    EXPECT_EQ(list.at(9), nullptr);
+    EXPECT_EQ(list.textAt(9), "");
+    EXPECT_FALSE(list.numberAt(9).has_value());
+}
+
+TEST(ImapSexp, ReportsNeedMoreWhenTheLineIsNotYetTerminated) {
+    EXPECT_EQ(parseResponseLine("* 1 FETCH (UID 1").status, ImapParse::NeedMore);
+}
+
+TEST(ImapSexp, ReportsMalformedWhenAListIsLeftOpenAtTheLineEnd) {
+    // The CRLF arrived, so no amount of further reading can close this list.
+    EXPECT_EQ(parseResponseLine("* 1 FETCH (UID 1\r\n").status, ImapParse::Malformed);
+}
+
+TEST(ImapSexp, ReportsMalformedOnAClosingParenthesisWithNothingOpen) {
+    EXPECT_EQ(parseResponseLine("* 1 FETCH (UID 1))\r\n").status, ImapParse::Malformed);
+}
+
+TEST(ImapSexp, RefusesNestingDeeperThanTheDepthCap) {
+    // A server can reach a stack overflow with nothing but open parentheses,
+    // and a stack overflow is not a parse error - it is the process.
+    std::string deep = "* 1 X ";
+    for (size_t i = 0; i < kMaxSexpDepth + 8; ++i) deep += '(';
+    for (size_t i = 0; i < kMaxSexpDepth + 8; ++i) deep += ')';
+    deep += "\r\n";
+    EXPECT_EQ(parseResponseLine(deep).status, ImapParse::Malformed);
+}
+
+TEST(ImapSexp, AcceptsNestingUpToTheDepthCap) {
+    std::string ok = "* 1 X ";
+    for (size_t i = 0; i < kMaxSexpDepth; ++i) ok += '(';
+    for (size_t i = 0; i < kMaxSexpDepth; ++i) ok += ')';
+    ok += "\r\n";
+    EXPECT_EQ(parseResponseLine(ok).status, ImapParse::Ok);
+}
+
+TEST(ImapSexp, DoesNotBlowTheStackOnThousandsOfOpenParentheses) {
+    // The cap is what makes this survivable rather than merely tidy.
+    std::string flood = "* 1 X ";
+    flood.append(50000, '(');
+    flood += "\r\n";
+    EXPECT_EQ(parseResponseLine(flood).status, ImapParse::Malformed);
+}
+
+// ---------------------------------------------------------------------------
+// LIST / LSUB
+// ---------------------------------------------------------------------------
+
+TEST(ImapList, ReadsFlagsDelimiterAndName) {
+    const std::string bytes =
+        "* LIST (\\HasNoChildren) \"/\" \"INBOX\"\r\n"
+        "* LIST (\\HasChildren \\Noselect) \"/\" \"Archive\"\r\n"
+        "A002 OK LIST completed\r\n";
+    const ImapListResult r = parseListResponse(bytes);
+    ASSERT_EQ(r.status, ImapParse::Ok);
+    ASSERT_EQ(r.mailboxes.size(), 2u);
+    EXPECT_EQ(r.mailboxes[0].nameRaw, "INBOX");
+    EXPECT_EQ(r.mailboxes[0].delimiter, "/");
+    ASSERT_EQ(r.mailboxes[0].flags.size(), 1u);
+    EXPECT_EQ(r.mailboxes[0].flags[0], "\\HasNoChildren");
+    EXPECT_EQ(r.mailboxes[1].nameRaw, "Archive");
+    ASSERT_EQ(r.mailboxes[1].flags.size(), 2u);
+    EXPECT_EQ(r.mailboxes[1].flags[1], "\\Noselect");
+}
+
+TEST(ImapList, ANilDelimiterMeansAFlatNamespaceNotAnUnknownOne) {
+    const ImapListResult r = parseListResponse("* LIST () NIL \"Flat\"\r\n");
+    ASSERT_EQ(r.status, ImapParse::Ok);
+    ASSERT_EQ(r.mailboxes.size(), 1u);
+    EXPECT_TRUE(r.mailboxes[0].delimiter.empty());
+    EXPECT_TRUE(r.mailboxes[0].flags.empty());
+}
+
+TEST(ImapList, ReturnsTheMailboxNameEXACTLYAsSentWithoutDecodingUtf7) {
+    // The bytes are what a later SELECT must carry, so they are handed back
+    // untouched; decoding modified UTF-7 is a caller's job.
+    const ImapListResult r =
+        parseListResponse("* LIST (\\HasNoChildren) \"/\" \"INBOX/S&AOE-rk&AOE-ny\"\r\n");
+    ASSERT_EQ(r.status, ImapParse::Ok);
+    ASSERT_EQ(r.mailboxes.size(), 1u);
+    EXPECT_EQ(r.mailboxes[0].nameRaw, "INBOX/S&AOE-rk&AOE-ny");
+}
+
+TEST(ImapList, ReadsLsubWithTheSameGrammar) {
+    const ImapListResult r = parseListResponse("* LSUB () \".\" \"Sent\"\r\n");
+    ASSERT_EQ(r.status, ImapParse::Ok);
+    ASSERT_EQ(r.mailboxes.size(), 1u);
+    EXPECT_EQ(r.mailboxes[0].nameRaw, "Sent");
+}
+
+TEST(ImapList, ReadsAMailboxNameSentAsALiteral) {
+    // {7} is exactly the 7 bytes of "Munka/A". A mailbox name arrives as a
+    // literal when it holds bytes a quoted string may not, which is routine on
+    // a UTF8=ACCEPT server.
+    const ImapListResult r = parseListResponse("* LIST () \"/\" {7}\r\nMunka/A\r\n");
+    ASSERT_EQ(r.status, ImapParse::Ok);
+    ASSERT_EQ(r.mailboxes.size(), 1u);
+    EXPECT_EQ(r.mailboxes[0].nameRaw, "Munka/A");
+}
+
+// ---------------------------------------------------------------------------
+// UID SEARCH
+// ---------------------------------------------------------------------------
+
+TEST(ImapSearch, ReadsTheListOfUids) {
+    const ImapSearchResult r =
+        parseSearchResponse("* SEARCH 12 14 19 7701\r\nA003 OK SEARCH completed\r\n");
+    ASSERT_EQ(r.status, ImapParse::Ok);
+    ASSERT_EQ(r.uids.size(), 4u);
+    EXPECT_EQ(r.uids[0], 12u);
+    EXPECT_EQ(r.uids[3], 7701u);
+}
+
+TEST(ImapSearch, AnEmptySearchResponseIsAResultNotAFailure) {
+    const ImapSearchResult r = parseSearchResponse("* SEARCH\r\nA003 OK SEARCH completed\r\n");
+    EXPECT_EQ(r.status, ImapParse::Ok);
+    EXPECT_TRUE(r.uids.empty());
+}
+
+TEST(ImapSearch, IgnoresEsearchRatherThanMisreadingIt) {
+    const ImapSearchResult r =
+        parseSearchResponse("* ESEARCH (TAG \"A1\") UID ALL 2:5\r\nA1 OK done\r\n");
+    EXPECT_EQ(r.status, ImapParse::Ok);
+    EXPECT_TRUE(r.uids.empty());
+}
+
+// ---------------------------------------------------------------------------
+// ENVELOPE
+// ---------------------------------------------------------------------------
+
+TEST(ImapEnvelopeParse, DecodesAnRfc2047HungarianSubjectAndKeepsTheRaw) {
+    const ImapEnvelopeResult r = parseEnvelopeResponse(kEnvelopeLine);
+    ASSERT_EQ(r.status, ImapParse::Ok);
+    ASSERT_TRUE(r.envelope.has_value());
+    EXPECT_EQ(r.envelope->subject, "Üdvözlünk a rendszerben");
+    EXPECT_EQ(r.envelope->subjectRaw, "=?UTF-8?B?w5xkdsO2emzDvG5rIGEgcmVuZHN6ZXJiZW4=?=");
+    EXPECT_EQ(r.envelope->date, "Thu, 08 Oct 2026 10:11:12 +0200");
+    EXPECT_EQ(r.envelope->messageId, "<msg1@pelda.hu>");
+    EXPECT_EQ(r.envelope->inReplyTo, "<parent@pelda.hu>");
+}
+
+TEST(ImapEnvelopeParse, BuildsTheAddressFromMailboxAndHost) {
+    const ImapEnvelopeResult r = parseEnvelopeResponse(kEnvelopeLine);
+    ASSERT_TRUE(r.envelope.has_value());
+    ASSERT_EQ(r.envelope->from.size(), 1u);
+    EXPECT_EQ(r.envelope->from[0].address, "ferenc@pelda.hu");
+    EXPECT_EQ(r.envelope->from[0].mailbox, "ferenc");
+    EXPECT_EQ(r.envelope->from[0].host, "pelda.hu");
+}
+
+TEST(ImapEnvelopeParse, DecodesADisplayNameInIso88591AndKeepsTheRaw) {
+    const ImapEnvelopeResult r = parseEnvelopeResponse(kEnvelopeLine);
+    ASSERT_TRUE(r.envelope.has_value());
+    ASSERT_EQ(r.envelope->from.size(), 1u);
+    EXPECT_EQ(r.envelope->from[0].name, "Szontágh Ferenc");
+    EXPECT_EQ(r.envelope->from[0].nameRaw, "=?ISO-8859-1?Q?Szont=E1gh_Ferenc?=");
+}
+
+TEST(ImapEnvelopeParse, ANilHostIsAGroupMarkerAndNotAnAddress) {
+    // Otherwise "undisclosed-recipients@" becomes something we try to send to.
+    const ImapEnvelopeResult r = parseEnvelopeResponse(kEnvelopeLine);
+    ASSERT_TRUE(r.envelope.has_value());
+    ASSERT_EQ(r.envelope->to.size(), 2u);
+    EXPECT_FALSE(r.envelope->to[0].groupMarker);
+    EXPECT_EQ(r.envelope->to[0].address, "anna@pelda.hu");
+    EXPECT_TRUE(r.envelope->to[1].groupMarker);
+    EXPECT_TRUE(r.envelope->to[1].address.empty());
+    EXPECT_EQ(r.envelope->to[1].mailbox, "undisclosed-recipients");
+}
+
+TEST(ImapEnvelopeParse, ANilAddressListIsEmptyRatherThanOneEmptyAddress) {
+    const ImapEnvelopeResult r = parseEnvelopeResponse(kEnvelopeLine);
+    ASSERT_TRUE(r.envelope.has_value());
+    EXPECT_TRUE(r.envelope->replyTo.empty());
+    EXPECT_TRUE(r.envelope->cc.empty());
+    EXPECT_TRUE(r.envelope->bcc.empty());
+    EXPECT_EQ(r.envelope->sender.size(), 1u);
+}
+
+// ---------------------------------------------------------------------------
+// BODYSTRUCTURE
+// ---------------------------------------------------------------------------
+
+TEST(ImapBodyStructure, ASinglePartMessageIsNotAListOfPartsAndIsNumberedOne) {
+    const ImapBodyStructureResult r = parseBodyStructureResponse(kSinglePart);
+    ASSERT_EQ(r.status, ImapParse::Ok);
+    ASSERT_TRUE(r.root.has_value());
+    EXPECT_FALSE(r.root->multipart);
+    EXPECT_EQ(r.root->type, "TEXT");
+    EXPECT_EQ(r.root->subtype, "PLAIN");
+    EXPECT_EQ(r.root->charset, "utf-8");
+    EXPECT_EQ(r.root->encoding, "7BIT");
+    EXPECT_TRUE(r.root->hasOctets);
+    EXPECT_EQ(r.root->octets, 1152u);
+    EXPECT_TRUE(r.root->hasLines);
+    EXPECT_EQ(r.root->lines, 23u);
+    // The part number of a non-multipart message is "1", not empty: BODY[1].
+    EXPECT_EQ(r.root->number, "1");
+}
+
+TEST(ImapBodyStructure, AMultipartContainerHasNoPartNumberOfItsOwn) {
+    const ImapBodyStructureResult r = parseBodyStructureResponse(kAlternative);
+    ASSERT_EQ(r.status, ImapParse::Ok);
+    ASSERT_TRUE(r.root.has_value());
+    EXPECT_TRUE(r.root->multipart);
+    EXPECT_EQ(r.root->type, "MULTIPART");
+    EXPECT_EQ(r.root->subtype, "ALTERNATIVE");
+    EXPECT_TRUE(r.root->number.empty());
+    ASSERT_EQ(r.root->children.size(), 2u);
+    EXPECT_EQ(r.root->children[0].number, "1");
+    EXPECT_EQ(r.root->children[1].number, "2");
+    EXPECT_EQ(r.root->children[1].subtype, "HTML");
+    EXPECT_EQ(r.root->params.at("boundary"), "=_b1");
+}
+
+TEST(ImapBodyStructure, ReadsAnAttachmentsDispositionAndDecodesItsFilename) {
+    const ImapBodyStructureResult r = parseBodyStructureResponse(kPdfAttachment);
+    ASSERT_EQ(r.status, ImapParse::Ok);
+    ASSERT_TRUE(r.root.has_value());
+    ASSERT_EQ(r.root->children.size(), 2u);
+    const ImapBodyPart& pdf = r.root->children[1];
+    EXPECT_EQ(pdf.number, "2");
+    EXPECT_EQ(pdf.type, "APPLICATION");
+    EXPECT_EQ(pdf.subtype, "PDF");
+    EXPECT_EQ(pdf.encoding, "BASE64");
+    EXPECT_EQ(pdf.octets, 98234u);
+    EXPECT_EQ(pdf.disposition, "ATTACHMENT");
+    EXPECT_EQ(pdf.filename, "árajánlat.pdf");
+    EXPECT_EQ(pdf.filenameRaw, "=?UTF-8?Q?=C3=A1raj=C3=A1nlat.pdf?=");
+    // The type's `name` parameter is still visible, and still loses to the
+    // disposition's filename when the two disagree.
+    EXPECT_EQ(pdf.name, "arajanlat.pdf");
+}
+
+TEST(ImapBodyStructure, NumbersPartsTheWayRfc3501Section645Says) {
+    const ImapBodyStructureResult r = parseBodyStructureResponse(kRfcExample);
+    ASSERT_EQ(r.status, ImapParse::Ok);
+    ASSERT_TRUE(r.root.has_value());
+    const ImapBodyPart& root = *r.root;
+    ASSERT_TRUE(root.multipart);
+    ASSERT_EQ(root.children.size(), 4u);
+
+    EXPECT_EQ(root.children[0].number, "1");
+    EXPECT_EQ(root.children[0].subtype, "PLAIN");
+    EXPECT_EQ(root.children[1].number, "2");
+    EXPECT_EQ(root.children[1].subtype, "OCTET-STREAM");
+
+    // Part 3 is a message/rfc822. Its encapsulated multipart adds NO level, so
+    // its children are 3.1 and 3.2.
+    const ImapBodyPart& three = root.children[2];
+    EXPECT_EQ(three.number, "3");
+    EXPECT_EQ(three.type, "MESSAGE");
+    EXPECT_EQ(three.subtype, "RFC822");
+    ASSERT_EQ(three.children.size(), 1u);
+    const ImapBodyPart& threeBody = three.children[0];
+    EXPECT_TRUE(threeBody.multipart);
+    EXPECT_TRUE(threeBody.number.empty());
+    ASSERT_EQ(threeBody.children.size(), 2u);
+    EXPECT_EQ(threeBody.children[0].number, "3.1");
+    EXPECT_EQ(threeBody.children[1].number, "3.2");
+
+    // Part 4 is a nested multipart, which DOES add a level.
+    const ImapBodyPart& four = root.children[3];
+    EXPECT_EQ(four.number, "4");
+    EXPECT_TRUE(four.multipart);
+    ASSERT_EQ(four.children.size(), 2u);
+    EXPECT_EQ(four.children[0].number, "4.1");
+    EXPECT_EQ(four.children[0].subtype, "GIF");
+
+    const ImapBodyPart& fourTwo = four.children[1];
+    EXPECT_EQ(fourTwo.number, "4.2");
+    EXPECT_EQ(fourTwo.subtype, "RFC822");
+    ASSERT_EQ(fourTwo.children.size(), 1u);
+    const ImapBodyPart& fourTwoBody = fourTwo.children[0];
+    EXPECT_TRUE(fourTwoBody.number.empty());
+    ASSERT_EQ(fourTwoBody.children.size(), 2u);
+    EXPECT_EQ(fourTwoBody.children[0].number, "4.2.1");
+    EXPECT_EQ(fourTwoBody.children[1].number, "4.2.2");
+    ASSERT_EQ(fourTwoBody.children[1].children.size(), 1u);
+    EXPECT_EQ(fourTwoBody.children[1].children[0].number, "4.2.2.1");
+    EXPECT_EQ(fourTwoBody.children[1].children[0].subtype, "GIF");
+}
+
+TEST(ImapBodyStructure, CarriesTheEnvelopeOfAnEncapsulatedMessage) {
+    const ImapBodyStructureResult r = parseBodyStructureResponse(kRfcExample);
+    ASSERT_TRUE(r.root.has_value());
+    const ImapBodyPart& three = r.root->children[2];
+    ASSERT_TRUE(three.envelope.has_value());
+    EXPECT_EQ(three.envelope->subject, "Fwd: teszt");
+    ASSERT_EQ(three.envelope->from.size(), 1u);
+    EXPECT_EQ(three.envelope->from[0].address, "a@pelda.hu");
+    EXPECT_TRUE(three.hasLines);
+    EXPECT_EQ(three.lines, 90u);
+}
+
+TEST(ImapBodyStructure, AMessageRfc822HoldingOnePartNumbersItAsPrefixOne) {
+    const std::string bytes =
+        "* 8 FETCH (UID 808 BODYSTRUCTURE ("
+        "(\"TEXT\" \"PLAIN\" (\"CHARSET\" \"utf-8\") NIL NIL \"7BIT\" 50 2)"
+        "(\"MESSAGE\" \"RFC822\" NIL NIL NIL \"7BIT\" 900 " FWD_ENV
+        " (\"TEXT\" \"PLAIN\" (\"CHARSET\" \"utf-8\") NIL NIL \"7BIT\" 400 10) 20 "
+        "NIL NIL NIL)"
+        " \"MIXED\"))\r\n";
+    const ImapBodyStructureResult r = parseBodyStructureResponse(bytes);
+    ASSERT_EQ(r.status, ImapParse::Ok);
+    ASSERT_TRUE(r.root.has_value());
+    ASSERT_EQ(r.root->children.size(), 2u);
+    const ImapBodyPart& msg = r.root->children[1];
+    EXPECT_EQ(msg.number, "2");
+    ASSERT_EQ(msg.children.size(), 1u);
+    // A message with no multipart body still has a part, and it is "1" - here
+    // relative to part 2, so 2.1.
+    EXPECT_EQ(msg.children[0].number, "2.1");
+}
+
+TEST(ImapBodyStructure, ToleratesABodyWithNoExtensionData) {
+    // A bare BODY (not BODYSTRUCTURE) stops after the required fields, so
+    // nothing here may require the disposition to be present.
+    const std::string bytes =
+        "* 1 FETCH (BODY (\"TEXT\" \"PLAIN\" (\"CHARSET\" \"utf-8\") NIL NIL \"7BIT\" 10 1))\r\n";
+    const ImapBodyStructureResult r = parseBodyStructureResponse(bytes);
+    ASSERT_EQ(r.status, ImapParse::Ok);
+    ASSERT_TRUE(r.root.has_value());
+    EXPECT_EQ(r.root->number, "1");
+    EXPECT_TRUE(r.root->disposition.empty());
+}
+
+// ---------------------------------------------------------------------------
+// RFC 2231 filenames
+// ---------------------------------------------------------------------------
+
+TEST(ImapBodyStructure, JoinsAnRfc2231SplitAndPercentEncodedFilename) {
+    const std::string bytes =
+        "* 1 FETCH (BODYSTRUCTURE (\"APPLICATION\" \"PDF\" NIL NIL NIL \"BASE64\" 10 "
+        "NIL (\"ATTACHMENT\" (\"FILENAME*0*\" \"UTF-8''%C3%A1raj\" "
+        "\"FILENAME*1*\" \"%C3%A1nlat.pdf\")) NIL))\r\n";
+    const ImapBodyStructureResult r = parseBodyStructureResponse(bytes);
+    ASSERT_EQ(r.status, ImapParse::Ok);
+    ASSERT_TRUE(r.root.has_value());
+    EXPECT_EQ(r.root->filename, "árajánlat.pdf");
+    EXPECT_EQ(r.root->filenameRaw, "UTF-8''%C3%A1raj%C3%A1nlat.pdf");
+}
+
+TEST(ImapBodyStructure, OrdersRfc2231SegmentsNumericallyNotLexicographically) {
+    // Segment 10 sorts before segment 2 as a string, which scrambles any
+    // filename long enough to need eleven segments.
+    const std::string bytes =
+        "* 1 FETCH (BODYSTRUCTURE (\"APPLICATION\" \"PDF\" NIL NIL NIL \"BASE64\" 10 "
+        "NIL (\"ATTACHMENT\" (\"FILENAME*0\" \"a\" \"FILENAME*1\" \"b\" "
+        "\"FILENAME*2\" \"c\" \"FILENAME*3\" \"d\" \"FILENAME*4\" \"e\" "
+        "\"FILENAME*5\" \"f\" \"FILENAME*6\" \"g\" \"FILENAME*7\" \"h\" "
+        "\"FILENAME*8\" \"i\" \"FILENAME*9\" \"j\" \"FILENAME*10\" \"k\")) NIL))\r\n";
+    const ImapBodyStructureResult r = parseBodyStructureResponse(bytes);
+    ASSERT_EQ(r.status, ImapParse::Ok);
+    ASSERT_TRUE(r.root.has_value());
+    EXPECT_EQ(r.root->filename, "abcdefghijk");
+}
+
+// ---------------------------------------------------------------------------
+// Picking the useful parts
+// ---------------------------------------------------------------------------
+
+TEST(ImapSelectBody, PicksTextPlainOverTextHtml) {
+    const ImapBodyStructureResult r = parseBodyStructureResponse(kAlternative);
+    ASSERT_TRUE(r.root.has_value());
+    const ImapBodySelection s = selectBody(*r.root);
+    ASSERT_TRUE(s.text.found);
+    EXPECT_EQ(s.text.number, "1");
+    EXPECT_EQ(s.text.subtype, "PLAIN");
+    EXPECT_EQ(s.text.encoding, "QUOTED-PRINTABLE");
+    EXPECT_EQ(s.text.charset, "utf-8");
+    EXPECT_FALSE(s.isHtmlFallback);
+    EXPECT_TRUE(s.attachments.empty());
+}
+
+TEST(ImapSelectBody, FallsBackToTextHtmlAndSaysSo) {
+    const ImapBodyStructureResult r = parseBodyStructureResponse(kHtmlOnly);
+    ASSERT_TRUE(r.root.has_value());
+    const ImapBodySelection s = selectBody(*r.root);
+    ASSERT_TRUE(s.text.found);
+    EXPECT_EQ(s.text.subtype, "HTML");
+    EXPECT_EQ(s.text.number, "1");
+    EXPECT_TRUE(s.isHtmlFallback);
+}
+
+TEST(ImapSelectBody, PicksTheBodyAndListsThePdfSeparately) {
+    const ImapBodyStructureResult r = parseBodyStructureResponse(kPdfAttachment);
+    ASSERT_TRUE(r.root.has_value());
+    const ImapBodySelection s = selectBody(*r.root);
+    ASSERT_TRUE(s.text.found);
+    EXPECT_EQ(s.text.number, "1");
+    ASSERT_EQ(s.attachments.size(), 1u);
+    EXPECT_EQ(s.attachments[0].number, "2");
+    EXPECT_EQ(s.attachments[0].filename, "árajánlat.pdf");
+    EXPECT_EQ(s.attachments[0].subtype, "PDF");
+    EXPECT_EQ(s.attachments[0].octets, 98234u);
+}
+
+TEST(ImapSelectBody, SinglePartMessageYieldsPartOneAsTheBody) {
+    const ImapBodyStructureResult r = parseBodyStructureResponse(kSinglePart);
+    ASSERT_TRUE(r.root.has_value());
+    const ImapBodySelection s = selectBody(*r.root);
+    ASSERT_TRUE(s.text.found);
+    EXPECT_EQ(s.text.number, "1");
+    EXPECT_TRUE(s.attachments.empty());
+}
+
+TEST(ImapSelectBody, NeverTakesAForwardedMessagesTextAsThisMessagesBody) {
+    const ImapBodyStructureResult r = parseBodyStructureResponse(kRfcExample);
+    ASSERT_TRUE(r.root.has_value());
+    const ImapBodySelection s = selectBody(*r.root);
+    ASSERT_TRUE(s.text.found);
+    EXPECT_EQ(s.text.number, "1") << "the body must be this message's own text";
+    // The forwarded messages are listed, not descended into, so 3.1 and 4.2.1
+    // never appear.
+    std::vector<std::string> numbers;
+    for (const ImapAttachmentRef& a : s.attachments) numbers.push_back(a.number);
+    EXPECT_EQ(numbers, (std::vector<std::string>{"2", "3", "4.1", "4.2"}));
+}
+
+TEST(ImapSelectBody, ListsAnInlineImageThatHasNoFilenameRatherThanDroppingIt) {
+    const std::string bytes =
+        "* 1 FETCH (BODYSTRUCTURE ("
+        "(\"TEXT\" \"HTML\" (\"CHARSET\" \"utf-8\") NIL NIL \"7BIT\" 500 20)"
+        "(\"IMAGE\" \"PNG\" NIL \"<logo@pelda.hu>\" NIL \"BASE64\" 4096 NIL NIL NIL)"
+        " \"RELATED\" (\"BOUNDARY\" \"=_r1\") NIL NIL))\r\n";
+    const ImapBodyStructureResult r = parseBodyStructureResponse(bytes);
+    ASSERT_TRUE(r.root.has_value());
+    const ImapBodySelection s = selectBody(*r.root);
+    EXPECT_TRUE(s.isHtmlFallback);
+    ASSERT_EQ(s.attachments.size(), 1u);
+    EXPECT_EQ(s.attachments[0].number, "2");
+    EXPECT_TRUE(s.attachments[0].filename.empty());
+    EXPECT_EQ(r.root->children[1].contentId, "<logo@pelda.hu>");
+}
+
+// ---------------------------------------------------------------------------
+// FETCH
+// ---------------------------------------------------------------------------
+
+TEST(ImapFetch, ReadsTheOrdinaryItemsAndKeysTheRecordByUid) {
+    const ImapFetchResult r = parseFetchResponse(kSinglePart);
+    ASSERT_EQ(r.status, ImapParse::Ok);
+    ASSERT_EQ(r.messages.size(), 1u);
+    const ImapFetchRecord& m = r.messages[0];
+    EXPECT_EQ(m.seq, 1u);
+    EXPECT_TRUE(m.hasUid);
+    EXPECT_EQ(m.uid, 101u);
+    ASSERT_EQ(m.flags.size(), 1u);
+    EXPECT_EQ(m.flags[0], "\\Seen");
+    EXPECT_EQ(m.internalDate, "08-Oct-2026 11:22:33 +0200");
+    EXPECT_TRUE(m.hasRfc822Size);
+    EXPECT_EQ(m.rfc822Size, 4217u);
+    EXPECT_TRUE(m.bodyStructure.has_value());
+    EXPECT_EQ(findByUid(r.messages, 101u), &r.messages[0]);
+    EXPECT_EQ(findByUid(r.messages, 999u), nullptr);
+}
+
+TEST(ImapFetch, AMissingUidIsReportedRatherThanFakedFromTheSequenceNumber) {
+    const ImapFetchResult r = parseFetchResponse("* 4 FETCH (FLAGS (\\Seen))\r\n");
+    ASSERT_EQ(r.status, ImapParse::Ok);
+    ASSERT_EQ(r.messages.size(), 1u);
+    EXPECT_FALSE(r.messages[0].hasUid);
+    EXPECT_EQ(r.messages[0].uid, 0u);
+    EXPECT_EQ(r.messages[0].seq, 4u);
+}
+
+TEST(ImapFetch, ReadsALiteralBodyPartContainingCrlfs) {
+    const ImapFetchResult r = parseFetchResponse(kBodyLiteral);
+    ASSERT_EQ(r.status, ImapParse::Ok);
+    ASSERT_EQ(r.messages.size(), 1u);
+    const ImapFetchRecord& m = r.messages[0];
+    ASSERT_EQ(m.bodyParts.count("TEXT"), 1u);
+    EXPECT_EQ(m.bodyParts.at("TEXT"), "Szia Ferenc!\r\n\r\nÜdv: Anna\r\n");
+    // The items AFTER the literal still parse, which is the whole point of
+    // counting bytes rather than splitting lines.
+    ASSERT_EQ(m.flags.size(), 1u);
+    EXPECT_EQ(m.flags[0], "\\Seen");
+}
+
+TEST(ImapFetch, APeekFetchComesBackLabelledWithoutThePeekAndStillKeysTheSame) {
+    // The .PEEK is a command-side instruction and never appears in the
+    // response. Keying by what we SENT finds nothing and reports an empty body
+    // for a message that arrived intact.
+    const std::string asSent =
+        "* 1 FETCH (UID 1 BODY.PEEK[1] {7}\r\nHello\r\n)\r\n";
+    const std::string asReturned =
+        "* 1 FETCH (UID 1 BODY[1] {7}\r\nHello\r\n)\r\n";
+    const ImapFetchResult a = parseFetchResponse(asSent);
+    const ImapFetchResult b = parseFetchResponse(asReturned);
+    ASSERT_EQ(a.status, ImapParse::Ok);
+    ASSERT_EQ(b.status, ImapParse::Ok);
+    ASSERT_EQ(a.messages.size(), 1u);
+    ASSERT_EQ(b.messages.size(), 1u);
+    EXPECT_EQ(a.messages[0].bodyParts.count("1"), 1u);
+    EXPECT_EQ(b.messages[0].bodyParts.count("1"), 1u);
+    EXPECT_EQ(a.messages[0].bodyParts.at("1"), "Hello\r\n");
+    EXPECT_EQ(b.messages[0].bodyParts.at("1"), "Hello\r\n");
+}
+
+TEST(ImapFetch, StripsAPartialFetchsOffsetSuffixFromTheSectionKey) {
+    const ImapFetchResult r =
+        parseFetchResponse("* 1 FETCH (UID 1 BODY[1]<0> {7}\r\nHello\r\n)\r\n");
+    ASSERT_EQ(r.status, ImapParse::Ok);
+    ASSERT_EQ(r.messages.size(), 1u);
+    EXPECT_EQ(r.messages[0].bodyParts.count("1"), 1u);
+}
+
+TEST(ImapFetch, KeepsASectionNameThatContainsSpacesAndParenthesesInOnePiece) {
+    // `[` and `]` are not IMAP delimiters, so the tokenizer splits this item
+    // name into three tokens. Left split, the returned header block is lost.
+    const std::string bytes =
+        "* 1 FETCH (UID 1 BODY[HEADER.FIELDS (SUBJECT FROM)] {39}\r\n"
+        "Subject: Teszt\r\nFrom: anna@pelda.hu\r\n\r\n)\r\n";
+    const ImapFetchResult r = parseFetchResponse(bytes);
+    ASSERT_EQ(r.status, ImapParse::Ok);
+    ASSERT_EQ(r.messages.size(), 1u);
+    const auto& parts = r.messages[0].bodyParts;
+    ASSERT_EQ(parts.count("HEADER.FIELDS (SUBJECT FROM)"), 1u)
+        << "the section name was split and the data lost";
+    EXPECT_EQ(parts.at("HEADER.FIELDS (SUBJECT FROM)"),
+              "Subject: Teszt\r\nFrom: anna@pelda.hu\r\n\r\n");
+}
+
+TEST(ImapFetch, AnEmptySectionIsTheWholeMessage) {
+    const ImapFetchResult r =
+        parseFetchResponse("* 1 FETCH (UID 1 BODY[] {7}\r\nHello\r\n)\r\n");
+    ASSERT_EQ(r.status, ImapParse::Ok);
+    ASSERT_EQ(r.messages.size(), 1u);
+    EXPECT_EQ(r.messages[0].bodyParts.count(""), 1u);
+}
+
+TEST(ImapFetch, FoldsRfc822SpellingsOntoTheSameSectionKeys) {
+    const ImapFetchResult r =
+        parseFetchResponse("* 1 FETCH (UID 1 RFC822.TEXT {7}\r\nHello\r\n)\r\n");
+    ASSERT_EQ(r.status, ImapParse::Ok);
+    ASSERT_EQ(r.messages.size(), 1u);
+    EXPECT_EQ(r.messages[0].bodyParts.count("TEXT"), 1u);
+}
+
+TEST(ImapFetch, IgnoresAnUnknownItemInsteadOfFailingTheWholeResponse) {
+    // Servers volunteer MODSEQ and X-GM-* unasked. Refusing the response over
+    // one of them would make the mailbox unreadable on that server.
+    const std::string bytes =
+        "* 6 FETCH (UID 606 MODSEQ (123456) X-GM-MSGID 1562258799411433683 "
+        "FLAGS (\\Seen \\Flagged) X-GM-LABELS (\\Important \"Munka\") "
+        "RFC822.SIZE 99)\r\n";
+    const ImapFetchResult r = parseFetchResponse(bytes);
+    ASSERT_EQ(r.status, ImapParse::Ok);
+    ASSERT_EQ(r.messages.size(), 1u);
+    const ImapFetchRecord& m = r.messages[0];
+    EXPECT_EQ(m.uid, 606u);
+    EXPECT_EQ(m.rfc822Size, 99u);
+    ASSERT_EQ(m.flags.size(), 2u);
+    EXPECT_EQ(m.flags[1], "\\Flagged");
+    EXPECT_EQ(m.unknownItems.size(), 3u) << "the unknowns must be recorded, not silent";
+}
+
+TEST(ImapFetch, SkipsResponseLinesThatAreNotFetches) {
+    const std::string bytes =
+        "* 23 EXISTS\r\n"
+        "* 2 RECENT\r\n"
+        "* OK [UIDVALIDITY 1234567890] UIDs valid\r\n"
+        "* 1 FETCH (UID 101 RFC822.SIZE 10)\r\n"
+        "A004 OK FETCH completed\r\n";
+    const ImapFetchResult r = parseFetchResponse(bytes);
+    ASSERT_EQ(r.status, ImapParse::Ok);
+    ASSERT_EQ(r.messages.size(), 1u);
+    EXPECT_EQ(r.messages[0].uid, 101u);
+}
+
+TEST(ImapFetch, ReadsSeveralMessagesFromOneBuffer) {
+    const std::string bytes =
+        "* 1 FETCH (UID 101 RFC822.SIZE 10)\r\n"
+        "* 2 FETCH (UID 102 RFC822.SIZE 20)\r\n"
+        "* 3 FETCH (UID 103 RFC822.SIZE 30)\r\n"
+        "A005 OK FETCH completed\r\n";
+    const ImapFetchResult r = parseFetchResponse(bytes);
+    ASSERT_EQ(r.status, ImapParse::Ok);
+    ASSERT_EQ(r.messages.size(), 3u);
+    EXPECT_EQ(r.messages[2].uid, 103u);
+    EXPECT_EQ(r.consumed, bytes.size());
+}
+
+// --- Truncation ------------------------------------------------------------
+
+TEST(ImapFetch, ReportsNeedMoreWhenTheBufferEndsInsideALiteral) {
+    // The missing bytes may themselves contain CRLF, so a line-based reader
+    // would decide this line was complete and parse nonsense.
+    const std::string truncated =
+        "* 7 FETCH (UID 707 BODY[TEXT] {28}\r\nSzia Fe";
+    const ImapFetchResult r = parseFetchResponse(truncated);
+    EXPECT_EQ(r.status, ImapParse::NeedMore);
+    EXPECT_TRUE(r.messages.empty());
+    EXPECT_EQ(r.consumed, 0u);
+}
+
+TEST(ImapFetch, ReportsNeedMoreWhenTheLiteralCountItselfIsSplit) {
+    const ImapFetchResult r = parseFetchResponse("* 7 FETCH (UID 707 BODY[TEXT] {2");
+    EXPECT_EQ(r.status, ImapParse::NeedMore);
+}
+
+TEST(ImapFetch, KeepsTheCompleteMessagesAndSaysWhereToResume) {
+    const std::string first = "* 1 FETCH (UID 101 RFC822.SIZE 10)\r\n";
+    const std::string bytes = first + "* 2 FETCH (UID 102 BODY[TEXT] {28}\r\nSzia";
+    const ImapFetchResult r = parseFetchResponse(bytes);
+    EXPECT_EQ(r.status, ImapParse::NeedMore);
+    ASSERT_EQ(r.messages.size(), 1u) << "the first message parsed and must not be thrown away";
+    EXPECT_EQ(r.messages[0].uid, 101u);
+    EXPECT_EQ(r.consumed, first.size());
+}
+
+TEST(ImapFetch, ReportsNeedMoreOnAnEmptyBuffer) {
+    EXPECT_EQ(parseFetchResponse("").status, ImapParse::NeedMore);
+}
+
+// --- Hostile input ---------------------------------------------------------
+
+TEST(ImapFetch, ReportsMalformedRatherThanThrowingOnAnUnbalancedResponse) {
+    const ImapFetchResult r = parseFetchResponse("* 1 FETCH (UID 101 FLAGS (\\Seen)))\r\n");
+    EXPECT_EQ(r.status, ImapParse::Malformed);
+    EXPECT_TRUE(r.messages.empty()) << "nothing from a malformed response may be trusted";
+}
+
+TEST(ImapFetch, ReportsMalformedOnABareCarriageReturn) {
+    EXPECT_EQ(parseFetchResponse("* 1 FETCH (UID 1)\rX").status, ImapParse::Malformed);
+}
+
+TEST(ImapFetch, SurvivesAFetchItemListThatEndsAfterAnItemName) {
+    // A name with no value: ignored, not indexed past the end.
+    const ImapFetchResult r = parseFetchResponse("* 1 FETCH (UID 1 RFC822.SIZE)\r\n");
+    ASSERT_EQ(r.status, ImapParse::Ok);
+    ASSERT_EQ(r.messages.size(), 1u);
+    EXPECT_EQ(r.messages[0].uid, 1u);
+    EXPECT_FALSE(r.messages[0].hasRfc822Size);
+}
+
+TEST(ImapFetch, SurvivesAWildlyTruncatedBodyStructure) {
+    const ImapFetchResult r = parseFetchResponse("* 1 FETCH (BODYSTRUCTURE (\"TEXT\"))\r\n");
+    ASSERT_EQ(r.status, ImapParse::Ok);
+    ASSERT_EQ(r.messages.size(), 1u);
+    ASSERT_TRUE(r.messages[0].bodyStructure.has_value());
+    EXPECT_EQ(r.messages[0].bodyStructure->type, "TEXT");
+    EXPECT_TRUE(r.messages[0].bodyStructure->subtype.empty());
+    EXPECT_FALSE(r.messages[0].bodyStructure->hasOctets);
+}
+
+TEST(ImapFetch, RefusesANonNumericSizeInsteadOfStoringZeroAsIfItWereReal) {
+    const ImapFetchResult r = parseFetchResponse("* 1 FETCH (UID 1 RFC822.SIZE abc)\r\n");
+    ASSERT_EQ(r.status, ImapParse::Ok);
+    ASSERT_EQ(r.messages.size(), 1u);
+    EXPECT_FALSE(r.messages[0].hasRfc822Size);
+}
+
+TEST(ImapFetch, RefusesNestingDeeperThanTheDepthCapInsideAFetch) {
+    std::string bytes = "* 1 FETCH (BODYSTRUCTURE ";
+    for (size_t i = 0; i < kMaxSexpDepth + 4; ++i) bytes += '(';
+    bytes += "\"TEXT\"";
+    for (size_t i = 0; i < kMaxSexpDepth + 4; ++i) bytes += ')';
+    bytes += ")\r\n";
+    const ImapFetchResult r = parseFetchResponse(bytes);
+    EXPECT_EQ(r.status, ImapParse::Malformed);
+}
+
+// --- JSON projection -------------------------------------------------------
+
+TEST(ImapFetchJson, ProjectsSectionNamesButNeverTheirBytes) {
+    const ImapFetchResult r = parseFetchResponse(kBodyLiteral);
+    ASSERT_EQ(r.messages.size(), 1u);
+    const nlohmann::json j = toJson(r.messages[0]);
+    EXPECT_EQ(j.at("uid"), 707u);
+    ASSERT_TRUE(j.at("body_sections").is_array());
+    EXPECT_EQ(j.at("body_sections")[0], "TEXT");
+    // A part can be megabytes and the JS heap it would land in is 64 MiB.
+    EXPECT_EQ(j.dump().find("Szia Ferenc"), std::string::npos);
+}
+
+TEST(ImapFetchJson, ProjectsThePartNumbersAPeekWouldNeed) {
+    const ImapBodyStructureResult r = parseBodyStructureResponse(kRfcExample);
+    ASSERT_TRUE(r.root.has_value());
+    const nlohmann::json j = toJson(*r.root);
+    EXPECT_EQ(j.at("parts")[2].at("number"), "3");
+    EXPECT_EQ(j.at("parts")[2].at("parts")[0].at("parts")[1].at("number"), "3.2");
+}

+ 203 - 0
runner/tests/mail_net_test.cpp

@@ -0,0 +1,203 @@
+#include <gtest/gtest.h>
+
+#include <curl/curl.h>
+
+#include "net/curl_errors.hpp"
+#include "net/mail_budget.hpp"
+#include "net/xfer_abort.hpp"
+
+using namespace svapi::runner::net;
+
+// ---------------------------------------------------------------- mail budget
+
+TEST(MailBudget, ConnectAndReadTogetherFitInsideTheBudget) {
+    MailBudgetRequest in;
+    in.remainingBudgetMs = 10000;
+    const MailBudget b = resolveMailBudget(in);
+    EXPECT_LE(b.connectSec + b.readSec, 10);
+    EXPECT_EQ(b.totalMs, 10000);
+}
+
+TEST(MailBudget, ConnectNeverTakesMoreThanHalfTheAvailableTime) {
+    MailBudgetRequest in;
+    in.remainingBudgetMs = 10000;
+    in.configuredConnectSec = 30;  // the operator asked for far more than the budget
+    const MailBudget b = resolveMailBudget(in);
+    EXPECT_EQ(b.connectSec, 5);
+    // This is the regression the embedding budget was written for: a connect
+    // stall must not be able to burn time outside the budget.
+    EXPECT_LE(b.connectSec + b.readSec, 10);
+}
+
+TEST(MailBudget, AConfiguredTimeoutNarrowsButNeverWidens) {
+    MailBudgetRequest in;
+    in.remainingBudgetMs = 10000;
+    in.configuredReadSec = 2;
+    const MailBudget b = resolveMailBudget(in);
+    EXPECT_EQ(b.readSec, 2);
+}
+
+TEST(MailBudget, TheScriptsOwnTimeoutIsReportedAsTheBindingConstraint) {
+    MailBudgetRequest in;
+    in.remainingBudgetMs = 10000;
+    in.callTimeoutMs = 1500;
+    const MailBudget b = resolveMailBudget(in);
+    EXPECT_TRUE(b.boundByCall);
+    EXPECT_EQ(b.totalMs, 1500);
+}
+
+TEST(MailBudget, AScriptTimeoutLargerThanTheBudgetDoesNotWidenIt) {
+    MailBudgetRequest in;
+    in.remainingBudgetMs = 3000;
+    in.callTimeoutMs = 60000;
+    const MailBudget b = resolveMailBudget(in);
+    EXPECT_FALSE(b.boundByCall);
+    EXPECT_EQ(b.totalMs, 3000);
+}
+
+TEST(MailBudget, EveryPhaseKeepsAOneSecondFloorSoNothingIsUnbounded) {
+    MailBudgetRequest in;
+    in.remainingBudgetMs = 1;
+    const MailBudget b = resolveMailBudget(in);
+    // 0 would mean "no timeout" to the client, which is the unbounded call this
+    // whole file exists to prevent.
+    EXPECT_GE(b.connectSec, 1);
+    EXPECT_GE(b.readSec, 1);
+}
+
+TEST(MailBudget, NoBudgetLeftStillYieldsAZeroTotalSoTheCallerRefuses) {
+    MailBudgetRequest in;
+    in.remainingBudgetMs = 0;
+    const MailBudget b = resolveMailBudget(in);
+    EXPECT_EQ(b.totalMs, 0);
+}
+
+TEST(MailBudget, TheTotalIsTheWholeConversationNotJustOneRoundTrip) {
+    // The reason this field exists: the per-phase read timeout bounds each
+    // quiet period, so five round trips each answering just inside it would
+    // otherwise run five times as long as the budget.
+    MailBudgetRequest in;
+    in.remainingBudgetMs = 4000;
+    const MailBudget b = resolveMailBudget(in);
+    EXPECT_EQ(b.totalMs, 4000);
+    EXPECT_LT(b.readSec, 4);
+}
+
+// ----------------------------------------------------------- abort decision
+
+TEST(XferAbort, AHealthyTransferIsNotAborted) {
+    EXPECT_EQ(shouldAbortTransfer(1000, 500, 10, 1024), AbortReason::None);
+}
+
+TEST(XferAbort, ATransferOfExactlyTheCapIsAllowed) {
+    // A file of exactly the limit is within the limit.
+    EXPECT_EQ(shouldAbortTransfer(1000, 500, 1024, 1024), AbortReason::None);
+}
+
+TEST(XferAbort, OneByteOverTheCapAborts) {
+    EXPECT_EQ(shouldAbortTransfer(1000, 500, 1025, 1024), AbortReason::TooLarge);
+}
+
+TEST(XferAbort, ADeadlineExactlyNowAborts) {
+    // A deadline of exactly now is spent, unlike a size of exactly the cap.
+    EXPECT_EQ(shouldAbortTransfer(1000, 1000, 10, 1024), AbortReason::Deadline);
+}
+
+TEST(XferAbort, SizeIsReportedAheadOfTimeWhenBothAreBreached) {
+    // Both remedies are different and the size one is actionable, so it wins.
+    EXPECT_EQ(shouldAbortTransfer(1000, 5000, 99999, 1024), AbortReason::TooLarge);
+}
+
+TEST(XferAbort, AZeroCapOrZeroDeadlineMeansNoLimitRatherThanAnImmediateAbort) {
+    EXPECT_EQ(shouldAbortTransfer(0, 99999, 99999, 0), AbortReason::None);
+}
+
+// -------------------------------------------------------------- error mapping
+
+TEST(MailErrors, SuccessIsSuccess) {
+    EXPECT_TRUE(mailFailureFor(CURLE_OK, 250, "", false).ok());
+}
+
+TEST(MailErrors, ATransportSuccessCarryingARefusalReplyCodeIsStillAFailure) {
+    // curl reports OK because the conversation worked; the server said no.
+    const MailFailure f = mailFailureFor(CURLE_OK, 550, "mailbox unavailable", true);
+    EXPECT_FALSE(f.ok());
+    EXPECT_EQ(f.status, 422);
+    EXPECT_EQ(f.slug, "mail_rejected");
+}
+
+TEST(MailErrors, AFourHundredReplyIsTransientAndRetryableByTheProtocolsOwnDefinition) {
+    const MailFailure f = mailFailureForReplyCode(451, "try again later");
+    EXPECT_EQ(f.status, 503);
+    EXPECT_EQ(f.slug, "mail_server_busy");
+    EXPECT_TRUE(f.retryable);
+}
+
+TEST(MailErrors, AFiveHundredReplyIsPermanentAndNotRetryable) {
+    const MailFailure f = mailFailureForReplyCode(550, "no such user");
+    EXPECT_EQ(f.status, 422);
+    EXPECT_FALSE(f.retryable);
+    // The server's own words survive, because they say which of the many 550
+    // causes it was.
+    EXPECT_NE(f.message.find("no such user"), std::string::npos);
+    EXPECT_NE(f.message.find("550"), std::string::npos);
+}
+
+TEST(MailErrors, ARejectedLoginIsNeverRetryableBecauseRetryingLocksTheAccount) {
+    const MailFailure f = mailFailureFor(CURLE_LOGIN_DENIED, 0, "", false);
+    EXPECT_EQ(f.slug, "mail_auth_failed");
+    EXPECT_FALSE(f.retryable);
+}
+
+TEST(MailErrors, ACertificateThatDoesNotVerifyIsNeverRetryableAndKeepsItsOwnSlug) {
+    const MailFailure f = mailFailureFor(CURLE_PEER_FAILED_VERIFICATION, 0, "", false);
+    EXPECT_EQ(f.slug, "mail_tls_untrusted");
+    EXPECT_FALSE(f.retryable);
+    // It must not be mistakable for a network blip in a log, because the
+    // credentials were about to go over that connection.
+    EXPECT_NE(f.slug, "mail_unreachable");
+}
+
+TEST(MailErrors, AReadThatTimesOutMayRetryButASendMayNot) {
+    EXPECT_TRUE(mailFailureFor(CURLE_OPERATION_TIMEDOUT, 0, "", false).retryable);
+    // The whole point of the sideEffecting parameter: a duplicate e-mail
+    // cannot be recalled.
+    EXPECT_FALSE(mailFailureFor(CURLE_OPERATION_TIMEDOUT, 0, "", true).retryable);
+}
+
+TEST(MailErrors, ATimeoutIsAGatewayTimeoutRatherThanRetryAsIs) {
+    // 503 means "retry as-is", which is dangerous advice for anything that may
+    // already have been delivered.
+    EXPECT_EQ(mailFailureFor(CURLE_OPERATION_TIMEDOUT, 0, "", true).status, 504);
+}
+
+TEST(MailErrors, ALostConnectionMidSendIsDeliveredThenUnansweredAndNotRetryable) {
+    EXPECT_TRUE(mailFailureFor(CURLE_RECV_ERROR, 0, "", false).retryable);
+    EXPECT_FALSE(mailFailureFor(CURLE_RECV_ERROR, 0, "", true).retryable);
+}
+
+TEST(MailErrors, DnsFailuresAreRetryableBecauseNothingReachedTheServer) {
+    EXPECT_TRUE(mailFailureFor(CURLE_COULDNT_RESOLVE_HOST, 0, "", true).retryable);
+    EXPECT_TRUE(mailFailureFor(CURLE_COULDNT_CONNECT, 0, "", true).retryable);
+}
+
+TEST(MailErrors, CurlsOwnMessageIsPreferredOverTheCodesName) {
+    // The code's name does not carry the host or the TLS reason, and
+    // "could not connect" without the address is unactionable.
+    const MailFailure f =
+        mailFailureFor(CURLE_COULDNT_CONNECT, 0, "Failed to connect to mail.example.com port 993",
+                       false);
+    EXPECT_NE(f.message.find("mail.example.com"), std::string::npos);
+}
+
+TEST(MailErrors, AnUnmappedCodeIsReportedAsOursRatherThanGuessedAsTheCallersFault) {
+    const MailFailure f = mailFailureFor(CURLE_CHUNK_FAILED, 0, "", false);
+    EXPECT_EQ(f.status, 502);
+    EXPECT_NE(f.status, 422);
+}
+
+TEST(MailErrors, AMalformedUrlIsTheCallersMistakeAndNotRetryable) {
+    const MailFailure f = mailFailureFor(CURLE_URL_MALFORMAT, 0, "", false);
+    EXPECT_EQ(f.status, 422);
+    EXPECT_FALSE(f.retryable);
+}

+ 239 - 0
runner/tests/mail_session_test.cpp

@@ -0,0 +1,239 @@
+#include <gtest/gtest.h>
+
+#include <algorithm>
+
+#include "fake_mail_server.hpp"
+#include "net/mail_session.hpp"
+
+using namespace svapi::runner::net;
+using svapi::testing::FakeImapServer;
+using svapi::testing::FakeSmtpServer;
+
+namespace {
+
+MailTransferOptions optionsFor(int64_t budgetMs = 5000, int64_t maxBytes = 1 << 20) {
+    MailBudgetRequest req;
+    req.remainingBudgetMs = budgetMs;
+    MailTransferOptions opt;
+    opt.budget = resolveMailBudget(req);
+    opt.maxBytes = maxBytes;
+    return opt;
+}
+
+MailAccount accountFor(uint16_t port) {
+    MailAccount a;
+    a.host = "127.0.0.1";
+    a.port = port;
+    a.user = "someone@example.com";
+    a.password = "correct-horse-battery-staple";
+    a.tls = false;  // the fake speaks plaintext; TLS is covered against real servers
+    a.startTls = false;
+    return a;
+}
+
+bool anyContains(const std::vector<std::string>& lines, const std::string& needle) {
+    return std::any_of(lines.begin(), lines.end(),
+                       [&](const std::string& l) { return l.find(needle) != std::string::npos; });
+}
+
+class ImapFixture : public ::testing::Test {
+protected:
+    void SetUp() override { ASSERT_TRUE(server.start()); }
+    void TearDown() override { server.stop(); }
+    FakeImapServer server;
+};
+
+} // namespace
+
+TEST(MailGlobal, TheRunnerRefusesToStartOnACurlThatIsNotThreadSafe) {
+    // Not a mock: this asserts the real libcurl we link is usable from the
+    // pool, which is the condition the runner checks at boot. If this ever
+    // fails, the runner is right to refuse to start.
+    EXPECT_EQ(mailGlobalInit(), std::string());
+    mailGlobalCleanup();
+}
+
+TEST_F(ImapFixture, AFetchGoesThroughCustomRequestAndTouchesNoFlag) {
+    ASSERT_EQ(mailGlobalInit(), std::string());
+    ImapSession session;
+    ASSERT_TRUE(session.open(accountFor(server.port()), optionsFor()).ok());
+
+    std::string response;
+    const MailFailure f = session.command("INBOX", "UID FETCH 7 BODY.PEEK[]", response);
+    ASSERT_TRUE(f.ok()) << f.slug << ": " << f.message;
+    EXPECT_NE(response.find("body text"), std::string::npos);
+
+    const std::vector<std::string> wire = server.received();
+    EXPECT_TRUE(anyContains(wire, "UID FETCH 7 BODY.PEEK[]"));
+    // The whole reason this path uses CUSTOMREQUEST rather than curl's ";UID="
+    // URL form: that form always sets \Seen, and undoing it afterwards with a
+    // STORE removes a flag it may not have set, turning an already-read message
+    // unread. No STORE must ever appear.
+    EXPECT_FALSE(anyContains(wire, "STORE"));
+    EXPECT_FALSE(anyContains(wire, "+FLAGS"));
+    EXPECT_FALSE(anyContains(wire, "-FLAGS"));
+    mailGlobalCleanup();
+}
+
+TEST_F(ImapFixture, SelectUntaggedChatterDoesNotLandInTheCommandsResponse) {
+    // MEASURED, not assumed. The question this answers: when a custom request
+    // runs against a mailbox in the URL, curl issues the SELECT itself, so does
+    // the caller's write callback also receive the SELECT's untagged lines?
+    // Whatever the answer, a parser has to be written for it, which is why it
+    // is pinned by a test rather than left to be rediscovered.
+    ASSERT_EQ(mailGlobalInit(), std::string());
+    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());
+
+    EXPECT_NE(response.find("FETCH"), std::string::npos);
+    EXPECT_EQ(response.find("EXISTS"), std::string::npos)
+        << "SELECT chatter reached the command response; the FETCH parser must tolerate it. "
+           "Actual response was:\n"
+        << response;
+    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
+    // and what gets an account throttled. One LOGIN for three commands is the
+    // observable form of that.
+    ASSERT_EQ(mailGlobalInit(), std::string());
+    ImapSession session;
+    ASSERT_TRUE(session.open(accountFor(server.port()), optionsFor()).ok());
+
+    std::string a, b, c;
+    ASSERT_TRUE(session.command("INBOX", "UID SEARCH ALL", a).ok());
+    ASSERT_TRUE(session.command("INBOX", "UID FETCH 7 BODY.PEEK[]", b).ok());
+    ASSERT_TRUE(session.command("INBOX", "UID FETCH 9 BODY.PEEK[]", c).ok());
+
+    const std::vector<std::string> wire = server.received();
+    const long logins = std::count_if(wire.begin(), wire.end(), [](const std::string& l) {
+        return l.find("LOGIN") != std::string::npos;
+    });
+    EXPECT_EQ(logins, 1);
+    mailGlobalCleanup();
+}
+
+TEST_F(ImapFixture, ThePasswordNeverReachesTheServersTranscript) {
+    // The fixture masks LOGIN before recording it. Asserted here rather than
+    // trusted, because a transcript that leaks a credential survives in a CI
+    // log long after the test has been forgotten.
+    ASSERT_EQ(mailGlobalInit(), std::string());
+    ImapSession session;
+    const MailAccount account = accountFor(server.port());
+    ASSERT_TRUE(session.open(account, optionsFor()).ok());
+    std::string response;
+    ASSERT_TRUE(session.command("INBOX", "UID SEARCH ALL", response).ok());
+
+    EXPECT_FALSE(anyContains(server.received(), account.password));
+    mailGlobalCleanup();
+}
+
+TEST_F(ImapFixture, AResponseLargerThanTheRunMayLoadIsRefusedAsTooLargeNotAsATimeout) {
+    ASSERT_EQ(mailGlobalInit(), std::string());
+    server.messageBody = std::string(64 * 1024, 'x');
+    ImapSession session;
+    ASSERT_TRUE(session.open(accountFor(server.port()), optionsFor(5000, 4096)).ok());
+
+    std::string response;
+    const MailFailure f = session.command("INBOX", "UID FETCH 7 BODY.PEEK[]", response);
+    ASSERT_FALSE(f.ok());
+    // The remedies differ, so the answers must differ: a caller told "timeout"
+    // for an oversized mailbox retries forever.
+    EXPECT_EQ(f.status, 413);
+    EXPECT_EQ(f.slug, "mail_too_large");
+    EXPECT_EQ(session.lastAbort(), AbortReason::TooLarge);
+    mailGlobalCleanup();
+}
+
+TEST_F(ImapFixture, AFailedCommandIsReportedWithItsOwnReasonRatherThanGenerically) {
+    ASSERT_EQ(mailGlobalInit(), std::string());
+    ImapSession session;
+    ASSERT_TRUE(session.open(accountFor(server.port()), optionsFor()).ok());
+    std::string response;
+    const MailFailure f = session.command("INBOX", "NONSENSE COMMAND", response);
+    EXPECT_FALSE(f.ok());
+    mailGlobalCleanup();
+}
+
+TEST(SmtpSend, AMessageIsDeliveredWithItsEnvelopeSeparateFromItsHeaders) {
+    ASSERT_EQ(mailGlobalInit(), std::string());
+    FakeSmtpServer server;
+    ASSERT_TRUE(server.start());
+
+    MailEnvelope envelope;
+    envelope.sender = "sender@example.com";
+    // The envelope carries the Bcc recipient; the message must not.
+    envelope.recipients = {"to@example.com", "bcc@example.com"};
+    const std::string message =
+        "From: sender@example.com\r\nTo: to@example.com\r\nSubject: hello\r\n\r\nbody\r\n";
+
+    const MailFailure f = smtpSend(accountFor(server.port()), optionsFor(), envelope, message);
+    ASSERT_TRUE(f.ok()) << f.slug << ": " << f.message;
+
+    const std::vector<std::string> wire = server.received();
+    EXPECT_TRUE(anyContains(wire, "MAIL FROM"));
+    EXPECT_TRUE(anyContains(wire, "bcc@example.com"));
+    // Present in the envelope, absent from the message. The classic leak.
+    EXPECT_EQ(server.dataReceived().find("bcc@example.com"), std::string::npos);
+    EXPECT_NE(server.dataReceived().find("Subject: hello"), std::string::npos);
+    server.stop();
+    mailGlobalCleanup();
+}
+
+TEST(SmtpSend, ABodyLineOfASinglePeriodSurvivesIntactAndDoesNotEndTheMessage) {
+    // curl dot-stuffs on the way out, so the renderer must NOT. If both do it
+    // the line arrives as "..", and if neither does the message is truncated at
+    // that line. Either way it is silent, which is why this is pinned.
+    ASSERT_EQ(mailGlobalInit(), std::string());
+    FakeSmtpServer server;
+    ASSERT_TRUE(server.start());
+
+    MailEnvelope envelope;
+    envelope.sender = "sender@example.com";
+    envelope.recipients = {"to@example.com"};
+    const std::string message =
+        "From: sender@example.com\r\nSubject: dots\r\n\r\nbefore\r\n.\r\nafter\r\n";
+
+    ASSERT_TRUE(smtpSend(accountFor(server.port()), optionsFor(), envelope, message).ok());
+    const std::string got = server.dataReceived();
+    EXPECT_NE(got.find("before"), std::string::npos);
+    EXPECT_NE(got.find("after"), std::string::npos) << "the message was truncated at the lone dot";
+    EXPECT_EQ(got.find("\r\n..\r\n"), std::string::npos) << "the body was dot-stuffed twice";
+    server.stop();
+    mailGlobalCleanup();
+}
+
+TEST(SmtpSend, AServerRefusalIsTheCallersProblemAndNotRetryable) {
+    ASSERT_EQ(mailGlobalInit(), std::string());
+    FakeSmtpServer server;
+    server.dataOutcome = "550 5.1.1 No such recipient\r\n";
+    ASSERT_TRUE(server.start());
+
+    MailEnvelope envelope;
+    envelope.sender = "sender@example.com";
+    envelope.recipients = {"nobody@example.com"};
+    const MailFailure f =
+        smtpSend(accountFor(server.port()), optionsFor(), envelope, "Subject: x\r\n\r\nbody\r\n");
+
+    ASSERT_FALSE(f.ok());
+    EXPECT_EQ(f.status, 422);
+    EXPECT_FALSE(f.retryable);
+    EXPECT_NE(f.message.find("550"), std::string::npos);
+    server.stop();
+    mailGlobalCleanup();
+}
+
+TEST(SmtpSend, AnEmptyEnvelopeIsRefusedBeforeAnySocketIsOpened) {
+    MailEnvelope noSender;
+    noSender.recipients = {"to@example.com"};
+    EXPECT_EQ(smtpSend(accountFor(1), optionsFor(), noSender, "x").slug, "mail_no_sender");
+
+    MailEnvelope noRecipient;
+    noRecipient.sender = "from@example.com";
+    EXPECT_EQ(smtpSend(accountFor(1), optionsFor(), noRecipient, "x").slug, "mail_no_recipient");
+}

+ 663 - 0
runner/tests/mime_build_test.cpp

@@ -0,0 +1,663 @@
+// Assembling an outgoing message.
+//
+// Two of these are security tests rather than formatting tests: a Bcc that
+// reaches a header discloses one recipient to another, and a CR or LF that
+// survives into a value lets the caller write headers of its own. Both are
+// asserted on the rendered bytes, not on an intermediate structure.
+#include <gtest/gtest.h>
+
+#include "functions/mime_words.hpp"
+#include "net/mime_build.hpp"
+
+using svapi::functions::MimeWords;
+using svapi::runner::net::buildMail;
+using svapi::runner::net::BuiltMail;
+using svapi::runner::net::mailBoundary;
+using svapi::runner::net::MailAttachment;
+using svapi::runner::net::MailBuildError;
+using svapi::runner::net::MailHeader;
+using svapi::runner::net::MailMessage;
+
+namespace {
+
+// A fixed seed everywhere, so every boundary in this file is predictable and
+// the bytes can be asserted exactly.
+constexpr uint64_t kSeed = 7;
+
+MailMessage minimalMessage() {
+    MailMessage msg;
+    msg.from = "alice@example.com";
+    msg.to = {"bob@example.com"};
+    msg.subject = "Hello";
+    msg.text = "Hi";
+    return msg;
+}
+
+bool contains(const std::string& haystack, const std::string& needle) {
+    return haystack.find(needle) != std::string::npos;
+}
+
+// The value of one header as it was rendered, unfolded back onto one line.
+std::string headerValue(const std::string& data, const std::string& name) {
+    const std::string key = name + ":";
+    std::size_t start = std::string::npos;
+    if (data.compare(0, key.size(), key) == 0)
+        start = key.size();
+    else if (const std::size_t at = data.find("\r\n" + key); at != std::string::npos)
+        start = at + 2 + key.size();
+    if (start == std::string::npos) return {};
+
+    std::string out;
+    std::size_t i = start;
+    while (i < data.size()) {
+        if (data.compare(i, 2, "\r\n") == 0) {
+            if (i + 2 < data.size() && (data[i + 2] == ' ' || data[i + 2] == '\t')) {
+                i += 3;
+                out += ' ';
+                continue;
+            }
+            break;
+        }
+        out += data[i++];
+    }
+    while (!out.empty() && out.front() == ' ') out.erase(out.begin());
+    return out;
+}
+
+// Encoded words on one line, and complete encoded words on one line. Counted
+// separately so a split word shows up as a mismatch; "?=" is matched without
+// overlap because a word's own terminator reads as "=?=" when the base64
+// payload happens to end in padding.
+std::pair<std::size_t, std::size_t> encodedWordCounts(const std::string& line) {
+    std::size_t opens = 0;
+    for (std::size_t at = line.find("=?UTF-8?"); at != std::string::npos;
+         at = line.find("=?UTF-8?", at + 8))
+        ++opens;
+    std::size_t closes = 0;
+    for (std::size_t at = line.find("?="); at != std::string::npos; at = line.find("?=", at + 2))
+        ++closes;
+    return {opens, closes};
+}
+
+}  // namespace
+
+TEST(MimeBuild, ATextOnlyMessageIsASinglePlainPartWithNoMultipartWrapper) {
+    MailMessage msg = minimalMessage();
+    msg.from = "Alice <alice@example.com>";
+    msg.text = "Hi there.\nBye";
+    msg.date = "Thu, 08 Oct 2026 12:00:00 +0000";
+    msg.messageId = "<abc@example.com>";
+
+    const BuiltMail built = buildMail(msg, kSeed);
+
+    EXPECT_EQ(built.data,
+              "Date: Thu, 08 Oct 2026 12:00:00 +0000\r\n"
+              "From: Alice <alice@example.com>\r\n"
+              "To: bob@example.com\r\n"
+              "Subject: Hello\r\n"
+              "Message-ID: <abc@example.com>\r\n"
+              "MIME-Version: 1.0\r\n"
+              "Content-Type: text/plain; charset=UTF-8\r\n"
+              "Content-Transfer-Encoding: quoted-printable\r\n"
+              "\r\n"
+              "Hi there.\r\n"
+              "Bye\r\n");
+    EXPECT_TRUE(built.boundaries.empty()) << "a single part needs no boundary";
+}
+
+TEST(MimeBuild, TheEnvelopeCarriesBareAddressesNotTheHeaderForms) {
+    MailMessage msg = minimalMessage();
+    msg.from = "Alice <alice@example.com>";
+    msg.to = {"Bob <bob@example.com>"};
+    msg.cc = {"\"Cecil, C\" <cecil@example.com>"};
+
+    const BuiltMail built = buildMail(msg, kSeed);
+
+    EXPECT_EQ(built.envelopeFrom, "alice@example.com");
+    EXPECT_EQ(built.envelopeRecipients,
+              (std::vector<std::string>{"bob@example.com", "cecil@example.com"}));
+}
+
+TEST(MimeBuild, ARepeatedRecipientIsSentOnceOnTheEnvelope) {
+    MailMessage msg = minimalMessage();
+    msg.to = {"bob@example.com", "Bob <bob@example.com>"};
+    msg.bcc = {"bob@example.com"};
+
+    EXPECT_EQ(buildMail(msg, kSeed).envelopeRecipients,
+              (std::vector<std::string>{"bob@example.com"}));
+}
+
+TEST(MimeBuild, ABccRecipientIsOnTheEnvelopeAndInNoHeader) {
+    MailMessage msg = minimalMessage();
+    msg.cc = {"cecil@example.com"};
+    msg.bcc = {"secret@example.com", "Hidden One <hidden@example.com>"};
+
+    const BuiltMail built = buildMail(msg, kSeed);
+
+    EXPECT_EQ(built.envelopeRecipients,
+              (std::vector<std::string>{"bob@example.com", "cecil@example.com",
+                                        "secret@example.com", "hidden@example.com"}));
+    // Nowhere in the rendered message, not just absent from a Bcc header: the
+    // address itself must not appear, in any header or any part.
+    EXPECT_FALSE(contains(built.data, "secret@example.com"));
+    EXPECT_FALSE(contains(built.data, "hidden@example.com"));
+    EXPECT_FALSE(contains(built.data, "Hidden One"));
+    EXPECT_FALSE(contains(built.data, "Bcc"));
+}
+
+TEST(MimeBuild, ACallerSuppliedBccHeaderIsRefusedRatherThanRendered) {
+    MailMessage msg = minimalMessage();
+    msg.headers = {{"Bcc", "sneaky@example.com"}};
+    EXPECT_THROW(buildMail(msg, kSeed), MailBuildError);
+}
+
+TEST(MimeBuild, TextPlusHtmlBecomesMultipartAlternative) {
+    MailMessage msg = minimalMessage();
+    msg.subject = "S";
+    msg.text = "plain";
+    msg.html = "<p>rich</p>";
+
+    const BuiltMail built = buildMail(msg, kSeed);
+    const std::string boundary = mailBoundary(kSeed, 0);
+    ASSERT_EQ(built.boundaries, (std::vector<std::string>{boundary}));
+
+    EXPECT_EQ(built.data,
+              "From: alice@example.com\r\n"
+              "To: bob@example.com\r\n"
+              "Subject: S\r\n"
+              "MIME-Version: 1.0\r\n"
+              "Content-Type: multipart/alternative; boundary=\"" + boundary + "\"\r\n"
+              "\r\n"
+              "--" + boundary + "\r\n"
+              "Content-Type: text/plain; charset=UTF-8\r\n"
+              "Content-Transfer-Encoding: quoted-printable\r\n"
+              "\r\n"
+              "plain\r\n"
+              "--" + boundary + "\r\n"
+              "Content-Type: text/html; charset=UTF-8\r\n"
+              "Content-Transfer-Encoding: quoted-printable\r\n"
+              "\r\n"
+              "<p>rich</p>\r\n"
+              "--" + boundary + "--\r\n");
+}
+
+TEST(MimeBuild, HtmlWithNoTextIsASingleHtmlPart) {
+    MailMessage msg = minimalMessage();
+    msg.text.clear();
+    msg.html = "<p>rich</p>";
+
+    const BuiltMail built = buildMail(msg, kSeed);
+    EXPECT_TRUE(built.boundaries.empty());
+    EXPECT_TRUE(contains(built.data, "Content-Type: text/html; charset=UTF-8\r\n"));
+    EXPECT_FALSE(contains(built.data, "multipart"));
+}
+
+TEST(MimeBuild, AnAttachmentWrapsTheBodyAsTheFirstPartOfMultipartMixed) {
+    MailMessage msg = minimalMessage();
+    msg.subject = "S";
+    msg.text = "body";
+    MailAttachment attachment;
+    attachment.filename = "note.txt";
+    attachment.contentType = "text/plain";
+    attachment.content = "bytes";
+    msg.attachments = {attachment};
+
+    const BuiltMail built = buildMail(msg, kSeed);
+    const std::string boundary = mailBoundary(kSeed, 0);
+    ASSERT_EQ(built.boundaries, (std::vector<std::string>{boundary}));
+
+    EXPECT_EQ(built.data,
+              "From: alice@example.com\r\n"
+              "To: bob@example.com\r\n"
+              "Subject: S\r\n"
+              "MIME-Version: 1.0\r\n"
+              "Content-Type: multipart/mixed; boundary=\"" + boundary + "\"\r\n"
+              "\r\n"
+              "--" + boundary + "\r\n"
+              "Content-Type: text/plain; charset=UTF-8\r\n"
+              "Content-Transfer-Encoding: quoted-printable\r\n"
+              "\r\n"
+              "body\r\n"
+              "--" + boundary + "\r\n"
+              "Content-Type: text/plain; name=\"note.txt\"\r\n"
+              "Content-Transfer-Encoding: base64\r\n"
+              "Content-Disposition: attachment; filename=\"note.txt\"\r\n"
+              "\r\n"
+              "Ynl0ZXM=\r\n"
+              "--" + boundary + "--\r\n");
+}
+
+TEST(MimeBuild, AnAttachmentAlongsideHtmlNestsAlternativeInsideMixed) {
+    MailMessage msg = minimalMessage();
+    msg.text = "t";
+    msg.html = "<b>h</b>";
+    MailAttachment attachment;
+    attachment.filename = "a.bin";
+    attachment.content = std::string("\x00\x01\xFF", 3);
+    msg.attachments = {attachment};
+
+    const BuiltMail built = buildMail(msg, kSeed);
+    ASSERT_EQ(built.boundaries.size(), 2u);
+    const std::string outer = built.boundaries[0];
+    const std::string inner = built.boundaries[1];
+    EXPECT_NE(outer, inner) << "the two levels must not share a boundary";
+
+    // The alternative sits wholly inside the first part of the mixed wrapper.
+    const std::size_t outerFirst = built.data.find("--" + outer + "\r\n");
+    const std::size_t innerClose = built.data.find("--" + inner + "--\r\n");
+    const std::size_t outerSecond = built.data.find("--" + outer + "\r\n", outerFirst + 1);
+    ASSERT_NE(outerFirst, std::string::npos);
+    ASSERT_NE(innerClose, std::string::npos);
+    ASSERT_NE(outerSecond, std::string::npos);
+    EXPECT_LT(outerFirst, innerClose);
+    EXPECT_LT(innerClose, outerSecond);
+
+    EXPECT_TRUE(contains(built.data,
+                         "Content-Type: multipart/mixed; boundary=\"" + outer + "\"\r\n"));
+    EXPECT_TRUE(contains(built.data,
+                         "Content-Type: multipart/alternative; boundary=\"" + inner + "\"\r\n"));
+    // An unknown type is stated as unknown rather than guessed.
+    EXPECT_TRUE(contains(built.data, "Content-Type: application/octet-stream; name=\"a.bin\"\r\n"));
+    EXPECT_TRUE(contains(built.data, "AAH/\r\n")) << "binary attachments go out as base64";
+}
+
+TEST(MimeBuild, AHungarianSubjectIsEncodedPerRfc2047AndDecodesBackUnchanged) {
+    MailMessage msg = minimalMessage();
+    msg.subject = "Árvíztűrő tükörfúrógép";
+
+    const BuiltMail built = buildMail(msg, kSeed);
+    const std::string rendered = headerValue(built.data, "Subject");
+
+    EXPECT_TRUE(contains(rendered, "=?UTF-8?B?")) << rendered;
+    EXPECT_EQ(MimeWords::decode(rendered), msg.subject);
+    // Nothing non-ASCII may survive into the header block itself.
+    for (const unsigned char c : built.data.substr(0, built.data.find("\r\n\r\n")))
+        EXPECT_LT(c, 0x80u) << "a raw non-ASCII byte reached a header";
+}
+
+TEST(MimeBuild, ALongNonAsciiSubjectFoldsWithoutBreakingAnEncodedWord) {
+    MailMessage msg = minimalMessage();
+    msg.subject.clear();
+    for (int i = 0; i < 12; ++i) msg.subject += "árvíztűrő ";
+
+    const BuiltMail built = buildMail(msg, kSeed);
+    const std::string rendered = headerValue(built.data, "Subject");
+    EXPECT_EQ(MimeWords::decode(rendered), msg.subject);
+
+    // Every line of the rendered header must be a whole number of encoded
+    // words: an `=?` with no `?=` after it on the same line means a word was
+    // split and the recipient sees the encoding as literal text.
+    const std::size_t start = built.data.find("Subject:");
+    const std::size_t end = built.data.find("\r\nMIME-Version:");
+    ASSERT_NE(start, std::string::npos);
+    ASSERT_NE(end, std::string::npos);
+    const std::string block = built.data.substr(start, end - start);
+    std::size_t at = 0;
+    int lines = 0;
+    while (at < block.size()) {
+        std::size_t nl = block.find("\r\n", at);
+        if (nl == std::string::npos) nl = block.size();
+        const std::string line = block.substr(at, nl - at);
+        ++lines;
+        EXPECT_LE(line.size(), 78u) << line;
+        const auto [opens, closes] = encodedWordCounts(line);
+        EXPECT_EQ(opens, closes) << "encoded word split across a fold: " << line;
+        at = nl + 2;
+    }
+    EXPECT_GT(lines, 1) << "this subject was supposed to be long enough to fold";
+}
+
+TEST(MimeBuild, ANonAsciiFilenameUsesRfc2231NotAnEncodedWord) {
+    MailMessage msg = minimalMessage();
+    MailAttachment attachment;
+    attachment.filename = "árvíz.txt";
+    attachment.contentType = "text/plain";
+    attachment.content = "x";
+    msg.attachments = {attachment};
+
+    const BuiltMail built = buildMail(msg, kSeed);
+    const std::string disposition = headerValue(built.data, "Content-Disposition");
+
+    // RFC 2047 words are not permitted in a parameter value, so a client that
+    // saw one would show it literally as the filename.
+    EXPECT_FALSE(contains(disposition, "=?UTF-8?")) << disposition;
+    EXPECT_TRUE(contains(disposition, "filename*=UTF-8''%C3%A1rv%C3%ADz.txt")) << disposition;
+    // An ASCII fallback is offered alongside for readers without RFC 2231.
+    EXPECT_TRUE(contains(disposition, "filename=\"__rv__z.txt\"")) << disposition;
+}
+
+TEST(MimeBuild, MostlyAsciiTextGoesOutAsQuotedPrintableAndStaysReadable) {
+    MailMessage msg = minimalMessage();
+    msg.text = "Kedves Ferenc, üdvözlöm!";
+
+    const BuiltMail built = buildMail(msg, kSeed);
+    EXPECT_TRUE(contains(built.data, "Content-Transfer-Encoding: quoted-printable\r\n"));
+    EXPECT_TRUE(contains(built.data, "Kedves Ferenc, =C3=BCdv=C3=B6zl=C3=B6m!\r\n"));
+}
+
+TEST(MimeBuild, TextThatIsMostlyNonAsciiGoesOutAsBase64Instead) {
+    MailMessage msg = minimalMessage();
+    // Quoted-printable triples every one of these bytes.
+    for (int i = 0; i < 40; ++i) msg.text += "árvíztűrő";
+
+    const BuiltMail built = buildMail(msg, kSeed);
+    EXPECT_TRUE(contains(built.data, "Content-Transfer-Encoding: base64\r\n"));
+    EXPECT_FALSE(contains(built.data, "=C3="));
+}
+
+TEST(MimeBuild, QuotedPrintableEncodesTrailingWhitespaceAndEqualsSigns) {
+    MailMessage msg = minimalMessage();
+    msg.text = "trail  \nx=y\ntab\t\n";
+
+    const BuiltMail built = buildMail(msg, kSeed);
+    const std::string body = built.data.substr(built.data.find("\r\n\r\n") + 4);
+
+    // Only the LAST space is encoded: an interior space is a literal, and a
+    // transport is only entitled to strip what is at the end of a line.
+    EXPECT_EQ(body,
+              "trail =20\r\n"
+              "x=3Dy\r\n"
+              "tab=09\r\n");
+}
+
+TEST(MimeBuild, QuotedPrintableSoftBreaksALongLineAtSeventySixCharacters) {
+    MailMessage msg = minimalMessage();
+    msg.text = std::string(76, 'A');
+
+    const BuiltMail built = buildMail(msg, kSeed);
+    const std::string body = built.data.substr(built.data.find("\r\n\r\n") + 4);
+
+    // 75 characters of content plus the `=` soft break is exactly 76; the
+    // seventy-sixth character therefore starts the next line.
+    EXPECT_EQ(body, std::string(75, 'A') + "=\r\nA\r\n");
+}
+
+TEST(MimeBuild, QuotedPrintableLeavesALineOfExactlySeventyFiveCharactersAlone) {
+    MailMessage msg = minimalMessage();
+    msg.text = std::string(75, 'A');
+
+    const BuiltMail built = buildMail(msg, kSeed);
+    const std::string body = built.data.substr(built.data.find("\r\n\r\n") + 4);
+    EXPECT_EQ(body, std::string(75, 'A') + "\r\n");
+}
+
+TEST(MimeBuild, NoQuotedPrintableLineEndsInWhitespaceEvenAcrossASoftBreak) {
+    MailMessage msg = minimalMessage();
+    // Lands a space right where a soft break would otherwise fall.
+    msg.text = std::string(74, 'A') + " " + std::string(74, 'B');
+
+    const BuiltMail built = buildMail(msg, kSeed);
+    const std::string body = built.data.substr(built.data.find("\r\n\r\n") + 4);
+
+    std::size_t at = 0;
+    while (at < body.size()) {
+        const std::size_t nl = body.find("\r\n", at);
+        ASSERT_NE(nl, std::string::npos);
+        const std::string line = body.substr(at, nl - at);
+        EXPECT_LE(line.size(), 76u) << line;
+        if (!line.empty())
+            EXPECT_FALSE(line.back() == ' ' || line.back() == '\t')
+                << "a strippable trailing space: [" << line << "]";
+        at = nl + 2;
+    }
+}
+
+TEST(MimeBuild, ABodyLineOfASinglePeriodCannotTerminateTheDataPhase) {
+    MailMessage msg = minimalMessage();
+    msg.text = "before\n.\n..\nafter";
+
+    const BuiltMail built = buildMail(msg, kSeed);
+    const std::string body = built.data.substr(built.data.find("\r\n\r\n") + 4);
+
+    // Not dot-stuffed (libcurl does that); instead no line BEGINS with a
+    // period, which is safe whether or not the transport stuffs.
+    EXPECT_EQ(body,
+              "before\r\n"
+              "=2E\r\n"
+              "=2E.\r\n"
+              "after\r\n");
+    EXPECT_FALSE(contains(built.data, "\r\n.\r\n"));
+    EXPECT_FALSE(contains(built.data, "\r\n..\r\n"))
+        << "that would be a stuffed line, and the transport stuffs again";
+}
+
+TEST(MimeBuild, ABoundaryOccurringInTheContentIsRegenerated) {
+    // A filename is the one place a caller's bytes reach a part verbatim: an
+    // ASCII parameter value is emitted as it came, so this really does put the
+    // first candidate boundary inside the content.
+    const std::string collides = mailBoundary(kSeed, 0);
+
+    MailMessage msg = minimalMessage();
+    MailAttachment attachment;
+    attachment.filename = collides + ".txt";
+    attachment.content = "x";
+    msg.attachments = {attachment};
+
+    const BuiltMail built = buildMail(msg, kSeed);
+    ASSERT_EQ(built.boundaries.size(), 1u);
+    EXPECT_NE(built.boundaries[0], collides)
+        << "a boundary inside a part truncates the message at that point";
+    EXPECT_EQ(built.boundaries[0], mailBoundary(kSeed, 1));
+    EXPECT_TRUE(contains(built.data, "filename=\"" + collides + ".txt\""))
+        << "the content itself must be untouched; it is the boundary that moves";
+}
+
+TEST(MimeBuild, ABoundaryCannotCollideWithQuotedPrintableBodyText) {
+    // The paired negative: the body encodings cannot reproduce "=_", because
+    // quoted-printable emits "=" only as "=XX" or at a line end and base64 has
+    // neither character. So a boundary pasted into the text is NOT a collision,
+    // and the first candidate stands.
+    const std::string candidate = mailBoundary(kSeed, 0);
+
+    MailMessage msg = minimalMessage();
+    msg.text = "see " + candidate + " here";
+    msg.html = "<p>x</p>";
+
+    const BuiltMail built = buildMail(msg, kSeed);
+    ASSERT_EQ(built.boundaries.size(), 1u);
+    EXPECT_EQ(built.boundaries[0], candidate);
+    EXPECT_FALSE(contains(built.data, "see " + candidate + " here"))
+        << "the equals sign must have been escaped";
+    EXPECT_TRUE(contains(built.data, "see =3D_svapi_"));
+}
+
+TEST(MimeBuild, NestedBoundariesNeverCollideWithEachOther) {
+    MailMessage msg = minimalMessage();
+    msg.text = "t";
+    msg.html = "<b>h</b>";
+    MailAttachment attachment;
+    attachment.filename = "a.txt";
+    attachment.content = "x";
+    msg.attachments = {attachment};
+
+    const BuiltMail built = buildMail(msg, kSeed);
+    ASSERT_EQ(built.boundaries.size(), 2u);
+    EXPECT_EQ(built.boundaries[1], mailBoundary(kSeed, 0));
+    EXPECT_EQ(built.boundaries[0], mailBoundary(kSeed, 1))
+        << "the outer boundary must step past the inner one it would have duplicated";
+}
+
+TEST(MimeBuild, TheSameMessageAndSeedAlwaysRenderTheSameBytes) {
+    MailMessage msg = minimalMessage();
+    msg.html = "<p>x</p>";
+    EXPECT_EQ(buildMail(msg, kSeed).data, buildMail(msg, kSeed).data);
+    EXPECT_NE(buildMail(msg, kSeed).data, buildMail(msg, kSeed + 1).data);
+}
+
+TEST(MimeBuild, EveryLineEndingIsCrlf) {
+    MailMessage msg = minimalMessage();
+    msg.subject = "Árvíztűrő";
+    msg.text = "a\nb\n";
+    msg.html = "<p>c</p>";
+    MailAttachment attachment;
+    attachment.filename = "á.txt";
+    attachment.content = "x";
+    msg.attachments = {attachment};
+
+    const std::string data = buildMail(msg, kSeed).data;
+    for (std::size_t i = 0; i < data.size(); ++i) {
+        if (data[i] == '\n') EXPECT_TRUE(i > 0 && data[i - 1] == '\r') << "bare LF at " << i;
+        if (data[i] == '\r') EXPECT_TRUE(i + 1 < data.size() && data[i + 1] == '\n')
+            << "bare CR at " << i;
+    }
+}
+
+// ---------------------------------------------------------------------------
+// Refusals. Every one of these would otherwise be a header the caller wrote.
+// ---------------------------------------------------------------------------
+
+TEST(MimeBuild, RefusesALineBreakInTheFromAddress) {
+    for (const std::string& breakChar : {"\r", "\n", "\r\n"}) {
+        MailMessage msg = minimalMessage();
+        msg.from = "alice@example.com" + breakChar + "Bcc: attacker@evil.example";
+        try {
+            buildMail(msg, kSeed);
+            FAIL() << "accepted a CR/LF in from";
+        } catch (const MailBuildError& error) {
+            EXPECT_EQ(error.field(), "from");
+        }
+    }
+}
+
+TEST(MimeBuild, RefusesALineBreakInARecipient) {
+    for (const std::string& field : {"to", "cc", "bcc"}) {
+        MailMessage msg = minimalMessage();
+        const std::string poison = "bob@example.com\r\nBcc: attacker@evil.example";
+        if (field == "to") msg.to = {poison};
+        if (field == "cc") msg.cc = {poison};
+        if (field == "bcc") msg.bcc = {poison};
+        try {
+            buildMail(msg, kSeed);
+            FAIL() << "accepted a CR/LF in " << field;
+        } catch (const MailBuildError& error) {
+            EXPECT_EQ(error.field(), field);
+        }
+    }
+}
+
+TEST(MimeBuild, RefusesALineBreakInTheReplyToAddress) {
+    MailMessage msg = minimalMessage();
+    msg.replyTo = "a@example.com\nX-Evil: 1";
+    EXPECT_THROW(buildMail(msg, kSeed), MailBuildError);
+}
+
+TEST(MimeBuild, RefusesALineBreakInTheSubject) {
+    MailMessage msg = minimalMessage();
+    msg.subject = "Hello\r\nX-Spoofed: yes";
+    try {
+        buildMail(msg, kSeed);
+        FAIL() << "accepted a CR/LF in the subject";
+    } catch (const MailBuildError& error) {
+        EXPECT_EQ(error.field(), "subject");
+    }
+}
+
+TEST(MimeBuild, RefusesALineBreakInAnAttachmentFilename) {
+    MailMessage msg = minimalMessage();
+    MailAttachment attachment;
+    attachment.filename = "ok.txt\r\nX-Evil: 1";
+    attachment.content = "x";
+    msg.attachments = {attachment};
+    try {
+        buildMail(msg, kSeed);
+        FAIL() << "accepted a CR/LF in a filename";
+    } catch (const MailBuildError& error) {
+        EXPECT_EQ(error.field(), "attachment filename");
+    }
+}
+
+TEST(MimeBuild, RefusesALineBreakInAnExtraHeaderName) {
+    MailMessage msg = minimalMessage();
+    msg.headers = {{"X-Thing\r\nX-Evil", "1"}};
+    try {
+        buildMail(msg, kSeed);
+        FAIL() << "accepted a CR/LF in a header name";
+    } catch (const MailBuildError& error) {
+        EXPECT_EQ(error.field(), "header name");
+    }
+}
+
+TEST(MimeBuild, RefusesALineBreakInAnExtraHeaderValue) {
+    MailMessage msg = minimalMessage();
+    msg.headers = {{"X-Thing", "1\r\nBcc: attacker@evil.example"}};
+    try {
+        buildMail(msg, kSeed);
+        FAIL() << "accepted a CR/LF in a header value";
+    } catch (const MailBuildError& error) {
+        EXPECT_EQ(error.field(), "header value");
+    }
+}
+
+TEST(MimeBuild, RefusesAColonInsideAnExtraHeaderName) {
+    // The rest of the name would parse as the value, and the real value as a
+    // second header.
+    MailMessage msg = minimalMessage();
+    msg.headers = {{"X-Thing: 1 X-Evil", "2"}};
+    EXPECT_THROW(buildMail(msg, kSeed), MailBuildError);
+}
+
+TEST(MimeBuild, RefusesAnExtraHeaderTheBuilderOwns) {
+    for (const std::string& name : {"Content-Type", "content-transfer-encoding", "MIME-Version",
+                                    "From", "To", "Subject", "Date", "Message-ID"}) {
+        MailMessage msg = minimalMessage();
+        msg.headers = {{name, "whatever"}};
+        EXPECT_THROW(buildMail(msg, kSeed), MailBuildError) << name;
+    }
+}
+
+TEST(MimeBuild, RefusesParametersSmuggledThroughAnAttachmentContentType) {
+    MailMessage msg = minimalMessage();
+    MailAttachment attachment;
+    attachment.filename = "a.txt";
+    attachment.contentType = "text/plain; boundary=\"x\"";
+    attachment.content = "x";
+    msg.attachments = {attachment};
+    EXPECT_THROW(buildMail(msg, kSeed), MailBuildError);
+}
+
+TEST(MimeBuild, RefusesAnEmptyFrom) {
+    MailMessage msg = minimalMessage();
+    msg.from.clear();
+    try {
+        buildMail(msg, kSeed);
+        FAIL() << "accepted an empty from";
+    } catch (const MailBuildError& error) {
+        EXPECT_EQ(error.field(), "from");
+    }
+}
+
+TEST(MimeBuild, RefusesAMessageWithNoRecipientAtAll) {
+    MailMessage msg = minimalMessage();
+    msg.to.clear();
+    try {
+        buildMail(msg, kSeed);
+        FAIL() << "accepted a message with nowhere to go";
+    } catch (const MailBuildError& error) {
+        EXPECT_EQ(error.field(), "to");
+    }
+}
+
+TEST(MimeBuild, ABccAloneIsEnoughToSendTo) {
+    MailMessage msg = minimalMessage();
+    msg.to.clear();
+    msg.bcc = {"secret@example.com"};
+
+    const BuiltMail built = buildMail(msg, kSeed);
+    EXPECT_EQ(built.envelopeRecipients, (std::vector<std::string>{"secret@example.com"}));
+    EXPECT_FALSE(contains(built.data, "secret@example.com"));
+    EXPECT_FALSE(contains(built.data, "\r\nTo:")) << "an empty To header is worse than none";
+}
+
+TEST(MimeBuild, RefusesAnAddressThatIsNotOneAfterExtraction) {
+    MailMessage msg = minimalMessage();
+    msg.to = {"bob@example.com alice@example.com"};
+    EXPECT_THROW(buildMail(msg, kSeed), MailBuildError);
+}
+
+TEST(MimeBuild, RefusesAnAttachmentWithNoFilename) {
+    MailMessage msg = minimalMessage();
+    MailAttachment attachment;
+    attachment.content = "x";
+    msg.attachments = {attachment};
+    EXPECT_THROW(buildMail(msg, kSeed), MailBuildError);
+}