@pithy-sh/email 0.8.1 → 0.9.0

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 (44) hide show
  1. package/README.md +2 -0
  2. package/dist/bounce/handler.d.ts +22 -2
  3. package/dist/bounce/handler.d.ts.map +1 -1
  4. package/dist/bounce/handler.js +60 -17
  5. package/dist/capability.d.ts +12 -0
  6. package/dist/capability.d.ts.map +1 -1
  7. package/dist/capability.js +25 -15
  8. package/dist/http/routes.d.ts.map +1 -1
  9. package/dist/http/routes.js +7 -1
  10. package/dist/http/schemas.d.ts +9 -0
  11. package/dist/http/schemas.d.ts.map +1 -1
  12. package/dist/http/schemas.js +5 -2
  13. package/dist/jobs/read.d.ts +12 -9
  14. package/dist/jobs/read.d.ts.map +1 -1
  15. package/dist/jobs/read.js +6 -5
  16. package/dist/migrations/0002_job_filters.d.ts +15 -0
  17. package/dist/migrations/0002_job_filters.d.ts.map +1 -0
  18. package/dist/migrations/0002_job_filters.js +25 -0
  19. package/dist/send/enqueue.d.ts +26 -3
  20. package/dist/send/enqueue.d.ts.map +1 -1
  21. package/dist/send/enqueue.js +25 -2
  22. package/dist/send/errorMapping.d.ts +15 -20
  23. package/dist/send/errorMapping.d.ts.map +1 -1
  24. package/dist/send/errorMapping.js +33 -27
  25. package/dist/send/runSend.d.ts +2 -2
  26. package/dist/send/runSend.d.ts.map +1 -1
  27. package/dist/send/runSend.js +1 -1
  28. package/dist/send/suppression.d.ts +4 -0
  29. package/dist/send/suppression.d.ts.map +1 -1
  30. package/dist/send/suppression.js +4 -0
  31. package/dist/version.generated.d.ts +1 -1
  32. package/dist/version.generated.js +1 -1
  33. package/package.json +3 -3
  34. package/src/bounce/handler.ts +84 -32
  35. package/src/capability.ts +47 -27
  36. package/src/http/routes.ts +4 -1
  37. package/src/http/schemas.ts +21 -2
  38. package/src/jobs/read.ts +14 -9
  39. package/src/migrations/0002_job_filters.ts +35 -0
  40. package/src/send/enqueue.ts +52 -5
  41. package/src/send/errorMapping.ts +45 -38
  42. package/src/send/runSend.ts +6 -7
  43. package/src/send/suppression.ts +13 -0
  44. package/src/version.generated.ts +1 -1
@@ -35,9 +35,32 @@ function resolveSchedule(input, now) {
35
35
  status: "scheduled"
36
36
  };
37
37
  }
38
+ /**
39
+ * The sender this job is stored with: the capability's identity, or a per-message one the composing capability
40
+ * claims. An unclaimed override is refused before anything is written.
41
+ */
42
+ function resolveSender(deps, input) {
43
+ if (input.from === void 0) return {
44
+ fromAddress: deps.fromAddress,
45
+ fromName: deps.fromName
46
+ };
47
+ const address = normalizeAddress(input.from.address);
48
+ const claimed = (deps.claimedFrom ?? []).map(normalizeAddress);
49
+ if (!claimed.includes(address)) throw new EmailInvalidPayloadError({
50
+ message: "This message cannot be sent from that address.",
51
+ action: claimed.length === 0 ? "Send without `from`, or send through the `enqueueAs` seam of the capability that claims the address." : `Send from one of the claimed addresses: ${claimed.join(", ")}.`,
52
+ detail: `from ${address} is not among the ${claimed.length} address(es) the composing capability claims`
53
+ });
54
+ const name = input.from.name?.trim();
55
+ return {
56
+ fromAddress: address,
57
+ fromName: name ? name : deps.fromName
58
+ };
59
+ }
38
60
  /** Enqueue an email job, dispatching the send Workflow immediately when the mode is `immediate`. */
