@sayedhfatimi/convex-email 0.1.1 → 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 +290 -44
  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
@@ -33,7 +33,7 @@ import {
33
33
  query,
34
34
  } from "./_generated/server.js";
35
35
  import { getConfig } from "./config.js";
36
- import { fetchCredentials, redact, secretStrings } from "./credentials.js";
36
+ import { cleanError, fetchCredentials, secretStrings } from "./credentials.js";
37
37
  import { vInboundProvider, vInboundState } from "./schema.js";
38
38
 
39
39
  /** Its own lane: a slow or failing app handler never delays a send. */
@@ -517,7 +517,7 @@ export const process = internalAction({
517
517
  // Already gone.
518
518
  }
519
519
  }
520
- const failure = truncate(redact(errorText(e), secrets), MAX_FAILURE);
520
+ const failure = truncate(cleanError(errorText(e), secrets), MAX_FAILURE);
521
521
  // A provider fetch may fail for a moment only: try again on a schedule.
522
522
  await ctx.runMutation(
523
523
  fetching ? internal.inbound.fetchFailed : internal.inbound.fail,
@@ -567,7 +567,7 @@ export const processed = internalMutation({
567
567
  if (row?.state !== "received") return null;
568
568
  const failure =
569
569
  result.kind === "failed"
570
- ? truncate(result.error, MAX_FAILURE)
570
+ ? truncate(cleanError(result.error, []), MAX_FAILURE)
571
571
  : "processing was canceled";
572
572
  await ctx.db.patch(context.inboundId, { state: "failed", failure });
573
573
  return null;
@@ -90,9 +90,12 @@ export default defineSchema({
90
90
  idempotencyKey: v.optional(v.string()),
91
91
  error: v.optional(v.string()),
92
92
  /**
93
- * Outbound only: an attempt ended with no definite provider answer (a
94
- * network error, a timeout), so the provider may have the message.
95
- * `retrySend` then needs `force`. Never cleared.
93
+ * Outbound only: set when a send may have reached the provider without a
94
+ * recorded acceptance (an exception, a provider 5xx, or RECORD_FAILED).
95
+ * `retrySend` then needs `force`; it is cleared when `retrySend` requeues
96
+ * the message, and when a late recorded acceptance upgrades a `failed`
97
+ * message that had no `providerId` (`recordSent`). It can stay set on a message that later reached `sent`
98
+ * after an earlier ambiguous attempt, meaning a duplicate may exist.
96
99
  */
97
100
  deliveryAmbiguous: v.optional(v.literal(true)),
98
101
  /** Recipients dropped by suppression or an unsubscribe, normalised. */
@@ -169,13 +172,26 @@ export default defineSchema({
169
172
  detail: v.optional(v.string()),
170
173
  /** True when no message of ours carries `providerId`. */
171
174
  orphan: v.boolean(),
175
+ /**
176
+ * Orphans only: what the event named, kept so it can be applied when a
177
+ * message records `providerId` later. Cleared once it is.
178
+ */
179
+ recipients: v.optional(v.array(v.string())),
180
+ rfcMessageId: v.optional(v.string()),
172
181
  })
173
182
  .index("by_tenant_provider_eventId", [
174
183
  "tenant",
175
184
  "provider",
176
185
  "providerEventId",
177
186
  ])
178
- .index("by_message", ["messageId"]),
187
+ .index("by_message", ["messageId"])
188
+ .index("by_provider_providerId_orphan", [
189
+ "provider",
190
+ "providerId",
191
+ "orphan",
192
+ ])
193
+ /** `cleanup`'s purge: orphans by age (the implicit `_creationTime`). */
194
+ .index("by_orphan", ["orphan"]),
179
195
 
180
196
  /** Inbound mail, one row per provider notification (or raw hand-in). */
181
197
  inbound: defineTable({
@@ -198,6 +214,8 @@ export default defineSchema({
198
214
  purgedAt: v.optional(v.number()),
199
215
  })
200
216
  .index("by_state_purged", ["state", "purgedAt"])
217
+ /** `cleanup`'s purge: rows in a state by age (the implicit `_creationTime`). */
218
+ .index("by_state", ["state"])
201
219
  .index("by_tenant_provider_providerId", [
202
220
  "tenant",
203
221
  "provider",
@@ -13,7 +13,7 @@ import {
13
13
  } from "../shared/validators.js";
14
14
  import type { Doc, Id } from "./_generated/dataModel.js";
15
15
  import { type MutationCtx, mutation } from "./_generated/server.js";
16
- import { upsertConfig } from "./config.js";
16
+ import { getConfig, upsertConfig } from "./config.js";
17
17
  import { enqueueDelivery } from "./deliver.js";
18
18
  import { isSuppressed, isUnsubscribed } from "./suppression.js";
19
19
 
@@ -81,9 +81,12 @@ function noControl(label: string, value: string, allowTab = false) {
81
81
  }
82
82
  }
83
83
 
84
- /** One `@` with a non-empty local part and domain, no control or whitespace. */
84
+ /**
85
+ * One `@` with a non-empty local part and domain; no control character,
86
+ * whitespace, `<`, `>`, `,`, `"` or `;`.
87
+ */
85
88
  function validAddress(a: string): boolean {
86
- if (hasControl(a) || /[\s<>,]/.test(a)) return false;
89
+ if (hasControl(a) || /[\s<>,";]/.test(a)) return false;
87
90
  const at = a.indexOf("@");
88
91
  return at > 0 && at === a.lastIndexOf("@") && at < a.length - 1;
89
92
  }
@@ -335,11 +338,8 @@ export const enqueue = mutation({
335
338
  // Every To dropped: the rest are not sent a message with no To.
336
339
  if (remaining.length === 0 || (toList.length > 0 && to.length === 0)) {
337
340
  status = "suppressed";
338
- } else if (config.testMode) {
339
- const allow = new Set(config.testAllowlist.map(normalizeAddress));
340
- status = remaining.every((a) => allow.has(a)) ? "queued" : "test";
341
341
  } else {
342
- status = "queued";
342
+ status = blockedByTestMode(config, remaining) ? "test" : "queued";
343
343
  }
344
344
 
345
345
  const now = Date.now();
@@ -388,6 +388,19 @@ export const enqueue = mutation({
388
388
  },
389
389
  });
390
390
 
391
+ /**
392
+ * Test mode: true when it is on and any recipient is outside the allowlist,
393
+ * so nothing may leave. No config means test mode was never set: not blocked.
394
+ */
395
+ function blockedByTestMode(
396
+ config: { testMode: boolean; testAllowlist: string[] } | null,
397
+ recipients: string[],
398
+ ): boolean {
399
+ if (!config?.testMode) return false;
400
+ const allow = new Set(config.testAllowlist.map(normalizeAddress));
401
+ return !recipients.every((a) => allow.has(normalizeAddress(a)));
402
+ }
403
+
391
404
  /**
392
405
  * Queue a `failed` outbound message again, on its own stream's pool. Any
393
406
  * other status is refused, and so is a failure the provider reported after
@@ -396,12 +409,18 @@ export const enqueue = mutation({
396
409
  * may already have arrived, so it is refused unless `force` is set. The
397
410
  * suppression and unsubscribe checks run again, as at enqueue: recipients
398
411
  * suppressed or unsubscribed since move to `suppressedRecipients`, and a
399
- * message left with no To is `suppressed` rather than queued. Returns the
400
- * resulting status.
412
+ * message left with no To is `suppressed` rather than queued. Test mode
413
+ * applies again from the stored config, as on a first send: a message with a
414
+ * recipient outside the allowlist becomes `test` and nothing is sent. A retry
415
+ * that queues clears `deliveryAmbiguous`. Returns the resulting status.
401
416
  */
402
417
  export const retry = mutation({
403
418
  args: { messageId: v.id("messages"), force: v.optional(v.boolean()) },
404
- returns: v.union(v.literal("queued"), v.literal("suppressed")),
419
+ returns: v.union(
420
+ v.literal("queued"),
421
+ v.literal("suppressed"),
422
+ v.literal("test"),
423
+ ),
405
424
  handler: async (ctx, { messageId, force }) => {
406
425
  const message = await ctx.db.get(messageId);
407
426
  if (!message) throw new Error("no such message");
@@ -445,11 +464,20 @@ export const retry = mutation({
445
464
  ...dropped,
446
465
  ]);
447
466
  // Same rule as enqueue: no To left means the rest are not sent.
448
- const status =
467
+ let status: "queued" | "suppressed" | "test";
468
+ if (
449
469
  (message.to.length > 0 && to.length === 0) ||
450
470
  to.length + cc.length + bcc.length === 0
451
- ? "suppressed"
471
+ ) {
472
+ status = "suppressed";
473
+ } else {
474
+ status = blockedByTestMode(
475
+ await getConfig(ctx),
476
+ unique([...to, ...cc, ...bcc]),
477
+ )
478
+ ? "test"
452
479
  : "queued";
480
+ }
453
481
  await ctx.db.patch(messageId, {
454
482
  status,
455
483
  to,
@@ -457,6 +485,7 @@ export const retry = mutation({
457
485
  bcc,
458
486
  suppressedRecipients,
459
487
  error: undefined,
488
+ ...(status === "queued" ? { deliveryAmbiguous: undefined } : {}),
460
489
  updatedAt: Date.now(),
461
490
  });
462
491
  if (status === "queued") {
@@ -81,7 +81,6 @@ export const handle = action({
81
81
  category: v.optional(v.string()),
82
82
  }),
83
83
  handler: async (ctx, { config, method, token }): Promise<Result> => {
84
- await ctx.runMutation(internal.config.upsert, { config });
85
84
  const claimed = peekUnsubTenant(token);
86
85
  if (claimed === null) return FAILED;
87
86
  let secret: string;
@@ -101,6 +100,8 @@ export const handle = action({
101
100
  }
102
101
  const payload = await verifyUnsubToken(secret, token);
103
102
  if (!payload) return FAILED;
103
+ // Stored only once the token verifies, never for a forged request.
104
+ await ctx.runMutation(internal.config.upsert, { config });
104
105
  const address = normalizeAddress(payload.address);
105
106
  if (method === "POST") {
106
107
  await ctx.runMutation(internal.unsubscribe.record, {
@@ -24,8 +24,6 @@ export const ingest = action({
24
24
  },
25
25
  returns: v.object({ status: v.number(), body: v.string() }),
26
26
  handler: async (ctx, { config, provider, request }): Promise<Reply> => {
27
- await ctx.runMutation(internal.config.upsert, { config });
28
-
29
27
  // The route's tenant, else the app's default (config, not payload).
30
28
  const tenant = request.tenant ?? config.defaultTenant;
31
29
 
@@ -65,6 +63,10 @@ export const ingest = action({
65
63
  return PARSE_ERROR;
66
64
  }
67
65
 
66
+ // Stored only now: a request that failed verification or parsing never
67
+ // writes the caller-supplied config.
68
+ await ctx.runMutation(internal.config.upsert, { config });
69
+
68
70
  if (parsed.events.length > 0) {
69
71
  await ctx.runMutation(internal.events.apply, {
70
72
  provider,
@@ -37,3 +37,12 @@ export async function readCapped(
37
37
  }
38
38
  return out.buffer;
39
39
  }
40
+
41
+ /** Cancels an unread body so the connection is released; never throws. */
42
+ export async function discardBody(res: Response): Promise<void> {
43
+ try {
44
+ await res.body?.cancel();
45
+ } catch {
46
+ // Nothing to release.
47
+ }
48
+ }