@sayedhfatimi/convex-email 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/README.md +308 -53
  2. package/dist/adapters/resend/inbound.d.ts.map +1 -1
  3. package/dist/adapters/resend/inbound.js +21 -5
  4. package/dist/adapters/resend/inbound.js.map +1 -1
  5. package/dist/adapters/resend/send.d.ts.map +1 -1
  6. package/dist/adapters/resend/send.js +9 -1
  7. package/dist/adapters/resend/send.js.map +1 -1
  8. package/dist/adapters/ses/inbound.d.ts.map +1 -1
  9. package/dist/adapters/ses/inbound.js +10 -3
  10. package/dist/adapters/ses/inbound.js.map +1 -1
  11. package/dist/adapters/ses/send.d.ts.map +1 -1
  12. package/dist/adapters/ses/send.js +4 -0
  13. package/dist/adapters/ses/send.js.map +1 -1
  14. package/dist/client/index.d.ts +20 -4
  15. package/dist/client/index.d.ts.map +1 -1
  16. package/dist/client/index.js +35 -20
  17. package/dist/client/index.js.map +1 -1
  18. package/dist/component/_generated/component.d.ts +2 -1
  19. package/dist/component/_generated/component.d.ts.map +1 -1
  20. package/dist/component/cleanup.d.ts +7 -0
  21. package/dist/component/cleanup.d.ts.map +1 -1
  22. package/dist/component/cleanup.js +141 -10
  23. package/dist/component/cleanup.js.map +1 -1
  24. package/dist/component/credentials.d.ts +11 -1
  25. package/dist/component/credentials.d.ts.map +1 -1
  26. package/dist/component/credentials.js +38 -3
  27. package/dist/component/credentials.js.map +1 -1
  28. package/dist/component/deliver.d.ts +13 -3
  29. package/dist/component/deliver.d.ts.map +1 -1
  30. package/dist/component/deliver.js +88 -36
  31. package/dist/component/deliver.js.map +1 -1
  32. package/dist/component/events.d.ts +15 -0
  33. package/dist/component/events.d.ts.map +1 -1
  34. package/dist/component/events.js +91 -31
  35. package/dist/component/events.js.map +1 -1
  36. package/dist/component/inbound.js +3 -3
  37. package/dist/component/inbound.js.map +1 -1
  38. package/dist/component/schema.d.ts +18 -4
  39. package/dist/component/schema.d.ts.map +1 -1
  40. package/dist/component/schema.js +22 -4
  41. package/dist/component/schema.js.map +1 -1
  42. package/dist/component/send.d.ts +5 -3
  43. package/dist/component/send.d.ts.map +1 -1
  44. package/dist/component/send.js +33 -15
  45. package/dist/component/send.js.map +1 -1
  46. package/dist/component/unsubscribe.d.ts.map +1 -1
  47. package/dist/component/unsubscribe.js +2 -1
  48. package/dist/component/unsubscribe.js.map +1 -1
  49. package/dist/component/webhooks.d.ts.map +1 -1
  50. package/dist/component/webhooks.js +3 -1
  51. package/dist/component/webhooks.js.map +1 -1
  52. package/dist/shared/readCapped.d.ts +2 -0
  53. package/dist/shared/readCapped.d.ts.map +1 -1
  54. package/dist/shared/readCapped.js +9 -0
  55. package/dist/shared/readCapped.js.map +1 -1
  56. package/package.json +1 -1
  57. package/src/adapters/resend/inbound.ts +20 -5
  58. package/src/adapters/resend/send.ts +10 -1
  59. package/src/adapters/ses/inbound.ts +9 -3
  60. package/src/adapters/ses/send.ts +4 -0
  61. package/src/client/index.ts +42 -21
  62. package/src/component/_generated/component.ts +2 -2
  63. package/src/component/cleanup.ts +158 -11
  64. package/src/component/credentials.ts +39 -5
  65. package/src/component/deliver.ts +104 -35
  66. package/src/component/events.ts +111 -41
  67. package/src/component/inbound.ts +3 -3
  68. package/src/component/schema.ts +22 -4
  69. package/src/component/send.ts +41 -12
  70. package/src/component/unsubscribe.ts +2 -1
  71. package/src/component/webhooks.ts +4 -2
  72. package/src/shared/readCapped.ts +9 -0
package/README.md CHANGED
@@ -1,15 +1,33 @@
1
1
  # @sayedhfatimi/convex-email
2
2
 
