Bläddra i källkod

docs(mail): keep the prod mailtest probe, and what it found

The deployed function and a README, so the next person can see what was
exercised against a real provider instead of rediscovering it. Every
other mail test here runs against a fake on the dev host, and a fake
cannot show what a provider actually does.

Documents the folding trap in api/llms.txt, which is the finding most
likely to bite a consumer: `header` is raw RFC 5322, so a long accented
subject arrives as `Subject:<CRLF> =?UTF-8?B?...?=<CRLF> =?UTF-8?B?...?=`
with nothing on the Subject line. The obvious regex finds an empty
subject and the next-obvious one silently captures only the first
encoded word. My own probe contained both mistakes at once, in opposite
directions, which is fair evidence a consumer will hit it.

Also corrects this file's claim that DigitalOcean blocks 2525. It blocks
25, 465 and 587. 2525 had nothing listening when I measured it and I
folded it into the block without testing a second host, which is the
check that would have told the two apart - the same over-reading I have
now made twice in one day.

Sending from prod works over 2525 with STARTTLS, verified end to end:
accepted in ~1.3 s, then found by UID SEARCH and fetched back `\Recent`
and NOT `\Seen` - BODY.PEEK proven in production against a genuinely new
message, which is the strongest form of that test.
fszontagh 1 månad sedan
förälder
incheckning
905723cefa
4 ändrade filer med 269 tillägg och 1 borttagningar
  1. 2 1
      CLAUDE.md
  2. 1 0
      api/llms.txt
  3. 63 0
      docs/prod-mailtest/README.md
  4. 203 0
      docs/prod-mailtest/mailprobe.js

+ 2 - 1
CLAUDE.md

@@ -102,7 +102,8 @@ docker run -d --name svapi-dev -p 8080:8080 -e SMARTBOTIC_VECTORAPI_KEY=dev svap
 - **`mailGlobalInit()` is called once from the runner's `main` before any worker starts, and FAILS CLOSED.** `curl_global_init` is not thread-safe and a lazy first-use from two pool threads is a real race. It also checks `CURL_VERSION_THREADSAFE` and refuses to start without it, in the same spirit as the runner refusing to start with no token on a non-loopback bind. **`CURLOPT_NOSIGNAL` on every handle**, or curl uses `SIGALRM` for resolution timeouts, which is unsafe off the main thread and can longjmp out of a worker - and a single-threaded test never shows it.
 - **One handle per (run, account), destroyed with the session. No `CURLSH`, no cross-tenant reuse.** A handle carries connection state and credentials. A fresh handle per command would mean a TCP connect, a TLS handshake and a LOGIN for every command, which is both slow and what gets an account throttled; a test asserts one LOGIN serves three commands.
 - **VERIFIED THROUGH THE DEPLOYED RUNNER ON PROD, 2026-10-09**, which is the only test that exercises the real binary, real project secrets and real egress together. `mailboxes` decoded 6 folders in 263 ms; `read` with a `smallerThanBytes` criterion returned 3 of 9 matches in 312 ms; `criteria: {unseen:true}` worked; and the **non-ASCII SEARCH refusal fired in production** as `mail_bad_argument` 422 naming the field, which is the single most important safety behaviour here because the alternative shipped elsewhere as silently empty results. Credentials came from project secrets via `passwordSecret`, never from source. A function whose policy grants **nothing** (`rules: []`) can still use `ctx.mail`, which confirms the deliberate decision that an outbound surface is gated by `network_egress` and the SSRF guard rather than by scope rules.