39
61
  async function enqueueEmail(deps, input) {
40
62
  const template = getTemplate(input.template);
63
+ const from = resolveSender(deps, input);
41
64
  const translator = emailTranslator(input.locale, deps.layersFor ?? kitEmailLayers);
42
65
  const subject = renderSubject(input.template, input.payload, deps.theme, translator);
43
66
  const { mode, sendAt, status: scheduled } = resolveSchedule(input, deps.now);
@@ -117,8 +140,8 @@ async function enqueueEmail(deps, input) {
117
140
  id: deps.newId(),
118
141
  toAddress: personalAddress(input.to),
119
142
  recipientKey: personalAddress(recipient),
120
- fromAddress: deps.fromAddress,
121
- fromName: deps.fromName,
143
+ fromAddress: from.fromAddress,
144
+ fromName: from.fromName,
122
145
  subject,
123
146
  template: input.template,
124
147
  category: template.category,
@@ -13,18 +13,12 @@ export interface ClassifiedSendError {
13
13
  /** The `E_*` code reported by the binding, a numeric provider code as a string, or `E_UNKNOWN` for none. */
14
14
  code: string;
15
15
  /**
16
- * The cause, as one operator-facing line: the code and whatever the provider said with it.
16
+ * The cause, as one operator-facing line: the code, whatever the provider said with it, and the sending domain
17
+ * when the code says that domain cannot send.
17
18
  *
18
- * **Exposed because the job row needs it and only the error object had it (pithy-sh/pithy#555).**
19
- * `runSend` persisted the bare `code` into `pithy_email_jobs.error`, so a magic link that failed five
20
- * times against a token for the wrong account recorded `E_UNKNOWN` five times and nothing about why —
21
- * while this exact string, naming `10000 Authentication error`, was being built two lines down and
22
- * thrown away with the error it decorated. Same family as #534: a failure that discards the cause it
23
- * was handed.
24
- *
25
- * Identical to `error.payload.detail`, deliberately — one composition, two readers, so the row and the
26
- * log cannot drift. `detail` is stripped at the client boundary, which is where a provider's own words
27
- * belong.
19
+ * `runSend` writes it to `pithy_email_jobs.error`, so the row names the cause rather than the bare code.
20
+ * Identical to `error.payload.detail`: one composition, two readers, so the row and the log cannot drift.
21
+ * `detail` is stripped at the client boundary, which is where a provider's own words belong.
28
22
  */
29
23
  detail: string;
30
24
  /** Whether the send should be retried with backoff. */
@@ -39,15 +33,16 @@ export interface ClassifiedSendError {
39
33
  * suppressed locally too; rate/quota and transient delivery codes are retryable; everything else
40
34
  * (validation, sender, content, headers) is terminal.
41
35
  *
42
- * **An unrecognized code is retryable, and that is deliberately unchanged.** A failure this module has
43
- * no code at all keeps its bounded retry, and so does a *numeric* provider code nobody here has listed —
44
- * see {@link isProviderNumericCode} for why those two are alike and an unlisted `E_*` is not.
36
+ * **An unrecognized code is retryable**: a failure with no code at all keeps its bounded retry, and so does
37
+ * a *numeric* provider code nobody here has listed — see {@link isProviderNumericCode} for why those two are
38
+ * alike and an unlisted `E_*` is not. The **authentication** class is named and terminal: `10000
39
+ * Authentication error` is a token that cannot send as this domain, and no retry changes that — see
40
+ * {@link UNAUTHORIZED} for why that is a list rather than "numeric means permanent".
45
41
  *
46
- * What changed for #555 is that the **authentication** class is now named and terminal: `10000
47
- * Authentication error` is a token that cannot send as this domain, and spending five attempts on it in
48
- * silence is what hid the whole incident. See {@link UNAUTHORIZED} for why that is a list rather than
49
- * "numeric means permanent" — the latter was this fix's first shape, and it made a momentary numeric
50
- * failure permanent as a side effect.
42
+ * `context.fromAddress` is the job's sender. When the code says its domain cannot send, the detail names the
43
+ * domain, so the operator knows which one to onboard.
51
44
  */
52
- export declare function classifySendError(err: unknown): ClassifiedSendError;
45
+ export declare function classifySendError(err: unknown, context?: {
46
+ fromAddress?: string;
47
+ }): ClassifiedSendError;
53
48
  //# sourceMappingURL=errorMapping.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"errorMapping.d.ts","sourceRoot":"","sources":["../../src/send/errorMapping.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,qCAAqC,CAAC;AAGtE;;;;;;GAMG;AAEH,4GAA4G;AAC5G,MAAM,WAAW,mBAAmB;IAClC,4GAA4G;IAC5G,IAAI,EAAE,MAAM,CAAC;IACb;;;;;;;;;;;;;OAaG;IACH,MAAM,EAAE,MAAM,CAAC;IACf,uDAAuD;IACvD,SAAS,EAAE,OAAO,CAAC;IACnB,2GAA2G;IAC3G,UAAU,EAAE,OAAO,CAAC;IACpB,qFAAqF;IACrF,KAAK,EAAE,UAAU,CAAC;CACnB;AAsED;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,iBAAiB,CAAC,GAAG,EAAE,OAAO,GAAG,mBAAmB,CA6BnE"}
1
+ {"version":3,"file":"errorMapping.d.ts","sourceRoot":"","sources":["../../src/send/errorMapping.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,qCAAqC,CAAC;AAGtE;;;;;;GAMG;AAEH,4GAA4G;AAC5G,MAAM,WAAW,mBAAmB;IAClC,4GAA4G;IAC5G,IAAI,EAAE,MAAM,CAAC;IACb;;;;;;;OAOG;IACH,MAAM,EAAE,MAAM,CAAC;IACf,uDAAuD;IACvD,SAAS,EAAE,OAAO,CAAC;IACnB,2GAA2G;IAC3G,UAAU,EAAE,OAAO,CAAC;IACpB,qFAAqF;IACrF,KAAK,EAAE,UAAU,CAAC;CACnB;AAiFD;;;;;;;;;;;;;GAaG;AACH,wBAAgB,iBAAiB,CAAC,GAAG,EAAE,OAAO,EAAE,OAAO,GAAE;IAAE,WAAW,CAAC,EAAE,MAAM,CAAA;CAAO,GAAG,mBAAmB,CAgC3G"}
@@ -16,15 +16,12 @@ const RATE_LIMITED = /* @__PURE__ */ new Set(["E_RATE_LIMIT_EXCEEDED", "E_DAILY_
16
16
  *
17
17
  * `10000` is Cloudflare's own: a token that is alive but not scoped for Email Sending, or scoped for an
18
18
  * account that does not own the sending domain, is answered `{ code: 10000, message: "Authentication
19
- * error" }` (#534 captured the body; `liveSend.integration.test.ts` documents the same rejection for a
20
- * general account token). That is the exact failure #555 spent five attempts on in silence.
19
+ * error" }` (`liveSend.integration.test.ts` documents the same rejection for a general account token).
21
20
  *
22
- * **Named rather than inferred from the code being numeric.** Treating every numeric code as terminal was
23
- * the first shape of this fix and it bought the auth case by making a *momentary* numeric failure
24
- * permanent too — one attempt, `status: "failed"`, where the retry budget used to apply. A code nobody
25
- * here recognizes is still unknown, whichever alphabet it is written in, and unknown has earned its
26
- * bounded retry since the module was written. So the auth class is listed, and the rule below is
27
- * unchanged for everything else.
21
+ * **Listed rather than inferred from the code being numeric.** Treating every numeric code as terminal would
22
+ * make a momentary numeric failure permanent too — one attempt, `status: "failed"`, where the retry budget
23
+ * applies. A code nobody here recognizes is still unknown, whichever alphabet it is written in, and unknown
24
+ * keeps its bounded retry.
28
25
  */
29
26
  const UNAUTHORIZED = /* @__PURE__ */ new Set([
30
27
  "10000",
@@ -32,6 +29,17 @@ const UNAUTHORIZED = /* @__PURE__ */ new Set([
32
29
  "E_FORBIDDEN"
33
30
  ]);
34
31
  /**
32
+ * Codes that mean **the sender's domain cannot send**: not onboarded onto Email Service, or not verified.
33
+ * Terminal like every unlisted `E_*`, and named so the job's error says which domain to onboard.
34
+ */
35
+ const SENDER_DOMAIN = /* @__PURE__ */ new Set(["E_SENDER_DOMAIN_NOT_AVAILABLE", "E_SENDER_NOT_VERIFIED"]);
36
+ /** The domain half of an address, lowercased, or `null` when it carries none. */
37
+ function domainOf(address) {
38
+ const at = address.lastIndexOf("@");
39
+ if (at < 0 || at === address.length - 1) return null;
40
+ return address.slice(at + 1).trim().toLowerCase();
41
+ }
42
+ /**
35
43
  * Whether a code is one of Cloudflare's numeric ones rather than the binding's `E_*` spelling.
36
44
  *
37
45
  * The distinction decides the retry, so it is a predicate rather than a guess at the call site. An `E_*`
@@ -46,16 +54,14 @@ function isProviderNumericCode(code) {
46
54
  /**
47
55
  * Read a thrown value's `.code`/`.message` without assuming its shape.
48
56
  *
49
- * **A numeric code counts, and that is not a detail.** The Email Service binding surfaces `E_*` strings,
50
- * but the REST path and the account layer behind it answer with Cloudflare's own numeric codes — an
51
- * unauthorized send is `{ code: 10000, message: "Authentication error" }` (#534 captured the body). Read
52
- * as "no code" that became `E_UNKNOWN`, which is both silent *and* retryable, so a credential fault
53
- * consumed every attempt without ever naming itself (#555).
57
+ * **A numeric code counts.** The Email Service binding surfaces `E_*` strings, but the REST path and the
58
+ * account layer behind it answer with Cloudflare's own numeric codes — an unauthorized send is
59
+ * `{ code: 10000, message: "Authentication error" }`. Read as "no code" that would be `E_UNKNOWN`, which is
60
+ * both silent *and* retryable, so a credential fault would consume every attempt without naming itself.
54
61
  *
55
- * **And a value with neither field still leaves a trace.** `String(err)` rather than `""`: an opaque
56
- * throw is the case where the operator has least to go on, so an empty string is the one answer that
57
- * cannot help. `E_UNKNOWN` remains the code — it means *nothing named itself*, which is the fact that
58
- * earns the bounded retry.
62
+ * **A value with neither field still leaves a trace.** `String(err)` rather than `""`: an opaque throw is
63
+ * the case where the operator has least to go on. `E_UNKNOWN` remains the code — it means *nothing named
64
+ * itself*, which is the fact that earns the bounded retry.
59
65
  */
60
66
  function readError(err) {
61
67
  if (err && typeof err === "object") {
@@ -77,19 +83,19 @@ function readError(err) {
77
83
  * suppressed locally too; rate/quota and transient delivery codes are retryable; everything else
78
84
  * (validation, sender, content, headers) is terminal.
79
85
  *
80
- * **An unrecognized code is retryable, and that is deliberately unchanged.** A failure this module has
81
- * no code at all keeps its bounded retry, and so does a *numeric* provider code nobody here has listed —
82
- * see {@link isProviderNumericCode} for why those two are alike and an unlisted `E_*` is not.
86
+ * **An unrecognized code is retryable**: a failure with no code at all keeps its bounded retry, and so does
87
+ * a *numeric* provider code nobody here has listed — see {@link isProviderNumericCode} for why those two are
88
+ * alike and an unlisted `E_*` is not. The **authentication** class is named and terminal: `10000
89
+ * Authentication error` is a token that cannot send as this domain, and no retry changes that — see
90
+ * {@link UNAUTHORIZED} for why that is a list rather than "numeric means permanent".
83
91
  *
84
- * What changed for #555 is that the **authentication** class is now named and terminal: `10000
85
- * Authentication error` is a token that cannot send as this domain, and spending five attempts on it in
86
- * silence is what hid the whole incident. See {@link UNAUTHORIZED} for why that is a list rather than
87
- * "numeric means permanent" — the latter was this fix's first shape, and it made a momentary numeric
88
- * failure permanent as a side effect.
92
+ * `context.fromAddress` is the job's sender. When the code says its domain cannot send, the detail names the
93
+ * domain, so the operator knows which one to onboard.
89
94
  */
90
- function classifySendError(err) {
95
+ function classifySendError(err, context = {}) {
91
96
  const { code, message } = readError(err);
92
- const detail = `email send failed: ${code}${message ? ` — ${message}` : ""}`;
97
+ const domain = SENDER_DOMAIN.has(code) && context.fromAddress ? domainOf(context.fromAddress) : null;
98
+ const detail = `email send failed: ${code}${message ? ` — ${message}` : ""}${domain ? ` (${domain} is not set up for sending on Email Service)` : ""}`;
93
99
  if (code === "E_RECIPIENT_SUPPRESSED") return {
94
100
  code,
95
101
  detail,
@@ -59,11 +59,11 @@ export interface SendDeps {
59
59
  /** This worker's environment name, stamped on each send (X-Pithy-Env) so the single inbound worker can route. */
60
60
  environment?: string;
61
61
  /**
62
- * When this pass began — **stable across a Workflow resume** (pithy-sh/pithy#327).
62
+ * When this pass began — **stable across a Workflow resume**.
63
63
  *
64
64
  * Everything that dates the work reads this: `sentAt`, the redaction stamp, the events, and how long a
65
65
  * tracked link stays valid. A driver body re-executes from the top on a resume, so a clock read there
66
- * answers with the resume — and a batch that backed off overnight dated its remaining jobs, and the
66
+ * answers with the resume — a batch that backed off overnight would date its remaining jobs, and the
67
67
  * expiry of every link in them, a day late. `runSendBatch` journals this in a step so a resume reads
68
68
  * back the instant the batch began.
69
69
  *
@@ -1 +1 @@
1
- {"version":3,"file":"runSend.d.ts","sourceRoot":"","sources":["../../src/send/runSend.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,EAAE,cAAc,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AACvE,OAAO,KAAK,EAAE,aAAa,EAAE,wBAAwB,EAAe,MAAM,gBAAgB,CAAC;AAE3F,OAAO,EAAE,KAAK,kBAAkB,EAAmC,MAAM,uBAAuB,CAAC;AACjG,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAGrD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;AAG5C;;;;;;;;;;;;;;;;;;GAkBG;AAEH,kGAAkG;AAClG,MAAM,WAAW,WAAW;IAC1B,qCAAqC;IACrC,GAAG,EAAE,MAAM,CAAC;IACZ,oEAAoE;IACpE,GAAG,EAAE,MAAM,CAAC;CACb;AAED,yDAAyD;AACzD,MAAM,WAAW,QAAQ;IACvB,gDAAgD;IAChD,EAAE,EAAE,aAAa,CAAC;IAClB,sGAAsG;IACtG,aAAa,EAAE,wBAAwB,CAAC;IACxC,MAAM,EAAE,WAAW,CAAC;IACpB,KAAK,EAAE,UAAU,CAAC;IAClB;;;;;;;OAOG;IACH,SAAS,CAAC,EAAE,kBAAkB,CAAC;IAC/B,8CAA8C;IAC9C,OAAO,EAAE,MAAM,CAAC;IAChB,6GAA6G;IAC7G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IACvB,gDAAgD;IAChD,EAAE,EAAE,aAAa,CAAC;IAClB,sGAAsG;IACtG,aAAa,EAAE,wBAAwB,CAAC;IACxC,MAAM,EAAE,WAAW,CAAC;IACpB,KAAK,EAAE,UAAU,CAAC;IAClB;;;;;;;OAOG;IACH,SAAS,CAAC,EAAE,kBAAkB,CAAC;IAC/B,8CAA8C;IAC9C,OAAO,EAAE,MAAM,CAAC;IAChB,6GAA6G;IAC7G,OAAO,CAAC,EAAE,WAAW,CAAC;IACtB,2CAA2C;IAC3C,WAAW,EAAE,MAAM,CAAC;IACpB,qEAAqE;IACrE,WAAW,EAAE,MAAM,CAAC;IACpB,iHAAiH;IACjH,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB;;;;;;;;;;;;OAYG;IACH,aAAa,EAAE,IAAI,CAAC;IACpB;;;;;;;;;;;;;OAaG;IACH,WAAW,EAAE,MAAM,IAAI,CAAC;CACzB;AAED,qCAAqC;AACrC,MAAM,WAAW,WAAW;IAC1B,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,cAAc,CAAC;IACvB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB;;;;;;;OAOG;IACH,iBAAiB,CAAC,EAAE,iBAAiB,CAAC;CACvC;AAuBD,wBAAsB,OAAO,CAAC,IAAI,EAAE,QAAQ,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,WAAW,CAAC,CAmLjF"}
@@ -170,7 +170,7 @@ async function runSend(deps, jobId) {
170
170
  messageId: result.messageId
171
171
  };
172
172
  } catch (err) {
173
- const classified = classifySendError(err);
173
+ const classified = classifySendError(err, { fromAddress: job.fromAddress });
174
174
  if (classified.suppressed) {
175
175
  await patchJob(deps, jobId, {
176
176
  status: "suppressed",
@@ -72,6 +72,10 @@ export interface SuppressionListFilter {
72
72
  reason?: SuppressionReason;
73
73
  /** Look one address up exactly, rather than paging the list. */
74
74
  email?: string;
75
+ /** The blocks in force at `now` (`true`), or the ones whose expiry has passed (`false`). Every row when absent. */
76
+ active?: boolean;
77
+ /** The instant `active` is judged at. Defaults to the moment of the read. */
78
+ now?: Date;
75
79
  /** The previous page's `nextCursor`. A malformed one is a first page. */
76
80
  cursor?: string;
77
81
  /** How many rows to return, clamped into range. */
@@ -1 +1 @@
1
- {"version":3,"file":"suppression.d.ts","sourceRoot":"","sources":["../../src/send/suppression.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAC5D,OAAO,EAAE,KAAK,SAAS,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAClE,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,gBAAgB,CAAC;AAE/D;;;;;;;;;;;;;;;;;;;GAmBG;AAEH;;;;;;;;;;;;;GAaG;AACH,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,iBAAiB,EAAE,IAAI,EAAE,SAAS,GAAG,OAAO,CAGrF;AAED;;;;;GAKG;AACH,wBAAsB,mBAAmB,CACvC,EAAE,EAAE,wBAAwB,EAC5B,KAAK,EAAE,MAAM,EACb,GAAG,EAAE,IAAI,EACT,IAAI,EAAE,SAAS,GACd,OAAO,CAAC,iBAAiB,GAAG,IAAI,CAAC,CAkBnC;AAED,8FAA8F;AAC9F,wBAAsB,QAAQ,CAC5B,EAAE,EAAE,wBAAwB,EAC5B,KAAK,EAAE;IACL,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,iBAAiB,CAAC;IAC1B,KAAK,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACtB,WAAW,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC5B,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACvB,SAAS,CAAC,EAAE,IAAI,GAAG,IAAI,CAAC;CACzB,EACD,GAAG,EAAE,IAAI,GACR,OAAO,CAAC,IAAI,CAAC,CAWf;AAED;;;;;;;;;;GAUG;AACH,wBAAsB,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From("pithyEmailSuppressions").selectAll().orderBy("createdAt", "desc").orderBy("id", "desc").limit(limit + 1);
124
124
  if (filter.reason) query = query.where("reason", "=", filter.reason);
125
125
  if (filter.email) query = query.where("email", "=", normalizeAddress(filter.email));
126
+ if (filter.active !== void 0) {
127
+ const at = SQLiteDate.encode(filter.now ?? /* @__PURE__ */ new Date());
128
+ query = query.where((eb) => filter.active ? eb.or([eb("expiresAt", "is", null), eb("expiresAt", ">", at)]) : eb.and([eb("expiresAt", "is not", null), eb("expiresAt", "<=", at)]));
129
+ }
126
130
  if (after) query = query.where((eb) => eb.or([eb("createdAt", "<", after.sort), eb.and([eb("createdAt", "=", after.sort), eb("id", "<", after.id)])]));
127
131
  const items = (await query.execute()).map((row) => EmailSuppression.parse(row));
128
132
  return toPage(items, limit, (row) => ({
@@ -3,5 +3,5 @@
3
3
  /** This package's npm name — the join key against a release feed. */
4
4
  export declare const PACKAGE_NAME = "@pithy-sh/email";
5
5
  /** This package's version, stamped from its own package.json at generation time. */
6
- export declare const PACKAGE_VERSION = "0.8.1";
6
+ export declare const PACKAGE_VERSION = "0.9.0";
7
7
  //# sourceMappingURL=version.generated.d.ts.map
@@ -4,6 +4,6 @@
4
4
  /** This package's npm name — the join key against a release feed. */
5
5
  const PACKAGE_NAME = "@pithy-sh/email";
6
6
  /** This package's version, stamped from its own package.json at generation time. */
7
- const PACKAGE_VERSION = "0.8.1";
7
+ const PACKAGE_VERSION = "0.9.0";
8
8
  //#endregion
9
9
  export { PACKAGE_NAME, PACKAGE_VERSION };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pithy-sh/email",
3
- "version": "0.8.1",
3
+ "version": "0.9.0",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -42,8 +42,8 @@
42
42
  "postal-mime": "^3.0.0"
43
43
  },
44
44
  "peerDependencies": {
45
- "@pithy-sh/core": "^0.15.0",
46
- "@pithy-sh/secrets": "^0.6.3",
45
+ "@pithy-sh/core": "^0.17.0",
46
+ "@pithy-sh/secrets": "^0.6.5",
47
47
  "hono": "^4.13.2",
48
48
  "kysely": "^0.29.0",
49
49
  "zod": "^4.4.0"
@@ -5,6 +5,7 @@ import type { D1Database } from "@cloudflare/workers-types";
5
5
  import { normalizeAddress } from "@pithy-sh/core/src/address/address";
6
6
  import type { CapabilityEmailHandler } from "@pithy-sh/core/src/capability/capability";
7
7
  import { SQLiteDate } from "@pithy-sh/core/src/data/codecs";
8
+ import { createWorkerLogger } from "@pithy-sh/core/src/logger/worker";
8
9
  import PostalMime from "postal-mime";
9
10
  import {
10
11
  type EmailDatabase,
@@ -34,6 +35,16 @@ export interface InboundOutcome {
34
35
  jobId?: string;
35
36
  /** Whether the address was added to the suppression list. */
36
37
  suppressed: boolean;
38
+ /** Each part left undone because the database it writes to was not given, in the order they were reached. */
39
+ skipped: InboundSkip[];
40
+ }
41
+
42
+ /** One part of applying a classification that did not run, and the binding it needed. */
43
+ export interface InboundSkip {
44
+ /** `job` is the job lookup, its bounce marking and its event; `suppression` is the suppression-list write. */
45
+ part: "job" | "suppression";
46
+ /** The Worker binding that part writes through. */
47
+ binding: "DB" | "EMAIL_SUPPRESSIONS";
37
48
  }
38
49
 
39
50
  /**
@@ -42,30 +53,40 @@ export interface InboundOutcome {
42
53
  * database. Pure of any MIME parsing — unit-testable. Note the single inbound worker only reaches its
43
54
  * own app DB, so a job-row update is best-effort (the originating job may live in another environment),
44
55
  * whereas the suppression — the safety-critical part — is always global.
56
+ *
57
+ * Each part runs on the database it needs and no other: a missing app database skips the job, a missing
58
+ * suppression database skips the suppression, and each skip is reported in `skipped` rather than thrown.
45
59
  */
46
60
  export async function applyInbound(
47
- db: EmailDatabase,
48
- suppressionDb: EmailSuppressionDatabase,
61
+ db: EmailDatabase | undefined,
62
+ suppressionDb: EmailSuppressionDatabase | undefined,
49
63
  c: InboundClassification,
50
64
  now: Date,
51
65
  environment?: string,
52
66
  ): Promise<InboundOutcome> {
53
- if (c.type === "ignore" || c.type === "auto_reply") return { acted: false, type: c.type, suppressed: false };
67
+ if (c.type === "ignore" || c.type === "auto_reply") {
68
+ return { acted: false, type: c.type, suppressed: false, skipped: [] };
69
+ }
70
+ const skipped: InboundSkip[] = [];
71
+ if (db === undefined) skipped.push({ part: "job", binding: "DB" });
54
72
 
55
73
  // Match the originating job by the original Message-ID against the stored send messageId.
56
- const job = c.originalMessageId
57
- ? await db
58
- .selectFrom("pithyEmailJobs")
59
- .select(["id", "toAddress", "status", "campaignId"])
60
- .where("messageId", "=", c.originalMessageId)
61
- .executeTakeFirst()
62
- : undefined;
74
+ const job =
75
+ c.originalMessageId && db
76
+ ? await db
77
+ .selectFrom("pithyEmailJobs")
78
+ .select(["id", "toAddress", "status", "campaignId"])
79
+ .where("messageId", "=", c.originalMessageId)
80
+ .executeTakeFirst()
81
+ : undefined;
63
82
 
64
83
  const recipient = c.recipient ? normalizeAddress(c.recipient) : job ? normalizeAddress(job.toAddress) : undefined;
65
84
  const isSuppressing = c.type === "hard" || c.type === "complaint";
66
85
  let suppressed = false;
67
86
 
68
- if (recipient && isSuppressing) {
87
+ if (recipient && isSuppressing && suppressionDb === undefined) {
88
+ skipped.push({ part: "suppression", binding: "EMAIL_SUPPRESSIONS" });
89
+ } else if (recipient && isSuppressing && suppressionDb) {
69
90
  await suppress(
70
91
  suppressionDb,
71
92
  {
@@ -80,7 +101,7 @@ export async function applyInbound(
80
101
  suppressed = true;
81
102
  }
82
103
 
83
- if (job) {
104
+ if (job && db) {
84
105
  await db
85
106
  .updateTable("pithyEmailJobs")
86
107
  .set({
@@ -106,31 +127,62 @@ export async function applyInbound(
106
127
  );
107
128
  }
108
129
 
109
- return { acted: suppressed || Boolean(job), type: c.type, jobId: job?.id, suppressed };
130
+ return { acted: suppressed || Boolean(job), type: c.type, jobId: job?.id, suppressed, skipped };
110
131
  }
111
132
 
112
- /** Build the inbound-email handler for the `Capability.email` seam. Reads `DB` + `EMAIL_SUPPRESSIONS` from env. */
133
+ /**
134
+ * Build the inbound-email handler for the `Capability.email` seam. Reads `DB` + `EMAIL_SUPPRESSIONS` from env.
135
+ *
136
+ * It never throws. `createEntrypoint` runs every capability's handler in turn, so a throw here would stop the ones
137
+ * after it, and a throw out of `email()` is a delivery failure the sender sees. A failure is logged with its error
138
+ * and the handler returns. It classifies before it touches a binding: a message it will not act on needs neither
139
+ * database, and each part of a bounce runs on the binding it needs, with a part whose binding is missing logged at
140
+ * warn rather than thrown.
141
+ */
113
142
  export function createBounceHandler(): CapabilityEmailHandler {
114
143
  return async (message, env) => {
115
- const raw = await new Response(message.raw).text();
116
- const parsed = await PostalMime.parse(raw);
117
- const headers: Record<string, string> = {};
118
- for (const header of parsed.headers) headers[header.key.toLowerCase()] = header.value;
144
+ const environment = typeof env.ENVIRONMENT === "string" ? env.ENVIRONMENT : undefined;
145
+ const log = createWorkerLogger({ name: "email", fields: { env: environment ?? "unknown" } });
146
+ try {
147
+ const raw = await new Response(message.raw).text();
148
+ const parsed = await PostalMime.parse(raw);
149
+ const headers: Record<string, string> = {};
150
+ for (const header of parsed.headers) headers[header.key.toLowerCase()] = header.value;
119
151
 
120
- const classification = classifyInbound({
121
- contentType: headers["content-type"],
122
- autoSubmitted: headers["auto-submitted"],
123
- autoReplyHeader: "x-autoreply" in headers || "x-autorespond" in headers,
124
- raw,
125
- });
152
+ const classification = classifyInbound({
153
+ contentType: headers["content-type"],
154
+ autoSubmitted: headers["auto-submitted"],
155
+ autoReplyHeader: "x-autoreply" in headers || "x-autorespond" in headers,
156
+ raw,
157
+ });
158
+ if (classification.type === "ignore" || classification.type === "auto_reply") return;
126
159
 
127
- const bindings = env as unknown as { DB: D1Database; EMAIL_SUPPRESSIONS: D1Database; ENVIRONMENT?: string };
128
- await applyInbound(
129
- emailDatabase(bindings.DB),
130
- emailSuppressionDatabase(bindings.EMAIL_SUPPRESSIONS),
131
- classification,
132
- new Date(),
133
- bindings.ENVIRONMENT,
134
- );
160
+ const { DB: db, EMAIL_SUPPRESSIONS: suppressions } = env;
161
+ const outcome = await applyInbound(
162
+ isD1(db) ? emailDatabase(db) : undefined,
163
+ isD1(suppressions) ? emailSuppressionDatabase(suppressions) : undefined,
164
+ classification,
165
+ new Date(),
166
+ environment,
167
+ );
168
+ for (const { part, binding } of outcome.skipped) {
169
+ log.warn(
170
+ `email ${part === "job" ? "bounce not recorded on its job" : "address not suppressed"} — no ${binding} binding`,
171
+ {
172
+ binding,
173
+ skipped: part,
174
+ type: classification.type,
175
+ action: `Bind \`${binding}\` in this Worker's wrangler.jsonc.`,
176
+ },
177
+ );
178
+ }
179
+ } catch (error) {
180
+ log.error("email inbound handling failed", { error });
181
+ }
135
182
  };
136
183
  }
184
+
185
+ /** Whether a binding is there to open: a D1 binding is an object, and an absent one is `undefined`. */
186
+ function isD1(binding: unknown): binding is D1Database {
187
+ return typeof binding === "object" && binding !== null;
188
+ }
package/src/capability.ts CHANGED
@@ -25,6 +25,7 @@ import { emailAdminRoutes } from "./http/guards";
25
25
  import { registerEmailAdminRoutes } from "./http/routes";
26
26
  import { email_0001_init } from "./migrations/0001_init";
27
27
  import { email_0001_suppressions } from "./migrations/0001_suppressions";
28
+ import { email_0002_job_filters } from "./migrations/0002_job_filters";
28
29
  import { EMAIL_PROCESSING } from "./processing/activities";
29
30
  import { DevMailDelivery } from "./provision/devDelivery";
30
31
  import { emailHostCatalogs } from "./provision/hostCatalogs";
@@ -141,6 +142,18 @@ export interface EmailCapability extends Capability {
141
142
  * `EnqueueDeps` or name the email bindings themselves.
142
143
  */
143
144
  enqueue: (env: EmailEnqueueEnv, input: EnqueueInput) => Promise<EnqueueResult>;
145
+ /**
146
+ * `enqueue`, able to send as the addresses a composing capability declares and no others.
147
+ *
148
+ * The one way a per-message `from` is accepted. `enqueue` declares none, so an override passed to it is
149
+ * refused; a capability that receives mail at its own addresses binds this once, at compose, with exactly
150
+ * those addresses, and an override outside them is refused at enqueue. `@pithy-sh/support` binds its
151
+ * `inboundAddresses` and `reply.replyToAddress`.
152
+ *
153
+ * A convention that keeps each capability to its own addresses, not a security boundary: trusted Worker code
154
+ * can call this with any list. What limits sending is Cloudflare, which sends only from onboarded domains.
155
+ */
156
+ enqueueAs: (claimed: readonly string[]) => (env: EmailEnqueueEnv, input: EnqueueInput) => Promise<EnqueueResult>;
144
157
  /**
145
158
  * The suppression list, from a request env — **it is the adopter's database, and this is how they open
146
159
  * it**.
@@ -263,9 +276,9 @@ export function email(config: EmailConfigInput): EmailCapability {
263
276
  if (Array.isArray(locales)) supportedLocales = locales.filter((tag) => typeof tag === "string");
264
277
  }
265
278
  },
266
- // Email provisioning wires inbound bounce routing (Email Routing rules), so the CI credential that
267
- // provisions email needs that scope — contributed into the one `ci-system` token.
268
- ciPermissions: ["email:routing"],
279
+ // Email provisioning can route the bounce address, which its flags name: no address is declared, so a session asks
280
+ // for the Email Routing scopes and the CI token is granted them on no zone.
281
+ inboundRouting: { addresses: [] },
269
282
  requiredBindings: [
270
283
  { type: "d1", name: "DB" },
271
284
  { type: "d1", name: "EMAIL_SUPPRESSIONS" },
@@ -276,7 +289,7 @@ export function email(config: EmailConfigInput): EmailCapability {
276
289
  binding: "DB",
277
290
  tables: emailTables,
278
291
  migrationOrder: EMAIL_MIGRATION_ORDER,
279
- migrations: { "0001_init": email_0001_init },
292
+ migrations: { "0001_init": email_0001_init, "0002_job_filters": email_0002_job_filters },
280
293
  },
281
294
  emailSuppressions: {
282
295
  binding: "EMAIL_SUPPRESSIONS",
@@ -390,29 +403,35 @@ export function email(config: EmailConfigInput): EmailCapability {
390
403
  if (composed === undefined) return undefined;
391
404
  return (charge) => composed.charge(env as unknown as Record<string, unknown>, charge);
392
405
  };
393
- const enqueue = (env: EmailEnqueueEnv, input: EnqueueInput): Promise<EnqueueResult> =>
394
- enqueueEmail(
395
- {
396
- db: emailDatabase(env.DB),
397
- fromAddress: resolved.fromAddress,
398
- fromName: resolved.fromName,
399
- theme,
400
- // Read through the closure, not captured: `compose` runs after this function is defined and
401
- // before any request reaches it, so a snapshot taken here would be the pre-compose English.
402
- layersFor: (locale) => layersFor(locale),
403
- sender: emailSenderBinding(env),
404
- // Read straight off the env the consumer forwarded. This one line is what makes suppression
405
- // automatic: a consumer names nothing, and a hard-bounced address is never queued for a send.
406
- suppressionDb: env.EMAIL_SUPPRESSIONS ? emailSuppressionDatabase(env.EMAIL_SUPPRESSIONS) : undefined,
407
- // Read through the closure for the reason `layersFor` is: `compose` fills it after this is defined.
408
- meter: chargeFor(env),
409
- // Read through the closure for the same reason: `compose` fills the composition after this is defined.
410
- consent: composedConsent(composition, env as unknown as Record<string, unknown>),
411
- now: new Date(),
412
- newId: () => crypto.randomUUID(),
413
- },
414
- input,
415
- );
406
+ const enqueueAs = (claimed: readonly string[]) => {
407
+ // Copied, so the list a capability bound at compose is the list every later call is held to.
408
+ const claimedFrom = Object.freeze([...claimed]);
409
+ return (env: EmailEnqueueEnv, input: EnqueueInput): Promise<EnqueueResult> =>
410
+ enqueueEmail(
411
+ {
412
+ db: emailDatabase(env.DB),
413
+ fromAddress: resolved.fromAddress,
414
+ fromName: resolved.fromName,
415
+ claimedFrom,
416
+ theme,
417
+ // Read through the closure, not captured: `compose` runs after this function is defined and
418
+ // before any request reaches it, so a snapshot taken here would be the pre-compose English.
419
+ layersFor: (locale) => layersFor(locale),
420
+ sender: emailSenderBinding(env),
421
+ // Read straight off the env the consumer forwarded. This one line is what makes suppression
422
+ // automatic: a consumer names nothing, and a hard-bounced address is never queued for a send.
423
+ suppressionDb: env.EMAIL_SUPPRESSIONS ? emailSuppressionDatabase(env.EMAIL_SUPPRESSIONS) : undefined,
424
+ // Read through the closure for the reason `layersFor` is: `compose` fills it after this is defined.
425
+ meter: chargeFor(env),
426
+ // Read through the closure for the same reason: `compose` fills the composition after this is defined.
427
+ consent: composedConsent(composition, env as unknown as Record<string, unknown>),
428
+ now: new Date(),
429
+ newId: () => crypto.randomUUID(),
430
+ },
431
+ input,
432
+ );
433
+ };
434
+ const enqueue = enqueueAs([]);
416
435
  return Object.assign(capability, {
417
436
  emailConfig: {
418
437
  fromAddress: resolved.fromAddress,
@@ -423,6 +442,7 @@ export function email(config: EmailConfigInput): EmailCapability {
423
442
  theme,
424
443
  },
425
444
  enqueue,
445
+ enqueueAs,
426
446
  suppressions,
427
447
  // Read through the closures, never captured — `compose` runs after this object is built, and both
428
448
  // values it fills are the whole point of the call.
@@ -218,6 +218,8 @@ export function registerEmailAdminRoutes(options: EmailAdminRoutesOptions): (app
218
218
  metadata: {
219
219
  connectionId: who.connectionId,
220
220
  status: query.status ?? null,
221
+ template: query.template ?? null,
222
+ category: query.category ?? null,
221
223
  returned: page.items.length,
222
224
  paged: Boolean(query.cursor),
223
225
  },
@@ -329,7 +331,7 @@ export function registerEmailAdminRoutes(options: EmailAdminRoutesOptions): (app
329
331
  const query = c.req.valid("query");
330
332
  const who = caller(c);
331
333
  const now = clock();
332
- const page = await listSuppressions(suppressions(c), query);
334
+ const page = await listSuppressions(suppressions(c), { ...query, now });
333
335
 
334
336
  // The heaviest read in the capability: this database is global, so a page of it is a page of
335
337
  // every environment's bounces, complaints, and opt-outs. Audited with whether it was a lookup
@@ -345,6 +347,7 @@ export function registerEmailAdminRoutes(options: EmailAdminRoutesOptions): (app
345
347
  connectionId: who.connectionId,
346
348
  reason: query.reason ?? null,
347
349
  lookup: Boolean(query.email),
350
+ active: query.active ?? null,
348
351
  returned: page.items.length,
349
352
  paged: Boolean(query.cursor),
350
353
  },