3
- A provider-neutral email component for [Convex](https://convex.dev). One client class, `Email`, sends and receives mail through Resend or Amazon SES, stores every message and delivery event, and keeps suppressions, unsubscribes and threads in one place, so you can move from one provider to the other without losing any of it.
3
+ Send **and receive** email in [Convex](https://convex.dev), on Resend or Amazon SES, so you can build inboxes, support desks and reply-by-email into your app. One client class, `Email`, stores every message and delivery event and keeps suppressions, unsubscribes and threads in one place, so you can move from one provider to the other without losing any of it.
4
4
 
5
- - Sending is queued: `mail.send` returns a message id at once and delivery runs in the background with retries.
6
- - Credentials never enter the component. Your app supplies them from a callback, per use.
7
- - Test mode is on by default: only addresses you allowlist are really sent to.
8
- - Delivery events (sent, delivered, bounced, complained, ...) update the message and, for hard bounces and complaints, suppress the address.
9
- - Inbound mail (Resend receiving, SES receipt rules, or raw MIME you hold) is parsed, cleaned, threaded and handed to your `onInbound` function.
10
- - Optional tenants: one deployment can serve several customers, each with their own provider account.
5
+ Live demo: [convex-email.dev](https://convex-email.dev) (coming soon).
11
6
 
12
- Status: 0.1.0 is not released yet. Resend and SES have been exercised against fakes and recorded payloads; the items still to be confirmed against the live providers are listed under [Not yet verified live](#not-yet-verified-live).
7
+ ## Why convex-email
8
+
9
+ Receiving, from Resend receiving, an SES receipt rule, or raw MIME you already hold:
10
+
11
+ - **Parsed and cleaned.** The message is parsed (MIME for SES and raw mail, the Receiving API's JSON for Resend), the HTML cleaned with an allow-list (remote images kept but flagged), and bodies and attachments stored in file storage.
12
+ - **Verdicts.** SPF, DKIM and DMARC from the provider, from verdicts you pass with raw MIME, or from an `Authentication-Results` header you trust.
13
+ - **Threading.** A reply joins the thread of the message it answers. When it answers one of yours, `parent` names that message, its tags, and whether the sender was one of its recipients.
14
+ - **De-duplication.** A provider that delivers the same notification twice gets one stored message.
15
+ - **An `onInbound` hook.** Your mutation gets each message, normalized, and returns `{ handled }`. Unhandled and failed mail stays listable and can be retried.
16
+ - **Text for HTML-only mail.** When the sender sent only HTML, `text` is derived from it and flagged `textFromHtml`.
17
+
18
+ Sending:
19
+
20
+ - **An outbox.** `mail.send` returns a message id at once; delivery runs in the background, with retries, on separate transactional and bulk queues.
21
+ - **Suppression.** Hard bounces and complaints suppress the address for later sends.
22
+ - **One-click unsubscribe.** RFC 8058 `List-Unsubscribe` headers with signed links, per category.
23
+ - **Events.** Sent, delivered, bounced, complained and the rest update the message, with an optional `onEvent` hook.
24
+ - **Tenants.** One deployment can serve several customers, each with their own provider account.
25
+ - **Test mode**, on by default: only addresses you allowlist are really sent to.
26
+ - **Resend to SES cutover** (and back) by flipping `sendVia`, keeping suppressions, unsubscribes and threads.
27
+
28
+ Credentials never enter the component: your app supplies them from a callback, per use.
29
+
30
+ Status: released (0.1.x) and tested live against Resend and Amazon SES. What was confirmed, and what is still open, is under [Verified live, and what is not yet](#verified-live-and-what-is-not-yet).
13
31
 
14
32
  The component runs entirely in Convex's default runtime. Components cannot contain `"use node"` files, so HTML cleaning, SNS signature checks and SigV4 signing all use runtime-neutral libraries.
15
33
 
@@ -183,11 +201,210 @@ export default http;
183
201
 
184
202
  The webhook URLs are on your deployment's HTTP actions domain (`https://<deployment>.convex.site/email/webhook/resend`).
185
203
 
204
+ To filter or route requests yourself (for example when the provider account is shared with other apps), call `mail.handleWebhook(ctx, request, provider)` from your own `httpAction`; pass `{ tenant }` as the fourth argument to scope the event to a tenant. `tenant` also selects which webhook secret verifies the request, so it must come from your app (for example from the route), never from the request body or headers. Read the body for your own check with `request.clone()`, because a body can be read only once.
205
+
206
+ ```ts
207
+ /**
208
+ * Mount it with `http.route({ path: "/email/webhook/resend", method: "POST", handler: filteredResendWebhook })`.
209
+ * The body is not verified yet, so use it only to drop requests, never to trust one.
210
+ */
211
+ export const filteredResendWebhook = httpAction(async (ctx, request) => {
212
+ // Read the body for your own check from a clone: a body can be read once.
213
+ // A body that is not JSON, or is `null`, is dropped rather than a 500.
214
+ const event: unknown = await request
215
+ .clone()
216
+ .json()
217
+ .catch(() => null);
218
+ const data = (event as { data?: Record<string, unknown> } | null)?.data;
219
+ // Your sending domains and your `ownDomains` (receiving domains).
220
+ const myDomains = ["example.com"];
221
+ const list = (x: unknown): unknown[] => (Array.isArray(x) ? x : [x]);
222
+ // `Name <a@b>` or `a@b`; the domain must match exactly (not `evil-example.com`).
223
+ const atMyDomain = (a: unknown) => {
224
+ if (typeof a !== "string") return false;
225
+ const addr = (/<([^<>]*)>\s*$/.exec(a)?.[1] ?? a).trim().toLowerCase();
226
+ return myDomains.some((d) => addr.endsWith(`@${d}`));
227
+ };
228
+ // Sent, delivered, bounced and complained events name you in `from`; inbound
229
+ // mail names you in `to`, `cc` or `bcc` (the adapter accepts all three).
230
+ const fields = [
231
+ data?.from,
232
+ data?.to,
233
+ data?.cc,
234
+ data?.bcc,
235
+ data?.received_for,
236
+ ];
237
+ const mine = fields.flatMap(list).some(atMyDomain);
238
+ if (!mine) return new Response("ignored", { status: 200 });
239
+ return await mail.handleWebhook(ctx, request, "resend");
240
+ });
241
+ ```
242
+
243
+ ## Build a mailbox
244
+
245
+ With the set-up above, an inbox, a support desk or reply-by-email is a table of your own plus a few functions. Your `onInbound` mutation files each message under its `threadId`; your queries list a thread; replies go out with `inReplyTo`, which puts them in the same thread.
246
+
247
+ The table, and the `onInbound` mutation that fills it (set it as `onInbound` in the `Email` options):
248
+
249
+ ```ts
250
+ /** Your table: add it to `defineSchema` in `convex/schema.ts` as `mailbox`. */
251
+ export const mailbox = defineTable({
252
+ tenant: v.optional(v.string()),
253
+ threadId: v.string(),
254
+ messageId: v.string(), // the component's message id
255
+ direction: v.union(v.literal("inbound"), v.literal("outbound")),
256
+ from: v.string(),
257
+ subject: v.string(),
258
+ text: v.optional(v.string()), // absent when the body came by reference
259
+ attachments: v.array(v.object({ id: v.string(), filename: v.string() })),
260
+ at: v.number(),
261
+ }).index("by_thread", ["tenant", "threadId", "at"]);
262
+
263
+ /** Set as `onInbound`: file each message under its thread. */
264
+ export const fileInbound = internalMutation({
265
+ args: vInboundForApp,
266
+ handler: async (ctx, m): Promise<{ handled: boolean; note?: string }> => {
267
+ if (m.verdicts.dmarc === "fail") {
268
+ // Not handled: it stays in `listUnhandled` for a person to look at.
269
+ return { handled: false, note: "DMARC failed" };
270
+ }
271
+ await ctx.db.insert("mailbox", {
272
+ tenant: m.tenant,
273
+ threadId: m.threadId,
274
+ messageId: m.messageId,
275
+ direction: "inbound",
276
+ from: m.from.address,
277
+ subject: m.subject,
278
+ // HTML-only mail gets `text` derived from its HTML (`textFromHtml`).
279
+ text: m.text,
280
+ attachments: m.attachments.map(({ id, filename }) => ({ id, filename })),
281
+ at: Date.now(),
282
+ });
283
+ return { handled: true };
284
+ },
285
+ });
286
+ ```
287
+
288
+ Returning `{ handled: true }` marks the message handled. Returning `handled: false`, or throwing, keeps it `unhandled`: `mail.listUnhandled` lists it, with the `note` you returned, and `mail.retryInbound` calls `onInbound` again (see [Inbound mail](#inbound-mail)). Only the `onInbound` result sets this flag; keep your own open or answered state in your table.
289
+
290
+ List a thread, and read what a row does not hold:
291
+
292
+ ```ts
293
+ /** Your app's rule for who may read and answer mail: here, anyone signed in. */
294
+ async function requireAgent(ctx: { auth: Auth }): Promise<UserIdentity> {
295
+ const agent = await ctx.auth.getUserIdentity();
296
+ if (!agent) throw new Error("not signed in");
297
+ return agent;
298
+ }
299
+
300
+ /** Your app's rule for tenants: here, a `tenant` claim on the identity. */
301
+ function requireTenant(agent: UserIdentity, tenant: string | undefined): void {
302
+ if (agent.tenant !== tenant) throw new Error("not your tenant");
303
+ }
304
+
305
+ /** One conversation, oldest first. */
306
+ export const thread = query({
307
+ args: { tenant: v.optional(v.string()), threadId: v.string() },
308
+ handler: async (ctx, { tenant, threadId }) => {
309
+ requireTenant(await requireAgent(ctx), tenant);
310
+ return await ctx.db
311
+ .query("mailbox")
312
+ .withIndex("by_thread", (q) =>
313
+ q.eq("tenant", tenant).eq("threadId", threadId),
314
+ )
315
+ .take(200);
316
+ },
317
+ });
318
+
319
+ /** The full body: text and cleaned HTML, read from storage. */
320
+ export const messageBody = action({
321
+ args: { messageId: v.string() },
322
+ handler: async (
323
+ ctx,
324
+ { messageId },
325
+ ): Promise<{ text?: string; html?: string }> => {
326
+ const agent = await requireAgent(ctx);
327
+ const message = await mail.get(ctx, messageId);
328
+ if (!message) throw new Error("no such message");
329
+ requireTenant(agent, message.tenant);
330
+ return await mail.inboundBody(ctx, messageId);
331
+ },
332
+ });
333
+
334
+ /** A short-lived download URL for one attachment. */
335
+ export const attachmentLink = query({
336
+ args: { messageId: v.string(), attachmentId: v.string() },
337
+ handler: async (ctx, { messageId, attachmentId }): Promise<string | null> => {
338
+ const agent = await requireAgent(ctx);
339
+ const message = await mail.get(ctx, messageId);
340
+ if (!message) throw new Error("no such message");
341
+ requireTenant(agent, message.tenant);
342
+ if (!message.attachments.some((a) => a.id === attachmentId)) {
343
+ throw new Error("not an attachment of this message");
344
+ }
345
+ return await mail.attachmentUrl(ctx, attachmentId);
346
+ },
347
+ });
348
+ ```
349
+
350
+ The row keeps `text` for the thread view. `messageBody` reads the text and cleaned HTML from storage (as `get`'s `htmlUrl` and `textUrl` do), which you need when together they are over 256 KiB: `onInbound` then gets `bodyByReference: true` and no `text` or `html`. Show the HTML with remote images blocked by default (`hasRemoteImages` tells you there are some), and open stored bodies and attachment URLs away from your app's own origin (see [Inbound mail](#inbound-mail)).
351
+
352
+ Reply in the thread:
353
+
354
+ ```ts
355
+ /** Answer a message in its thread. */
356
+ export const replyInThread = mutation({
357
+ args: { messageId: v.string(), text: v.string() },
358
+ handler: async (ctx, { messageId, text }): Promise<string> => {
359
+ const agent = await requireAgent(ctx);
360
+ const original = await mail.get(ctx, messageId);
361
+ if (!original) throw new Error("no such message");
362
+ requireTenant(agent, original.tenant);
363
+ const subject = /^re:/i.test(original.subject)
364
+ ? original.subject
365
+ : `Re: ${original.subject}`;
366
+ const id = await mail.send(ctx, {
367
+ from: "Support <support@example.com>",
368
+ to: original.replyTo.length > 0 ? original.replyTo : original.from,
369
+ subject,
370
+ text,
371
+ // Sets In-Reply-To and References, and joins the original's thread.
372
+ inReplyTo: messageId,
373
+ tenant: original.tenant,
374
+ });
375
+ await ctx.db.insert("mailbox", {
376
+ tenant: original.tenant,
377
+ threadId: original.threadId,
378
+ messageId: id,
379
+ direction: "outbound",
380
+ from: "support@example.com",
381
+ subject,
382
+ text,
383
+ attachments: [],
384
+ at: Date.now(),
385
+ });
386
+ return id;
387
+ },
388
+ });
389
+ ```
390
+
391
+ When the customer answers your reply, the answer arrives with the same `threadId` and a `parent` naming your message, so it lands in the same conversation.
392
+
393
+ What your app owns:
394
+
395
+ - **Auth.** `get`, `inboundBody`, `attachmentUrl` and `status` take bare ids, and the component has no notion of users. `requireAgent` and `requireTenant` stand in for your own rules: every public function in this section checks both before it returns a row, a body or a link, or sends. The samples after it that are public (the send and upload ones) call `requireAgent`; the admin ones, and `receiveFromRouter`, are `internal*` functions for you to call from your own authorised code.
396
+ - **Tenants.** The component threads within a tenant, but a thread id is a Message-ID, so two tenants can hold the same one: the table's index starts with the tenant, and `requireTenant` checks that the caller belongs to it. A single-tenant app has no tenant, and the check passes when the identity has no `tenant` claim either.
397
+ - **Retention.** `cleanup` deletes stored bodies and attachment files past its cut-off, and with `purge: true` the messages too (see [Housekeeping](#housekeeping)); keep in your table what you need for longer.
398
+ - **Trust.** Threading follows the `In-Reply-To` and `References` headers the sender wrote, so anyone who quotes a Message-ID joins its thread. Check `verdicts`, and `parent.senderWasRecipient` for a reply to your own mail, before you act on who a message claims to be from.
399
+
186
400
  ## Sending
187
401
 
402
+ The samples from here on leave out the app's own auth, apart from `requireAgent` where a signed-in user calls them: a public function that sends or reads mail must check its caller first, and the `internal*` ones are for your own authorised functions to call.
403
+
188
404
  `mail.send(ctx, input)` works from a mutation or an action and returns the message id. It validates, writes the message row and the bodies, and queues delivery; it does not wait for the provider.
189
405
 
190
406
  ```ts
407
+ /** A reply to a stored message, with a tag the app can read back. */
191
408
  export const sendTicketReply = mutation({
192
409
  args: {
193
410
  to: v.string(),
@@ -195,8 +412,12 @@ export const sendTicketReply = mutation({
195
412
  replyId: v.string(),
196
413
  inReplyTo: v.string(),
197
414
  },
198
- handler: async (ctx, { to, ticketId, replyId, inReplyTo }): Promise<string> =>
199
- await mail.send(ctx, {
415
+ handler: async (
416
+ ctx,
417
+ { to, ticketId, replyId, inReplyTo },
418
+ ): Promise<string> => {
419
+ await requireAgent(ctx);
420
+ return await mail.send(ctx, {
200
421
  from: "Support <support@example.com>",
201
422
  to,
202
423
  subject: "Re: your request",
@@ -205,7 +426,8 @@ export const sendTicketReply = mutation({
205
426
  tags: { ticket: ticketId },
206
427
  // One key per reply: a key per ticket would swallow every later reply.
207
428
  idempotencyKey: `ticket-reply-${replyId}`,
208
- }),
429
+ });
430
+ },
209
431
  });
210
432
  ```
211
433
 
@@ -213,25 +435,28 @@ Fields: `from`, `to`, `cc`, `bcc`, `replyTo` (a string or an array), `subject`,
213
435
 
214
436
  - `inReplyTo` is a component message id or an RFC `Message-ID`. The component sets `In-Reply-To` and `References` and puts the message in the parent's thread.
215
437
  - `stream` is `"transactional"` (default) or `"bulk"`. Each has its own queue, so a newsletter cannot delay a sign-in email. A bulk send can use a second SES configuration set (`configurationSets.bulk`).
216
- - `idempotencyKey` is per tenant: a second `send` with the same key returns the first message's id instead of sending again.
438
+ - `idempotencyKey` is per tenant: a second `send` with the same key returns the first message's id instead of sending again, until `cleanup` with `purge: true` deletes the first message. The replay returns the first message whatever the second call's content: the content is not compared, so use a new key for a different message.
217
439
  - `tags` come back on `onEvent` and, for replies, on `parent.tags` in `onInbound`. Keys match `^[A-Za-z][A-Za-z0-9_-]{0,63}$`, values match `^[A-Za-z0-9_-]{1,256}$`, at most 50 tags, and the `cx_` prefix is reserved.
218
440
  - `headers` are extra headers. You cannot set structural or threading headers (`From`, `To`, `Cc`, `Bcc`, `Sender`, `Reply-To`, `Subject`, `Date`, `Return-Path`, `MIME-Version`, `Message-ID`, `In-Reply-To`, `References`, `List-Unsubscribe`, `List-Unsubscribe-Post`, anything `Content-*`), and each name may appear once (case-insensitive). At most 50 headers, each value up to 998 characters with no control characters. SESv2 accepts at most 15 custom headers: more than that is a permanent error from SES.
219
- - At most 100 recipients across `to`, `cc` and `bcc`. Addresses are lower-cased and de-duplicated. Recipients are sent as bare addresses (display names are not kept) in 0.1.0; the `from` display name is kept (on SES a non-ASCII one is RFC 2047 encoded).
441
+ - At most 100 recipients across `to`, `cc` and `bcc`. Addresses are lower-cased and de-duplicated. An address may not contain `"` or `;` (a send that names one throws `is not a valid address`). Recipients are sent as bare addresses (display names are not kept) in 0.1.0; the `from` display name is kept (on SES a non-ASCII one is RFC 2047 encoded).
220
442
  - When `unsubscribe` is configured, a message with a `category` must have exactly one recipient across `to`, `cc` and `bcc`: the unsubscribe link in it names that address.
221
443
  - The raw size limit is 10 MiB on both adapters (bodies plus attachments). The providers allow about 30 MiB raw (40 MB after base64), but a send holds the whole message in memory in Convex's default runtime, so the component stays well below that; the live probes measure the real ceiling.
222
444
 
223
445
  Sending from an action works the same way:
224
446
 
225
447
  ```ts
448
+ /** `send` works from an action too. */
226
449
  export const sendFromAction = action({
227
450
  args: { to: v.string() },
228
- handler: async (ctx, { to }): Promise<string> =>
229
- await mail.send(ctx, {
451
+ handler: async (ctx, { to }): Promise<string> => {
452
+ await requireAgent(ctx);
453
+ return await mail.send(ctx, {
230
454
  from: "Example <hello@example.com>",
231
455
  to,
232
456
  subject: "Sent from an action",
233
457
  text: "Hello.",
234
- }),
458
+ });
459
+ },
235
460
  });
236
461
  ```
237
462
 
@@ -240,9 +465,11 @@ export const sendFromAction = action({
240
465
  Store the file first, then pass its id. An attachment can be linked to one message only.
241
466
 
242
467
  ```ts
468
+ /** Store a file, then attach it. An attachment links to one message only. */
243
469
  export const sendWithAttachment = mutation({
244
470
  args: { to: v.string(), bytes: v.bytes() },
245
471
  handler: async (ctx, { to, bytes }): Promise<string> => {
472
+ await requireAgent(ctx);
246
473
  const invoice = await mail.storeAttachment(ctx, {
247
474
  bytes,
248
475
  filename: "invoice.pdf",
@@ -262,9 +489,13 @@ export const sendWithAttachment = mutation({
262
489
  For a large file, have the browser upload to a one-time URL instead of passing bytes through a mutation:
263
490
 
264
491
  ```ts
492
+ /** For a large file: the browser uploads to this URL, then registers it. */
265
493
  export const startUpload = mutation({
266
494
  args: {},
267
- handler: async (ctx): Promise<string> => await mail.attachmentUploadUrl(ctx),
495
+ handler: async (ctx): Promise<string> => {
496
+ await requireAgent(ctx);
497
+ return await mail.attachmentUploadUrl(ctx);
498
+ },
268
499
  });
269
500
 
270
501
  export const finishUpload = mutation({
@@ -273,8 +504,10 @@ export const finishUpload = mutation({
273
504
  filename: v.string(),
274
505
  contentType: v.string(),
275
506
  },
276
- handler: async (ctx, args): Promise<string> =>
277
- await mail.registerUpload(ctx, args),
507
+ handler: async (ctx, args): Promise<string> => {
508
+ await requireAgent(ctx);
509
+ return await mail.registerUpload(ctx, args);
510
+ },
278
511
  });
279
512
  ```
280
513
 
@@ -284,12 +517,16 @@ export const finishUpload = mutation({
284
517
 
285
518
  A message's `status` is one of `queued`, `test`, `suppressed`, `sending`, `sent`, `delivery_delayed`, `delivered`, `bounced`, `complained`, `failed`, `rejected` (and `received` for inbound mail). It only moves forward, so events that arrive out of order cannot undo a later state. `mail.status(ctx, id)` returns it; `mail.get(ctx, id)` returns the message with its attachments, events and short-lived URLs for the stored bodies (`null` once `cleanup` has removed them).
286
519
 
287
- Delivery to the provider is retried when the failure is transient (8 attempts, backing off from 5 s and doubling: about ten minutes in all), and recorded as `failed` with an error text when it is not or when the attempts run out. The error text never contains a credential and is cut to 1000 characters. The transactional queue runs 4 sends at a time, the bulk queue 2.
520
+ Delivery to the provider is retried when the failure is transient (8 attempts, backing off from 5 s and doubling: about ten minutes in all), and recorded as `failed` with an error text when it is not or when the attempts run out. A provider 5xx counts as a possible acceptance: the message is marked `deliveryAmbiguous` (and is still retried). Resend's daily or monthly quota error fails at once, without retries. The error text never contains a credential and is cut to 1000 characters. The transactional queue runs 4 sends at a time, the bulk queue 2.
288
521
 
289
- `mail.retrySend(ctx, messageId)` queues a `failed` message again (status back to `queued`, error cleared, on its own stream's queue). It re-runs the suppression and unsubscribe checks first, so a recipient who bounced, complained or unsubscribed since is dropped into `suppressedRecipients`; if no `To` recipient is left the message becomes `suppressed` and is not queued. It returns the resulting status (`queued` or `suppressed`). It throws for any other status, and for a failure the provider reported after accepting the message (send that one anew). When an attempt ended without an answer from the provider (a network error or a timeout), the message is marked `deliveryAmbiguous` (readable from `get`): the provider may already have delivered it. `retrySend` then refuses unless you pass `{ force: true }`. Resend drops a resend of the same message within its idempotency window (the key is the component message id); SES has no idempotency key, so a forced retry on SES can deliver twice.
522
+ `mail.retrySend(ctx, messageId)` queues a `failed` message again (status back to `queued`, error cleared, on its own stream's queue). It re-runs the suppression and unsubscribe checks first, so a recipient who bounced, complained or unsubscribed since is dropped into `suppressedRecipients`; if no `To` recipient is left the message becomes `suppressed` and is not queued. Test mode is applied again from the config stored by the last send or webhook, not the app's current options, so a deploy that turns test mode on reaches retries only once a send or webhook has stored it. It returns the resulting status (`queued`, `suppressed`, or `test` when test mode is on and a recipient is not in `testAllowlist`, in which case nothing is sent). A retry that queues clears `deliveryAmbiguous`. It throws for any other status, and for a failure the provider reported after accepting the message (send that one anew). When an attempt ended without an answer from the provider (a network error, a timeout or a provider 5xx), the message is marked `deliveryAmbiguous` (readable from `get`): the provider may already have delivered it. `retrySend` then refuses unless you pass `{ force: true }`. Resend drops a resend of the same message within its idempotency window (the key is the component message id); SES has no idempotency key, so a forced retry on SES can deliver twice.
290
523
 
291
524
  ```ts
292
- export const retryFailedSend = mutation({
525
+ /**
526
+ * Queue a failed message again; `force` only after checking it never arrived.
527
+ * Internal: call it from your own authorised admin function.
528
+ */
529
+ export const retryFailedSend = internalMutation({
293
530
  args: { id: v.string(), force: v.optional(v.boolean()) },
294
531
  handler: async (ctx, { id, force }): Promise<void> => {
295
532
  await mail.retrySend(ctx, id, { force });
@@ -297,7 +534,7 @@ export const retryFailedSend = mutation({
297
534
  });
298
535
  ```
299
536
 
300
- Delivery is at-least-once in one narrow window: if the process dies between the provider accepting a message and the component recording it, the retry sends again. Resend drops the duplicate through the `Idempotency-Key` header (the component message id); SES has no idempotency key, so on SES that window can produce a duplicate.
537
+ Delivery is at-least-once in one narrow window: if the process dies between the provider accepting a message and the component recording it, the retry sends again. Resend drops the duplicate through the `Idempotency-Key` header (the component message id); SES has no idempotency key, so on SES that window can produce a duplicate. If the job cannot record the provider's acceptance, Workpool's completion step records it. A result with no recordable provider id ends the message `failed` and `deliveryAmbiguous` (error text: "the provider may have accepted this message, but its result could not be recorded"). Only a deterministic bug in the completion step itself, failing both inline and on Workpool's retry, could leave a message in `sending`.
301
538
 
302
539
  ## Credentials and the security model
303
540
 
@@ -379,7 +616,7 @@ Other rules the component keeps for you: it never reads `process.env`, never rea
379
616
 
380
617
  ## Test mode
381
618
 
382
- `testMode` defaults to `true`. In test mode, a message is only sent when every remaining recipient (to, cc and bcc) is in `testAllowlist`; otherwise it is stored with status `test` and nothing leaves. Set `testMode: false` (the example uses `EMAIL_LIVE=true`) when you are ready for real recipients. Suppressed and unsubscribed recipients are dropped before the test-mode check.
619
+ `testMode` defaults to `true`. In test mode, a message is only sent when every remaining recipient (to, cc and bcc) is in `testAllowlist`; otherwise it is stored with status `test` and nothing leaves. Set `testMode: false` (the example uses `EMAIL_LIVE=true`) when you are ready for real recipients. Suppressed and unsubscribed recipients are dropped before the test-mode check. `retrySend` applies test mode too, using the stored config.
383
620
 
384
621
  ## Tenants
385
622
 
@@ -401,9 +638,9 @@ Two consequences to plan for:
401
638
 
402
639
  ## Delivery events
403
640
 
404
- Each webhook is verified, parsed into normalized events and appended to the message's event log: `sent`, `delivered`, `delivery_delayed`, `bounced` (with `bounceType`: `hard`, `soft` or `undetermined`), `complained`, `failed`, `rejected`. Duplicates (providers redeliver) are ignored. An event for a message this component did not send, for example from another product on a shared Resend account, is stored as an orphan and otherwise ignored. Orphan events accumulate: `cleanup` does not prune them yet.
641
+ Each webhook is verified, parsed into normalized events and appended to the message's event log: `sent`, `delivered`, `delivery_delayed`, `bounced` (with `bounceType`: `hard`, `soft` or `undetermined`), `complained`, `failed`, `rejected`. Duplicates (providers redeliver) are ignored. An event for a message this component did not send, for example from another product on a shared Resend account, is stored as an orphan and otherwise ignored. An event that arrives before the send is recorded (a fast provider can report one before the component stores its provider id) is held the same way and applied once the send is recorded, from the tenant's own route or an account-level one. Orphan events stay until `cleanup` runs with `purge: true`, which removes those older than its cut-off. Use a cut-off of hours or more, not minutes: an early event waits as an orphan until its send is recorded, and a short cut-off could purge it first.
405
642
 
406
- `onEvent` is called through a queue for each event that matched a message (not for orphans), so a slow handler never blocks the webhook:
643
+ `onEvent` is called through a queue for each event that matched a message (not for orphans; for an early event, once it is applied), so a slow handler never blocks the webhook:
407
644
 
408
645
  ```ts
409
646
  export const onEvent = internalMutation({
@@ -417,13 +654,14 @@ export const onEvent = internalMutation({
417
654
  A hard bounce or a complaint adds a suppression for the addresses the message went to. Soft and undetermined bounces do not. A suppressed address is dropped from later sends (listed in the message's `suppressedRecipients`); if every recipient is dropped, or every `to` recipient is (no message goes out without a `To`), the message is `suppressed`. Addresses are lower-cased and trimmed, never plus-stripped.
418
655
 
419
656
  ```ts
420
- export const suppressed = query({
657
+ /** Internal: call it from your own authorised admin function. */
658
+ export const suppressed = internalQuery({
421
659
  args: { paginationOpts: paginationOptsValidator },
422
660
  handler: async (ctx, { paginationOpts }) =>
423
661
  await mail.suppressions.list(ctx, { paginationOpts }),
424
662
  });
425
663
 
426
- export const unsuppress = mutation({
664
+ export const unsuppress = internalMutation({
427
665
  args: { address: v.string() },
428
666
  handler: async (ctx, { address }): Promise<void> => {
429
667
  await mail.suppressions.remove(ctx, { address });
@@ -438,17 +676,20 @@ export const unsuppress = mutation({
438
676
  Send with a `category` and, if you configured `unsubscribe: { url, mailto? }`, the message carries `List-Unsubscribe` (your URL with a signed token `t`, plus a `mailto:` when set) and `List-Unsubscribe-Post: List-Unsubscribe=One-Click`. The token is signed with the `unsubscribeSecret` from your credentials callback, which is asked with `{ provider: null, tenant, purpose: "unsubscribe" }` both when signing and when checking a link, so links survive a provider cutover. The token names the tenant, address and category. The URL and `mailto` are those configured when the message was sent. A bulk send with a category and no `unsubscribe` option is rejected; on the transactional stream the header is simply left off.
439
677
 
440
678
  ```ts
679
+ /** A newsletter: its own lane, with an unsubscribe link for the category. */
441
680
  export const sendNewsletter = mutation({
442
681
  args: { to: v.string() },
443
- handler: async (ctx, { to }): Promise<string> =>
444
- await mail.send(ctx, {
682
+ handler: async (ctx, { to }): Promise<string> => {
683
+ await requireAgent(ctx);
684
+ return await mail.send(ctx, {
445
685
  from: "News <news@example.com>",
446
686
  to,
447
687
  subject: "This month",
448
688
  html: "<p>News.</p>",
449
689
  stream: "bulk",
450
690
  category: "newsletter",
451
- }),
691
+ });
692
+ },
452
693
  });
453
694
  ```
454
695
 
@@ -460,13 +701,14 @@ How `unsubscribeHandler` behaves:
460
701
  Read and change a person's choices from your own preferences screen:
461
702
 
462
703
  ```ts
463
- export const preferences = query({
704
+ /** Internal: your function checks that `address` is the signed-in user's own. */
705
+ export const preferences = internalQuery({
464
706
  args: { address: v.string() },
465
707
  handler: async (ctx, { address }) =>
466
708
  await mail.unsubscribes.list(ctx, { address }),
467
709
  });
468
710
 
469
- export const resubscribe = mutation({
711
+ export const resubscribe = internalMutation({
470
712
  args: { address: v.string() },
471
713
  handler: async (ctx, { address }): Promise<void> => {
472
714
  await mail.unsubscribes.set(ctx, {
@@ -527,13 +769,16 @@ export const readBody = internalAction({
527
769
  await mail.inboundBody(ctx, id),
528
770
  });
529
771
 
530
- /** A support screen: unhandled and failed inbound mail, and a retry. */
531
- export const unhandled = query({
772
+ /**
773
+ * A support screen: unhandled and failed inbound mail, and a retry. Internal:
774
+ * call them from your own functions, after checking who is asking.
775
+ */
776
+ export const unhandled = internalQuery({
532
777
  args: {},
533
778
  handler: async (ctx) => await mail.listUnhandled(ctx, { limit: 50 }),
534
779
  });
535
780
 
536
- export const retry = action({
781
+ export const retry = internalAction({
537
782
  args: { id: v.string() },
538
783
  handler: async (ctx, { id }) => await mail.retryInbound(ctx, id),
539
784
  });
@@ -544,19 +789,18 @@ export const retry = action({
544
789
  If you already hold the raw message (for example your own mail router), hand it in; it runs the same pipeline:
545
790
 
546
791
  ```ts
547
- export const receiveFromRouter = action({
792
+ export const receiveFromRouter = internalAction({
548
793
  args: { mime: v.bytes() },
549
794
  handler: async (ctx, { mime }): Promise<string> =>
550
- await mail.receiveRaw(ctx, {
551
- mime,
552
- source: "console-router",
553
- // Omit `verdicts` to fall back to a trusted Authentication-Results header.
554
- verdicts: { spf: "pass", dkim: "pass", dmarc: "pass" },
555
- }),
795
+ // Call this from your own authenticated route or function, the one that
796
+ // actually receives the raw message. `verdicts` is omitted on purpose: the
797
+ // component then reads a trusted Authentication-Results header, or records
798
+ // no verdict. Pass `verdicts` only if your own router computed them.
799
+ await mail.receiveRaw(ctx, { mime, source: "console-router" }),
556
800
  });
557
801
  ```
558
802
 
559
- Verdicts you pass are recorded with `source` as their origin, never as the provider's, and are authoritative: no header is read, even when you pass `{}`. The `keepRawMime` option applies to `receiveRaw` only: the raw bytes are stored for it and deleted after parsing unless `keepRawMime` is `true`. Provider-delivered mail is never kept raw by the component.
803
+ Without `verdicts`, the component reads a trusted Authentication-Results header (see `trustedAuthServIds`) and otherwise records none. Verdicts you pass are recorded with `source` as their origin, never as the provider's, and are authoritative: no header is read, even when you pass `{}`. The `keepRawMime` option applies to `receiveRaw` only: the raw bytes are stored for it and deleted after parsing unless `keepRawMime` is `true`. Provider-delivered mail is never kept raw by the component.
560
804
 
561
805
  ## Resend set-up
562
806
 
@@ -570,7 +814,7 @@ Resend dedupes sends through the `Idempotency-Key` header, which the component s
570
814
 
571
815
  ## Amazon SES set-up
572
816
 
573
- 1. **Identity.** Verify the domain (or address) you send from in SES, in the region you will use, and move the account out of the sandbox.
817
+ 1. **Identity.** Verify the domain (or address) you send from in SES, in the region you will use, and move the account out of the sandbox. While the account is still in the sandbox, SES only delivers to verified identities, and it checks the sender's IAM permission against the **recipient's** identity as well. So add each verified recipient's identity ARN (for example `arn:aws:ses:<region>:<account>:identity/you@example.org`) to the `ses:SendEmail` resources in step 5, or every send to it fails with `AccessDeniedException`. SES's mailbox simulator addresses are exempt.
574
818
  2. **Configuration sets, one per stream.** Create a configuration set for the transactional stream (and a second one for bulk if you want separate reputation and metrics). Add an event destination to each that publishes to an SNS topic, with the event types `Send`, `Delivery`, `DeliveryDelay`, `Bounce`, `Complaint`, `Reject` and `Rendering Failure`. Return them as `configurationSets: { transactional, bulk? }`; a bulk send uses the transactional set when no bulk one is given.
575
819
  3. **SNS to the webhook.** Subscribe each topic over HTTPS to `https://<deployment>.convex.site/email/webhook/ses` (or the per-tenant route). The component confirms the subscription itself. It verifies every SNS message signature (the signing certificate is fetched only from an `sns.<region>.amazonaws.com` host) and refuses topics that are not listed: put every topic ARN, including the inbound one, in `trustedTopicArns`. A failed verification is a 401; a certificate that cannot be fetched (network error, timeout, non-2xx) is a 500, so SNS delivers the message again.
576
820
  4. **Inbound (optional).** Verify the receiving domain's MX record, create an S3 bucket, and add a receipt rule with an S3 action that writes to the bucket and notifies an SNS topic (the notification must carry the bucket and object key, so set the topic on the S3 action). Subscribe the topic to the same webhook. List the bucket in `inboundBuckets`: the adapter will only read buckets named there, and with none listed it refuses all inbound fetches. SES receiving is only available in some regions.
@@ -605,7 +849,7 @@ The `ses:FromAddress` condition stops the key from being used to send as any oth
605
849
 
606
850
  Return `{ provider: "ses", region, accessKeyId, secretAccessKey, sessionToken?, configurationSets, trustedTopicArns, inboundBuckets }` from your callback.
607
851
 
608
- SES chooses the `Message-ID` itself, so the component sends none: it learns the real one from the `Send` event and updates the message. The tenant, when there is one, is sent as the SES `TenantName`.
852
+ SES chooses the `Message-ID` itself, so the component sends none. It records the id SES puts in the delivered header, `<MessageId@<region>.amazonses.com>` (`<MessageId@email.amazonses.com>` in us-east-1). SES's events carry only the bare `MessageId`, without `@`, which is never allowed to replace it. Replies quote the full form in `In-Reply-To`, so they thread. The tenant, when there is one, is sent as the SES `TenantName`.
609
853
 
610
854
  ## Capabilities
611
855
 
@@ -647,7 +891,9 @@ Every message records the provider that sent or received it, and an old message'
647
891
 
648
892
  ## Housekeeping
649
893
 
650
- `cleanup({ olderThanMs })` deletes stored bodies, attachment rows and files, and the kept raw MIME of handled inbound mail, for messages older than the cut-off. It keeps message rows and events, so history and threading survive. It never touches `queued` or `sending` messages, or inbound mail that is unhandled or failed. It is global (not per tenant) and bounded per call: when it returns `more: true`, call it again. A duplicate inbound row never purges the message it points at; only the row that stored that message does. Orphan events are not pruned yet.
894
+ `cleanup({ olderThanMs })` deletes stored bodies, attachment rows and files, and the kept raw MIME of handled inbound mail, for messages older than the cut-off. It keeps message rows and events, so history and threading survive. It never touches `queued` or `sending` messages, or inbound mail that is unhandled or failed. It is global (not per tenant) and bounded per call: when it returns `more: true`, call it again. A duplicate inbound row never purges the message it points at; only the row that stored that message does.
895
+
896
+ `cleanup({ olderThanMs, purge: true })` does the same and then deletes the rows as well: outbound messages in a final status (`test`, `suppressed`, `sent`, `delivery_delayed`, `delivered`, `bounced`, `complained`, `failed`, `rejected`) not updated since the cut-off, with their events and attachments; handled inbound rows older than the cut-off, with the message each one stored and its raw MIME (a duplicate row deletes only itself); and orphan events older than the cut-off. A message is kept when its status (or its Message-ID) changed after the cut-off; an event that changes neither, such as a second recipient's `delivered`, does not extend its life, and the purge deletes that event with the message. A delivery still delayed after the cut-off counts as final. It never touches `queued` or `sending` messages, inbound mail that is received, fetched, unhandled or failed, suppressions or unsubscribes. It is global and bounded the same way: call it again while it returns `more: true`. Deleting the rows has costs. A reply to a purged message no longer joins its thread: `inReplyTo` with the purged message's Message-ID starts a new thread from that id, and with its component id it throws. An inbound reply to a purged message gets no `parent` and does not adopt its tenant. A `send` with a purged message's `idempotencyKey` sends again. A late event for a purged message is stored as an orphan, which a later purge removes. A provider that redelivers a purged inbound notification has it processed again, because the row that de-duplicated it is gone. A suppression keeps the id of a message that may be gone.
651
897
 
652
898
  ```ts
653
899
  /** Runs `cleanup` again while it reports `more`. */
@@ -676,14 +922,23 @@ export const exampleCrons = () => {
676
922
 
677
923
  where `internal.email.cleanup` is the `internalMutation` in the example app that calls `mail.cleanup(ctx, { olderThanMs: 90 * 24 * 60 * 60 * 1000 })`.
678
924
 
679
- ## Not yet verified live
925
+ ## Verified live, and what is not yet
926
+
927
+ Checked against the real services on 2026-12-03, on Resend and on SES in eu-north-1 (in the sandbox):
928
+
929
+ - **Resend** replaces the component's `Message-ID` with its own. The component records the real one from the events, and replies thread.
930
+ - **SES** delivers the header `<MessageId@eu-north-1.amazonses.com>`, which the component records, and replies thread.
931
+ - **Resend's Receiving API and its `email.received` webhook** match the adapter. The test fixtures are captured real payloads, with personal data replaced.
932
+ - **Bounces and complaints** (both providers' simulators) suppress the address, and a late `delivered` event does not undo a complaint.
933
+ - **Inbound on SES** works end to end (MX, receipt rule, S3, SNS, the component), with SES's own SPF/DKIM/DMARC verdicts.
934
+ - **Switching providers** (`sendVia` from SES back to Resend) keeps suppressions.
680
935
 
681
- These points depend on how the real providers behave and are confirmed in a live test before 0.1.0 is released:
936
+ Not yet verified live:
682
937
 
683
- - Whether Resend keeps the `Message-ID` header the component generates (the component relies on it to match replies to messages).
684
- - The format of the SES `Message-ID` host (the adapter derives `<id@email.amazonses.com>` or a regional host; the `Send` event's value replaces it).
685
- - The field names of Resend's Receiving API and `email.received` webhook.
686
- - How large a message the default runtime can send and receive (the 10 MiB cap is deliberately conservative until then).
938
+ - The us-east-1 SES header host (`email.amazonses.com`), which is covered by tests only.
939
+ - A send for a tenant on SES (SES `TenantName`).
940
+ - A late Resend event arriving after switching to SES.
941
+ - How large a message the default runtime can send and receive. The 10 MiB cap is deliberately conservative until then.
687
942
 
688
943
  ## Development
689
944
 
@@ -1 +1 @@
1
- {"version":3,"file":"inbound.d.ts","sourceRoot":"","sources":["../../../src/adapters/resend/inbound.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAEV,mBAAmB,EAEnB,aAAa,EACd,MAAM,uBAAuB,CAAC;AAoK/B,wBAAsB,kBAAkB,CACtC,KAAK,EAAE;IAAE,MAAM,EAAE,MAAM,CAAA;CAAE,EACzB,CAAC,EAAE,mBAAmB,GACrB,OAAO,CAAC,aAAa,CAAC,CAqExB"}
1
+ {"version":3,"file":"inbound.d.ts","sourceRoot":"","sources":["../../../src/adapters/resend/inbound.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAEV,mBAAmB,EAEnB,aAAa,EACd,MAAM,uBAAuB,CAAC;AAmL/B,wBAAsB,kBAAkB,CACtC,KAAK,EAAE;IAAE,MAAM,EAAE,MAAM,CAAA;CAAE,EACzB,CAAC,EAAE,mBAAmB,GACrB,OAAO,CAAC,aAAa,CAAC,CAqExB"}
@@ -1,6 +1,6 @@
1
1
  import { parseAddressList } from "../../shared/address.js";
2
2
  import { toVerdict } from "../../shared/authResults.js";
3
- import { readCapped } from "../../shared/readCapped.js";
3
+ import { discardBody, readCapped } from "../../shared/readCapped.js";
4
4
  import { RESEND_API, RESEND_MAX_BYTES } from "./send.js";
5
5
  const MAX_ATTACHMENTS = 100;
6
6
  const isObject = (x) => typeof x === "object" && x !== null && !Array.isArray(x);
@@ -16,9 +16,17 @@ async function getJson(apiKey, path) {
16
16
  catch {
17
17
  throw new Error("Resend receiving fetch failed");
18
18
  }
19
- if (!res.ok)
19
+ if (!res.ok) {
20
+ await discardBody(res);
20
21
  throw new Error(`Resend receiving fetch failed (${res.status})`);
21
- const json = await res.json();
22
+ }
23
+ let json;
24
+ try {
25
+ json = await res.json();
26
+ }
27
+ catch {
28
+ throw new Error("Resend receiving fetch failed");
29
+ }
22
30
  if (!isObject(json))
23
31
  throw new Error("Resend receiving fetch failed");
24
32
  return json;
@@ -58,7 +66,7 @@ function stripAngles(id) {
58
66
  function sizeOf(x) {
59
67
  const n = typeof x === "number"
60
68
  ? x
61
- : typeof x === "string" && x.trim()
69
+ : typeof x === "string" && /^\d+$/.test(x.trim())
62
70
  ? Number(x)
63
71
  : NaN;
64
72
  return Number.isFinite(n) && n >= 0 ? n : undefined;
@@ -118,12 +126,20 @@ async function fetchAttachment(apiKey, emailId, meta, limit) {
118
126
  }
119
127
  if (res.type === "opaqueredirect" ||
120
128
  (res.status >= 300 && res.status < 400)) {
129
+ await discardBody(res);
121
130
  throw new Error("Resend attachment download was redirected");
122
131
  }
123
132
  if (!res.ok) {
133
+ await discardBody(res);
124
134
  throw new Error(`Resend attachment download failed (${res.status})`);
125
135
  }
126
- const content = await readCapped(res, limit);
136
+ let content;
137
+ try {
138
+ content = await readCapped(res, limit);
139
+ }
140
+ catch {
141
+ throw new Error("Resend attachment download failed");
142
+ }
127
143
  if (!content)
128
144
  return null;
129
145
  const source = { ...detail, ...meta };