-- **`ctx.mail.send` CANNOT WORK on the DigitalOcean prod droplet**: outbound 25, 465, 587 and 2525 are all blocked by the provider, confirmed as the host's policy rather than the mail server's by `smtp.gmail.com:587` and `smtp.sendgrid.net:587` being blocked too. IMAP 993 and 143 are open. A send therefore fails as `mail_timeout` 504 after ~7 s with **`retryable: false`** - which is the right answer and worth noting: a send is never retryable even when the timeout proves nothing could have been delivered, because the guarantee has to hold without knowing. The ~7 s is also live confirmation that connect is capped at HALF the run budget (15 s descriptor timeout). Sending from prod needs the provider's block lifted or a relay on an open port.
+- **A returned `header` is RAW and FOLDED, and the naive regex truncates it SILENTLY.** Measured through the deployed runner: a long accented subject arrived as `Subject:<CRLF> =?UTF-8?B?...?=<CRLF> =?UTF-8?B?...?=` - nothing on the `Subject:` line at all, the value split across two continuation lines as two encoded words. `/Subject:.*=\?UTF-8\?/` is then false (`.` cannot cross the CRLF) while `/^Subject:\s*(.*)$/m` matches but captures only the FIRST encoded word, so one check fails loudly and the other lies. Both of my probe's checks were wrong, in opposite directions. Consumers must unfold before parsing and decode every encoded word, which `api/llms.txt` now says. Candidate improvement: expose a decoded `subject` on each message so no consumer has to get this right - deliberately NOT built, since it is a new surface.
+- **`ctx.mail.send` CANNOT WORK on the DigitalOcean prod droplet**: outbound 25, 465 and 587 are blocked by the provider (**2525 is NOT** - an earlier version of this note said it was, which was wrong: 2525 merely had nothing listening at the time, and I folded it into the block without the second host that would have told the two apart), confirmed as the host's policy rather than the mail server's by `smtp.gmail.com:587` and `smtp.sendgrid.net:587` being blocked too. IMAP 993 and 143 are open. A send therefore fails as `mail_timeout` 504 after ~7 s with **`retryable: false`** - which is the right answer and worth noting: a send is never retryable even when the timeout proves nothing could have been delivered, because the guarantee has to hold without knowing. The ~7 s is also live confirmation that connect is capped at HALF the run budget (15 s descriptor timeout). **Sending from prod WORKS over port 2525 with STARTTLS**, verified end to end through the deployed runner: send accepted in ~1.3 s, then found by `UID SEARCH` and fetched back, with the message arriving `\\Recent` and NOT `\\Seen` - which is `BODY.PEEK` proven in production against a genuinely new message, the strongest form of that test. A send over 587 still fails as `mail_timeout` 504 with `retryable: false`.
 - **A returned object containing `status`, `headers` or `body` is read as a response ENVELOPE, and an envelope may contain nothing else.** A diagnostic object with a field called `status` therefore fails the run with `invalid_return` - and if that object was built in a `catch`, it HIDES the error it was meant to report. Cost me a debugging round on prod.
 - **VERIFIED AGAINST A LIVE SERVER on 2026-10-08** (Dovecot-ish on `mail.onmail.hu`, IMAP 993 implicit TLS and SMTP 587 STARTTLS, credentials in `/data/dev/.env`). Everything below was measured against that server, not a fixture, and every fake-server claim in this section survived it: `LIST` and modified-UTF-7 decoding, `EXAMINE` reporting `PERMANENTFLAGS ()` read-only, `UID SEARCH` including `UNSEEN`, **a peek fetch of a genuinely UNSEEN message leaving it unseen** (the weak version of this test uses an already-seen message and proves nothing), the direct parse of a good fetch returning `NeedMore` while the framed re-parse returns `Ok`, no tagged line in the buffer, and **a multi-uid `UID FETCH` delivering zero bytes**. A full send-and-read-back round trip confirmed an accented Hungarian subject surviving as two `=?UTF-8?B?` encoded words and decoding back exactly, quoted-printable chosen for the accented text, a lone `.` body line arriving intact and not double-stuffed, an RFC 2231 attachment filename, and `BODYSTRUCTURE` part numbering of `1.1` for the text inside a `multipart/alternative` inside a `multipart/mixed` with the attachment at `2`. Note `EXAMINE` alone prevents a flag change, so that test confirms the read path is safe but does NOT isolate `BODY.PEEK`'s own contribution.
 - **The fake IMAP/SMTP servers are committed** (`runner/tests/fake_mail_server.hpp`): in-process TCP listeners on **ephemeral** ports. Ephemeral because a fixed port collides - twice during development a test reached a stale server from an earlier run and "passed" against the wrong process. They **mask credentials** before recording a transcript, and the SMTP one answers a bare `AUTH PLAIN` with a **334 challenge, not 235**: answering 235 made an earlier harness report a working login for a client that had sent no credentials. It also **un-stuffs** the leading period during DATA, as a real receiver does, or a correct client looks like it double-stuffed.

+ 1 - 0
api/llms.txt

@@ -241,6 +241,7 @@ export default async function (ctx) {
 - **A job, cron or db run's `ctx` is NOT the HTTP shape.** It carries `trigger`, `depth`, `enqueued_by` and `enqueued_at_ms`, with your payload under **`ctx.body`** - there is no `ctx.method`, `ctx.path`, `ctx.query` or `ctx.params`. A cron payload is `{schedule, scheduled_at}`; a database-event payload is `{collection, table, id, event, document}`.
 - `ctx.mail` - **IMAP read and SMTP send.** Three calls, deliberately few, each opening one session and closing it. Connection fields are shared: `host`, `port` (optional, 0 or absent means the scheme default), `user`/`userSecret`, `password`/`passwordSecret`, `tls` (default **true**), `startTls`, `timeoutMs`. **Prefer `passwordSecret`/`userSecret`**: they name a project secret resolved host-side, so an error or a log that echoes your options object cannot leak it and an operator can rotate it without a code push. A literal `password` is accepted, because `ctx.env` already hands your script the value anyway. Naming a secret that does not exist is **422** `mail_secret_missing`, which names the secret and never a value; passing both a literal and a secret name for the same credential is `ambiguous_body`. An unknown option key is **refused, not ignored**.
   - `ctx.mail.read({mailbox, criteria, limit, ...})` -> `{messages: [...], matched: n}`. `mailbox` defaults to `INBOX`; `limit` defaults to 20 and is **capped at 200** (over it is refused, not clamped). `matched` is the size of the whole search result and `messages` the newest `limit` of it, so you can tell a full page from the end of the mailbox. Each message carries `uid`, `seq`, `flags`, `internal_date`, `size`, `header`, `text`, `body_sections` and a `headerEncoding`/`textEncoding` of `text` or `base64` - **mail is routinely not UTF-8**, so the encoding is stated rather than assumed. Reading uses `EXAMINE` and `BODY.PEEK`, so **it never marks mail as seen**.
+  - **`header` is RAW RFC 5322, which means it is FOLDED - do not parse it with an obvious regex.** Measured against a real provider: a long accented subject came back as `Subject:<CRLF> =?UTF-8?B?...?=<CRLF> =?UTF-8?B?...?=`, with **nothing on the `Subject:` line itself** and the value split across two continuation lines as two separate encoded words. So `/Subject:.*/` finds an EMPTY subject, and `/^Subject:\s*(.*)$/m` finds only the FIRST encoded word - a silently truncated subject, which is worse. Unfold first (join a line beginning with a space or tab onto the previous one), then RFC 2047-decode **every** encoded word in the result and concatenate. The same applies to any long header, `To` and `From` included.
   - **`criteria` is a structured object, never raw IMAP syntax** - the only string accepted is `'ALL'` (the default). Fields: `since`, `before`, `from`, `to`, `subject`, `text`, `body`, `headerName`+`headerValue`, `unseen`, `seen`, `flagged`, `largerThanBytes`, `smallerThanBytes`. `headerName` and `headerValue` are one criterion in two halves and must both be given, because a server answers a half-stated one with a syntax error rather than with a match. **A non-ASCII criterion value is REFUSED** (naming the field): expressing it needs a multi-step `CHARSET UTF-8` literal exchange this transport does not drive, and sending the bytes anyway makes the server match nothing - and zero results is indistinguishable from "there is no such mail", which is a silently wrong answer rather than a missing feature. Filter on an ASCII-safe criterion, or on sender or date, and match accented text yourself after fetching. Mailbox NAMES are unaffected and may be non-ASCII.
   - `ctx.mail.mailboxes({...})` -> `[{name, nameEncoding, flags, delimiter}]`. Names are decoded from IMAP's modified UTF-7, so `Beérkezett` arrives readable.
   - `ctx.mail.send({from, to, cc, bcc, subject, text, html, attachments, replyTo, headers, inReplyTo, references, ...})` -> `{ok: true, accepted: [...]}`. `to`/`cc`/`bcc` take a string or an array. Structure is chosen for you: text only is `text/plain`, text plus `html` is `multipart/alternative`, and attachments wrap it in `multipart/mixed`. Attachments are `{filename, contentType, base64}`. **`bcc` recipients receive the message but appear in no header of it.** A non-ASCII subject, display name or filename is encoded correctly (RFC 2047, and RFC 2231 for filenames). An address, subject, filename or header containing CR or LF is **refused by name** - that is header injection.

+ 63 - 0
docs/prod-mailtest/README.md

@@ -0,0 +1,63 @@
+# The prod `mailtest` project
+
+A live `ctx.mail` exercise running on the production server, against a real mail
+provider. It exists because every other test in this repo runs against a fake
+server on the dev host, and a fake cannot show what a provider actually does.
+
+`mailprobe.js` is the function as deployed. Keep it in the repo so the next
+person can see what was tested rather than rediscovering it.
+
+## Layout
+
+- project `mailtest` on prod
+- secrets `MAIL_IMAP_PASSWORD` and `MAIL_SMTP_PASSWORD`, set over
+  `PUT /api/v1/projects/mailtest/secrets/{name}`
+- one http function `mailprobe`, route `/mail/:op`, reached at
+  `/fn/mailtest/mail/<op>`
+
+**No credential is in the source.** `userSecret`/`passwordSecret` name the
+project secrets and the host resolves them, so neither this file nor an echoed
+options object can leak one.
+
+`timeoutMs: 15000` is needed: the default wall budget is 2 s and a TLS IMAP
+session plus a LOGIN does not fit in it.
+
+## The ops
+
+| op | what it proves |
+|---|---|
+| `mailboxes` | LIST works and modified UTF-7 is decoded |
+| `read` | a plain read of this mailbox EXCEEDS the 4 MiB per-run cap |
+| `small` | `smallerThanBytes` is the documented remedy for that, and it works |
+| `unseen` | a structured `criteria` object |
+| `accents` | a non-ASCII criterion is REFUSED, not sent |
+| `send` | SMTP over STARTTLS on 2525 |
+| `roundtrip` | send to the readable mailbox, then fetch it back and assert bytes |
+
+## What this found that the fakes did not
+
+- **`mail_too_large` carried two different statuses** (413 transport, 422
+  per-run cap) while the docs promised 413. Fixed: 422 everywhere.
+- **A returned object containing `status`, `headers` or `body` is read as a
+  response ENVELOPE** and may hold nothing else, so a diagnostic field named
+  `status` fails the run with `invalid_return` - and inside a `catch` it hides
+  the error it was reporting.
+- **`header` is raw and FOLDED.** A long accented subject arrives as
+  `Subject:<CRLF> =?UTF-8?B?...?=<CRLF> =?UTF-8?B?...?=`, with nothing on the
+  `Subject:` line. The obvious regex finds an empty subject; the next-obvious
+  one silently captures only the FIRST encoded word. See task #59.
+- **Port 2525 was never blocked by the host.** An earlier note said
+  DigitalOcean blocked 25, 465, 587 and 2525; it blocks the first three. 2525
+  simply had nothing listening when it was measured, and was folded into the
+  block without the second host that would have distinguished them.
+
+## Confirmed in production
+
+A send is accepted in ~1.3 s; the message is then found by `UID SEARCH` and
+fetched back carrying `\Recent` and **not** `\Seen`, which is `BODY.PEEK`
+proven against a genuinely new message. The lone `.` line survives and is not
+doubled, quoted-printable is applied (the body shows `stamp=3D`), the accented
+attachment filename uses RFC 2231, `multipart/mixed` is declared in the header
+with `multipart/alternative` inside, and a send over 587 fails as
+`mail_timeout` 504 with `retryable: false` after ~7 s - which is also live
+confirmation that connect is capped at HALF the run budget.

+ 203 - 0
docs/prod-mailtest/mailprobe.js

@@ -0,0 +1,203 @@
+// Exercises ctx.mail through the DEPLOYED runner against a real mail provider.
+//
+// Credentials are NEVER in this source: userSecret/passwordSecret name project
+// secrets that the host resolves, so nothing here or in an echoed options
+// object can leak them.
+//
+// timeoutMs is raised to the HTTP ceiling because the default wall budget is
+// 2 s and a TLS IMAP session plus a LOGIN does not fit in that.
+export const on = {
+  id: 'mailprobe',
+  type: 'http',
+  route: '/mail/:op',
+  method: ['GET', 'POST'],
+  timeoutMs: 15000,
+};
+
+const IMAP = {
+  host: 'mail.onmail.hu',
+  port: 993,
+  tls: true,
+  user: 'nbot@fsociety.hu',
+  passwordSecret: 'MAIL_IMAP_PASSWORD',
+};
+
+// 2525 with STARTTLS. NOT 587: DigitalOcean blocks outbound 25, 465 and 587
+// from this droplet (confirmed as the host's policy, since gmail and sendgrid
+// are blocked on 587 too), while 2525 is open. tls and startTls are mutually
+// exclusive, so tls must be false here; plaintext is still refused off
+// loopback, which startTls satisfies.
+const SMTP = {
+  host: 'mail.onmail.hu',
+  port: 2525,
+  tls: false,
+  startTls: true,
+  user: 'nbot@fsociety.hu',
+  passwordSecret: 'MAIL_SMTP_PASSWORD',
+};
+
+export default async function (ctx) {
+  const op = (ctx.params && ctx.params.op) || 'mailboxes';
+  const started = Date.now();
+  try {
+    if (op === 'mailboxes') {
+      const boxes = await ctx.mail.mailboxes(IMAP);
+      return {
+        op, ok: true, ms: Date.now() - started,
+        count: boxes.length,
+        // nameEncoding proves the modified-UTF-7 decode ran.
+        boxes: boxes.map(b => ({ name: b.name, nameEncoding: b.nameEncoding, delimiter: b.delimiter })),
+      };
+    }
+
+    if (op === 'read') {
+      const r = await ctx.mail.read({ ...IMAP, mailbox: 'INBOX', criteria: 'ALL', limit: 3 });
+      return {
+        op, ok: true, ms: Date.now() - started,
+        matched: r.matched,
+        returned: r.messages.length,
+        messages: r.messages.map(m => ({
+          uid: m.uid, flags: m.flags, size: m.size,
+          internal_date: m.internal_date,
+          headerEncoding: m.headerEncoding, textEncoding: m.textEncoding,
+          body_sections: m.body_sections,
+          // A SLICE only: the point is that bytes arrived, not to echo mail.
+          header_head: (m.header || '').slice(0, 120),
+          text_head: (m.text || '').slice(0, 80),
+        })),
+      };
+    }
+
+    if (op === 'small') {
+      // The documented remedy for mail_too_large: ask for less. A plain
+      // read of this mailbox exceeds the 4 MiB per-run cap, so bound it by
+      // message size rather than by count - limit alone cannot help, since
+      // one big message is enough to blow the cap.
+      const r = await ctx.mail.read({
+        ...IMAP, criteria: { smallerThanBytes: 60000 }, limit: 3,
+      });
+      return {
+        op, ok: true, ms: Date.now() - started,
+        matched: r.matched, returned: r.messages.length,
+        messages: r.messages.map(m => ({
+          uid: m.uid, flags: m.flags, size: m.size,
+          headerEncoding: m.headerEncoding, textEncoding: m.textEncoding,
+          body_sections: m.body_sections,
+          subject: ((m.header || '').match(/^Subject:\s*(.*)$/mi) || [])[1] || null,
+          text_head: (m.text || '').slice(0, 60),
+        })),
+      };
+    }
+
+    if (op === 'unseen') {
+      // A structured criterion, which is the only form accepted.
+      const r = await ctx.mail.read({ ...IMAP, criteria: { unseen: true }, limit: 5 });
+      return { op, ok: true, ms: Date.now() - started, matched: r.matched, uids: r.messages.map(m => m.uid) };
+    }
+
+    if (op === 'accents') {
+      // MUST be refused by field name rather than sent. A pass here is a
+      // silently wrong answer, not a feature.
+      const r = await ctx.mail.read({ ...IMAP, criteria: { subject: 'árvíztűrő' }, limit: 1 });
+      return { op, ok: true, unexpected: true, matched: r.matched };
+    }
+
+    if (op === 'send') {
+      const stamp = String(Date.now());
+      const r = await ctx.mail.send({
+        ...SMTP,
+        from: 'Kővágó Örs <nbot@fsociety.hu>',
+        to: 'test001@fsociety.hu',
+        subject: 'ctx.mail prod proba ' + stamp + ' - árvíztűrő tükörfúrógép',
+        text: 'Ez a level a telepitett runnerbol ment. stamp=' + stamp +
+              '\n.\nEgy maganyos pont a fenti sorban.\n',
+        html: '<p>Ez a levél a <b>telepített runnerből</b> ment.</p>',
+        attachments: [{ filename: 'árvíztűrő.txt', contentType: 'text/plain', base64: 'w6FydsOtenT9csWR' }],
+      });
+      return { op, ok: true, ms: Date.now() - started, accepted: r.accepted };
+    }
+
+    if (op === 'roundtrip') {
+      // The strongest end-to-end check available: send to the mailbox we can
+      // READ, then fetch it back and assert on the bytes. Sent to nbot@ rather
+      // than test001@ precisely because test001@ routes to a human's box we
+      // cannot open.
+      const stamp = String(Date.now());
+      const subject = 'svapi roundtrip ' + stamp + ' - árvíztűrő tükörfúrógép';
+      const sent = await ctx.mail.send({
+        ...SMTP,
+        from: 'Kővágó Örs <nbot@fsociety.hu>',
+        to: 'nbot@fsociety.hu',
+        subject,
+        // A lone '.' on its own line: dot-stuffing is curl's job, and if we
+        // also stuffed it the body would be corrupt; if neither did, the
+        // message would be TRUNCATED here.
+        text: 'stamp=' + stamp + '\n.\nA fenti sorban egy magányos pont áll.\n',
+        html: '<p>stamp=' + stamp + ' <b>árvíztűrő</b></p>',
+        attachments: [{ filename: 'árvíztűrő.txt', contentType: 'text/plain', base64: 'w6FydsOtenT9csWR' }],
+      });
+
+      // Give the server a moment to file it, then find it by an ASCII-safe
+      // criterion - the accented subject CANNOT be searched for, by design.
+      let found = null;
+      for (let attempt = 0; attempt < 6 && !found; attempt++) {
+        const r = await ctx.mail.read({
+          ...IMAP, criteria: { subject: 'svapi roundtrip ' + stamp }, limit: 1,
+        });
+        if (r.messages.length > 0) found = r.messages[0];
+      }
+      if (!found) {
+        return { op, ok: false, sent: sent.accepted, stamp, error: 'sent but not found on read-back' };
+      }
+      const header = found.header || '';
+      const text = found.text || '';
+      return {
+        op, ok: true, ms: Date.now() - started, stamp,
+        sent: sent.accepted,
+        uid: found.uid,
+        flags: found.flags,
+        checks: {
+          // The subject must arrive as RFC 2047 encoded words, not raw bytes.
+          subject_is_encoded_word: /Subject:.*=\?UTF-8\?/i.test(header),
+          subject_raw: (header.match(/^Subject:\s*(.*)$/mi) || [])[1] || null,
+          // The lone dot survived and was not doubled.
+          lone_dot_intact: /\n\.\r?\n|\r\n\.\r\n/.test(text),
+          double_stuffed: text.indexOf('\n..') !== -1,
+          // RFC 2231 for the accented filename.
+          rfc2231_filename: /filename\*=|filename\*0\*=/i.test(text),
+          quoted_printable: /Content-Transfer-Encoding:\s*quoted-printable/i.test(text),
+          multipart_alternative: /multipart\/alternative/i.test(text),
+          multipart_mixed: /multipart\/mixed/i.test(text),
+          // Quoted-printable encodes '=' as '=3D', so the literal 'stamp='
+          // is NOT in the transferred body - looking for it was a naive check.
+          stamp_in_body_qp: text.indexOf('stamp=3D' + stamp) !== -1,
+          // multipart/mixed is declared in the HEADER (it is the top-level
+          // Content-Type); only the inner alternative boundary shows in TEXT.
+          mixed_in_header: /multipart\/mixed/i.test(header),
+        },
+        headerEncoding: found.headerEncoding,
+        // The exact bytes around the Subject, escaped, so a fold is visible.
+        subject_region: (function () {
+          const i = header.search(/^Subject:/mi);
+          if (i < 0) return null;
+          return header.slice(i, i + 120).replace(/\r/g, '<CR>').replace(/\n/g, '<LF>');
+        })(),
+      };
+    }
+
+    return { op, ok: false, error: 'unknown op; use mailboxes|read|small|unseen|accents|send' };
+  } catch (e) {
+    // The shape a consumer branches on: slug, status and retryable.
+    // NOT a key called `status`: a returned object carrying status, headers or
+    // body is read as a response ENVELOPE, and an envelope may hold nothing
+    // else - so a diagnostic field named `status` turns into a 500
+    // invalid_return and hides the very error it was meant to report.
+    return {
+      op, ok: false, ms: Date.now() - started,
+      code: e.code || null,
+      httpStatus: e.status || null,
+      retryable: (e.details && e.details.retryable) ?? null,
+      message: String(e.message || e).slice(0, 400),
+    };
+  }
+}