@pithy-sh/email 0.8.2 → 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
@@ -3,7 +3,7 @@
3
3
 
4
4
  import { MAX_PAGE_SIZE } from "@pithy-sh/core/src/data/cursor";
5
5
  import { z } from "zod";
6
- import { EmailJobStatus, SuppressionReason } from "../data/enums";
6
+ import { EmailJobStatus, SuppressionReason, TemplateCategory } from "../data/enums";
7
7
 
8
8
  /**
9
9
  * The request schemas for every email route — the three public callbacks and the six control-plane
@@ -137,10 +137,21 @@ export const JobsQuery = z
137
137
  status: EmailJobStatus.optional().describe(
138
138
  "Filter to one lifecycle state — `failed` is the pane this capability exists for. Absent lists every state.",
139
139
  ),
140
+ template: z
141
+ .string()
142
+ .min(1)
143
+ .max(128)
144
+ .optional()
145
+ .describe(
146
+ "Filter to one template id, exactly (`magicLink`, `newsletter`). A shape check only: the template set is the project's, and one nothing has sent is an empty page.",
147
+ ),
148
+ category: TemplateCategory.optional().describe(
149
+ "Filter to one category: `transactional` or `marketing`. Absent lists both.",
150
+ ),
140
151
  cursor: Cursor,
141
152
  limit: Limit,
142
153
  })
143
- .describe("The send-log query: which state to filter by, and where to resume.");
154
+ .describe("The send-log query: which state, template and category to filter by, and where to resume.");
144
155
  export type JobsQuery = z.output<typeof JobsQuery>;
145
156
 
146
157
  /**
@@ -159,6 +170,14 @@ export const SuppressionsQuery = z
159
170
  email: AddressFilter.optional().describe(
160
171
  "Look one address up, exactly. Answers `is this person blocked` without disclosing anybody else.",
161
172
  ),
173
+ active: z
174
+ .enum(["true", "false"])
175
+ .describe("`true` or `false`.")
176
+ .transform((value) => value === "true")
177
+ .optional()
178
+ .describe(
179
+ "`true` for the blocks in force now, `false` for the ones whose expiry has passed. Judged as each row's `active` is. Both when absent.",
180
+ ),
162
181
  cursor: Cursor,
163
182
  limit: Limit,
164
183
  })
package/src/jobs/read.ts CHANGED
@@ -6,7 +6,7 @@ import { decodeCursor, type PageCursor, pageLimit, toPage } from "@pithy-sh/core
6
6
  import { InternalError } from "@pithy-sh/core/src/error/pithyError";
7
7
  import type { z } from "zod";
8
8
  import { EmailJob } from "../data/emailJob";
9
- import type { EmailJobStatus } from "../data/enums";
9
+ import type { EmailJobStatus, TemplateCategory } from "../data/enums";
10
10
  import type { EmailDatabase } from "../data/tables";
11
11
 
12
12
  /**
@@ -37,6 +37,10 @@ import type { EmailDatabase } from "../data/tables";
37
37
  export interface JobListFilter {
38
38
  /** One lifecycle state, or every state when absent. */
39
39
  status?: EmailJobStatus;
40
+ /** One template id, exactly, or every template when absent. */
41
+ template?: string;
42
+ /** One category, or both when absent. */
43
+ category?: TemplateCategory;
40
44
  /** The previous page's `nextCursor`. A malformed one is a first page. */
41
45
  cursor?: string;
42
46
  /** How many rows to return, clamped into range. */
@@ -65,7 +69,7 @@ function jobCursor(raw: string | undefined): { sort: number; id: string } | unde
65
69
  return { sort: cursor.sort, id: String(cursor.id) };
66
70
  }
67
71
 
68
- /** One page of jobs, newest first, optionally filtered to one status. */
72
+ /** One page of jobs, newest first, optionally filtered to one status, template and category. */
69
73
  export async function listJobs(db: EmailDatabase, filter: JobListFilter): Promise<JobPage> {
70
74
  const limit = pageLimit(filter.limit);
71
75
  const after = jobCursor(filter.cursor);
@@ -80,6 +84,8 @@ export async function listJobs(db: EmailDatabase, filter: JobListFilter): Promis
80
84
  .limit(limit + 1);
81
85
 
82
86
  if (filter.status) query = query.where("status", "=", filter.status);
87
+ if (filter.template !== undefined) query = query.where("template", "=", filter.template);
88
+ if (filter.category !== undefined) query = query.where("category", "=", filter.category);
83
89
  if (after) {
84
90
  query = query.where((eb) =>
85
91
  eb.or([eb("createdAt", "<", after.sort), eb.and([eb("createdAt", "=", after.sort), eb("id", "<", after.id)])]),
@@ -109,8 +115,7 @@ export async function getJob(db: EmailDatabase, jobId: string): Promise<EmailJob
109
115
  *
110
116
  * ## Two axes, because a template is not always one message
111
117
  *
112
- * It was `(to, template)` alone, and that could not finish its only intended consumer (pithy-sh/pithy#382).
113
- * Six account notices ride one `operationalNotice` to the same addresses, so the template id does not
118
+ * `(to, template)` alone cannot answer every send decision. Six account notices ride one `operationalNotice` to the same addresses, so the template id does not
114
119
  * separate them; `correlation` is the enqueue-side discriminator that does. See {@link SentSubject} for
115
120
  * why the two are a union and not three optional fields.
116
121
  *
@@ -133,8 +138,8 @@ export async function getJob(db: EmailDatabase, jobId: string): Promise<EmailJob
133
138
  * - **`subject`.** Rendered content, and the temptation is specific: it is the only per-row string that
134
139
  * distinguishes two messages sharing a template, so a caller needing that discrimination would match
135
140
  * on it. That match breaks on a copy edit, silently, in the direction of sending again. Discriminating
136
- * two notices was the enqueue side's problem and now has an enqueue-side answer — `correlation`
137
- * (#382) — rather than a rendered string exported to be string-matched.
141
+ * two notices is the enqueue side's problem and has an enqueue-side answer, `correlation`, rather than
142
+ * a rendered string exported to be string-matched.
138
143
  * - **`messageId`, `error`, `bounceCode`.** The provider's own words. A provider error routinely embeds
139
144
  * the recipient, which is why the list view carries `failed` rather than the text.
140
145
  *
@@ -165,11 +170,11 @@ export type SentSummary = z.output<typeof SentSummary>;
165
170
  * Which messages are being asked about — one of the two indexed axes, and the type admits no third
166
171
  * answer.
167
172
  *
168
- * **`(to, template)`** is the original question: has this template already gone to this person. It runs
173
+ * **`(to, template)`** is the plain question: has this template already gone to this person. It runs
169
174
  * on `(recipientKey, template, createdAt)`.
170
175
  *
171
- * **`correlation`** is the question a template carrying more than one kind of message needs
172
- * (pithy-sh/pithy#382): has *this thing* already been said. Six account notices ride one
176
+ * **`correlation`** is the question a template carrying more than one kind of message needs:
177
+ * has *this thing* already been said. Six account notices ride one
173
178
  * `operationalNotice` to the same addresses, so the template id cannot separate them and the address is
174
179
  * a proxy for the account only while one person belongs to one account. It runs on
175
180
  * `(correlation, createdAt)`.
@@ -0,0 +1,35 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import type { Kysely } from "kysely";
5
+ import type { Migration } from "kysely/migration";
6
+
7
+ /**
8
+ * The send log filtered by template or by category, newest first.
9
+ *
10
+ * `GET {base}/jobs?template=…` and `?category=…` page `pithy_email_jobs` on `(createdAt, id)` under one equality.
11
+ * Without an index led by the filtered column, SQLite walks `pithyEmailJobsCreatedIdx` and tests every job the
12
+ * project ever queued, and a template nobody has sent in a year is the whole table. `createdAt` second, so the
13
+ * filtered page is read in order and stops at the limit.
14
+ *
15
+ * **Appended, never folded into `0001`.** The email capability has shipped, so its table is history.
16
+ */
17
+ export const email_0002_job_filters: Migration = {
18
+ up: async (db: Kysely<unknown>): Promise<void> => {
19
+ await db.schema
20
+ .createIndex("pithyEmailJobsTemplateCreatedIdx")
21
+ .on("pithyEmailJobs")
22
+ .columns(["template", "createdAt"])
23
+ .execute();
24
+ await db.schema
25
+ .createIndex("pithyEmailJobsCategoryCreatedIdx")
26
+ .on("pithyEmailJobs")
27
+ .columns(["category", "createdAt"])
28
+ .execute();
29
+ },
30
+
31
+ down: async (db: Kysely<unknown>): Promise<void> => {
32
+ await db.schema.dropIndex("pithyEmailJobsCategoryCreatedIdx").execute();
33
+ await db.schema.dropIndex("pithyEmailJobsTemplateCreatedIdx").execute();
34
+ },
35
+ };
@@ -109,11 +109,22 @@ export interface EnqueueInput {
109
109
  /**
110
110
  * The address a recipient's answer should go to, when it is not `fromAddress`.
111
111
  *
112
- * `@pithy-sh/support` is what this is for: a reply is sent as the adopter's onboarded sending
113
- * identity (Cloudflare validates the `From` domain against exactly what was onboarded) while the
114
- * conversation has to come back to the support inbox, which is usually a different subdomain.
112
+ * `@pithy-sh/support` sets it on every reply, so the customer's answer comes back to the support inbox
113
+ * whichever address the reply was sent {@link from}.
115
114
  */
116
115
  replyTo?: string;
116
+ /**
117
+ * The sender of this one message, when it is not the capability's `fromAddress` and `fromName`.
118
+ *
119
+ * Refused unless `address` is one the composing capability declared: {@link EnqueueDeps.claimedFrom}, which
120
+ * only {@link import("../capability").EmailCapability.enqueueAs} fills, and the plain `enqueue` leaves empty.
121
+ * That keeps a capability to the addresses it declared; it is not a boundary against Worker code, which can
122
+ * call `enqueueAs` itself. Cloudflare sends only from onboarded domains. `name` falls back to `fromName`.
123
+ *
124
+ * The job is sent from exactly this address. A domain Email Service cannot send from fails the job with
125
+ * the domain named; no other sender is tried.
126
+ */
127
+ from?: EnqueueFrom;
117
128
  /**
118
129
  * The `Message-ID` this job answers, angle brackets included — the `In-Reply-To` header.
119
130
  *
@@ -144,11 +155,24 @@ export interface EnqueueInput {
144
155
  consentSubject?: ConsentSubject;
145
156
  }
146
157
 
158
+ /** A per-message sender: an address the composing capability claims, and an optional display name. */
159
+ export interface EnqueueFrom {
160
+ /** The address the message is sent from. Must be on {@link EnqueueDeps.claimedFrom}. */
161
+ address: string;
162
+ /** The display name. Absent sends under the capability's `fromName`. */
163
+ name?: string;
164
+ }
165
+
147
166
  /** Dependencies enqueue needs: the database, the from identity, optional send-Workflow binding, time, ids. */
148
167
  export interface EnqueueDeps {
149
168
  db: EmailDatabase;
150
169
  fromAddress: string;
151
170
  fromName: string;
171
+ /**
172
+ * The addresses a per-message {@link EnqueueInput.from} may name, supplied by the capability composing the
173
+ * call. Absent or empty refuses every override.
174
+ */
175
+ claimedFrom?: readonly string[];
152
176
  theme: EmailTheme;
153
177
  /**
154
178
  * Where the words for a locale come from — the composed project's catalogs.
@@ -275,9 +299,32 @@ function resolveSchedule(input: EnqueueInput, now: Date): { mode: SendMode; send
275
299
  return { mode, sendAt: resolveTimezoneSendAt(input.localTime, input.timezone, now), status: "scheduled" };
276
300
  }
277
301
 
302
+ /**
303
+ * The sender this job is stored with: the capability's identity, or a per-message one the composing capability
304
+ * claims. An unclaimed override is refused before anything is written.
305
+ */
306
+ function resolveSender(deps: EnqueueDeps, input: EnqueueInput): { fromAddress: string; fromName: string } {
307
+ if (input.from === undefined) return { fromAddress: deps.fromAddress, fromName: deps.fromName };
308
+ const address = normalizeAddress(input.from.address);
309
+ const claimed = (deps.claimedFrom ?? []).map(normalizeAddress);
310
+ if (!claimed.includes(address)) {
311
+ throw new EmailInvalidPayloadError({
312
+ message: "This message cannot be sent from that address.",
313
+ action:
314
+ claimed.length === 0
315
+ ? "Send without `from`, or send through the `enqueueAs` seam of the capability that claims the address."
316
+ : `Send from one of the claimed addresses: ${claimed.join(", ")}.`,
317
+ detail: `from ${address} is not among the ${claimed.length} address(es) the composing capability claims`,
318
+ });
319
+ }
320
+ const name = input.from.name?.trim();
321
+ return { fromAddress: address, fromName: name ? name : deps.fromName };
322
+ }
323
+
278
324
  /** Enqueue an email job, dispatching the send Workflow immediately when the mode is `immediate`. */
279
325
  export async function enqueueEmail(deps: EnqueueDeps, input: EnqueueInput): Promise<EnqueueResult> {
280
326
  const template = getTemplate(input.template);
327
+ const from = resolveSender(deps, input);
281
328
  // Validates the payload against the template schema and computes the stored subject — in the
282
329
  // recipient's language, which is also what the row records so the body can be rendered in it later.
283
330
  const translator = emailTranslator(input.locale, deps.layersFor ?? kitEmailLayers);
@@ -370,8 +417,8 @@ export async function enqueueEmail(deps: EnqueueDeps, input: EnqueueInput): Prom
370
417
  id: deps.newId(),
371
418
  toAddress: personalAddress(input.to),
372
419
  recipientKey: personalAddress(recipient),
373
- fromAddress: deps.fromAddress,
374
- fromName: deps.fromName,
420
+ fromAddress: from.fromAddress,
421
+ fromName: from.fromName,
375
422
  subject,
376
423
  template: input.template,
377
424
  category: template.category,
@@ -17,18 +17,12 @@ export interface ClassifiedSendError {
17
17
  /** The `E_*` code reported by the binding, a numeric provider code as a string, or `E_UNKNOWN` for none. */
18
18
  code: string;
19
19
  /**
20
- * The cause, as one operator-facing line: the code and whatever the provider said with it.
20
+ * The cause, as one operator-facing line: the code, whatever the provider said with it, and the sending domain
21
+ * when the code says that domain cannot send.
21
22
  *
22
- * **Exposed because the job row needs it and only the error object had it (pithy-sh/pithy#555).**
23
- * `runSend` persisted the bare `code` into `pithy_email_jobs.error`, so a magic link that failed five
24
- * times against a token for the wrong account recorded `E_UNKNOWN` five times and nothing about why —
25
- * while this exact string, naming `10000 Authentication error`, was being built two lines down and
26
- * thrown away with the error it decorated. Same family as #534: a failure that discards the cause it
27
- * was handed.
28
- *
29
- * Identical to `error.payload.detail`, deliberately — one composition, two readers, so the row and the
30
- * log cannot drift. `detail` is stripped at the client boundary, which is where a provider's own words
31
- * belong.
23
+ * `runSend` writes it to `pithy_email_jobs.error`, so the row names the cause rather than the bare code.
24
+ * Identical to `error.payload.detail`: one composition, two readers, so the row and the log cannot drift.
25
+ * `detail` is stripped at the client boundary, which is where a provider's own words belong.
32
26
  */
33
27
  detail: string;
34
28
  /** Whether the send should be retried with backoff. */
@@ -55,18 +49,31 @@ const RATE_LIMITED = new Set(["E_RATE_LIMIT_EXCEEDED", "E_DAILY_LIMIT_EXCEEDED"]
55
49
  *
56
50
  * `10000` is Cloudflare's own: a token that is alive but not scoped for Email Sending, or scoped for an
57
51
  * account that does not own the sending domain, is answered `{ code: 10000, message: "Authentication
58
- * error" }` (#534 captured the body; `liveSend.integration.test.ts` documents the same rejection for a
59
- * general account token). That is the exact failure #555 spent five attempts on in silence.
52
+ * error" }` (`liveSend.integration.test.ts` documents the same rejection for a general account token).
60
53
  *
61
- * **Named rather than inferred from the code being numeric.** Treating every numeric code as terminal was
62
- * the first shape of this fix and it bought the auth case by making a *momentary* numeric failure
63
- * permanent too — one attempt, `status: "failed"`, where the retry budget used to apply. A code nobody
64
- * here recognizes is still unknown, whichever alphabet it is written in, and unknown has earned its
65
- * bounded retry since the module was written. So the auth class is listed, and the rule below is
66
- * unchanged for everything else.
54
+ * **Listed rather than inferred from the code being numeric.** Treating every numeric code as terminal would
55
+ * make a momentary numeric failure permanent too — one attempt, `status: "failed"`, where the retry budget
56
+ * applies. A code nobody here recognizes is still unknown, whichever alphabet it is written in, and unknown
57
+ * keeps its bounded retry.
67
58
  */
68
59
  const UNAUTHORIZED = new Set(["10000", "E_UNAUTHORIZED", "E_FORBIDDEN"]);
69
60
 
61
+ /**
62
+ * Codes that mean **the sender's domain cannot send**: not onboarded onto Email Service, or not verified.
63
+ * Terminal like every unlisted `E_*`, and named so the job's error says which domain to onboard.
64
+ */
65
+ const SENDER_DOMAIN = new Set(["E_SENDER_DOMAIN_NOT_AVAILABLE", "E_SENDER_NOT_VERIFIED"]);
66
+
67
+ /** The domain half of an address, lowercased, or `null` when it carries none. */
68
+ function domainOf(address: string): string | null {
69
+ const at = address.lastIndexOf("@");
70
+ if (at < 0 || at === address.length - 1) return null;
71
+ return address
72
+ .slice(at + 1)
73
+ .trim()
74
+ .toLowerCase();
75
+ }
76
+
70
77
  /**
71
78
  * Whether a code is one of Cloudflare's numeric ones rather than the binding's `E_*` spelling.
72
79
  *
@@ -83,16 +90,14 @@ function isProviderNumericCode(code: string): boolean {
83
90
  /**
84
91
  * Read a thrown value's `.code`/`.message` without assuming its shape.
85
92
  *
86
- * **A numeric code counts, and that is not a detail.** The Email Service binding surfaces `E_*` strings,
87
- * but the REST path and the account layer behind it answer with Cloudflare's own numeric codes — an
88
- * unauthorized send is `{ code: 10000, message: "Authentication error" }` (#534 captured the body). Read
89
- * as "no code" that became `E_UNKNOWN`, which is both silent *and* retryable, so a credential fault
90
- * consumed every attempt without ever naming itself (#555).
93
+ * **A numeric code counts.** The Email Service binding surfaces `E_*` strings, but the REST path and the
94
+ * account layer behind it answer with Cloudflare's own numeric codes — an unauthorized send is
95
+ * `{ code: 10000, message: "Authentication error" }`. Read as "no code" that would be `E_UNKNOWN`, which is
96
+ * both silent *and* retryable, so a credential fault would consume every attempt without naming itself.
91
97
  *
92
- * **And a value with neither field still leaves a trace.** `String(err)` rather than `""`: an opaque
93
- * throw is the case where the operator has least to go on, so an empty string is the one answer that
94
- * cannot help. `E_UNKNOWN` remains the code — it means *nothing named itself*, which is the fact that
95
- * earns the bounded retry.
98
+ * **A value with neither field still leaves a trace.** `String(err)` rather than `""`: an opaque throw is
99
+ * the case where the operator has least to go on. `E_UNKNOWN` remains the code — it means *nothing named
100
+ * itself*, which is the fact that earns the bounded retry.
96
101
  */
97
102
  function readError(err: unknown): { code: string; message: string } {
98
103
  if (err && typeof err === "object") {
@@ -112,19 +117,21 @@ function readError(err: unknown): { code: string; message: string } {
112
117
  * suppressed locally too; rate/quota and transient delivery codes are retryable; everything else
113
118
  * (validation, sender, content, headers) is terminal.
114
119
  *
115
- * **An unrecognized code is retryable, and that is deliberately unchanged.** A failure this module has
116
- * no code at all keeps its bounded retry, and so does a *numeric* provider code nobody here has listed —
117
- * see {@link isProviderNumericCode} for why those two are alike and an unlisted `E_*` is not.
120
+ * **An unrecognized code is retryable**: a failure with no code at all keeps its bounded retry, and so does
121
+ * a *numeric* provider code nobody here has listed — see {@link isProviderNumericCode} for why those two are
122
+ * alike and an unlisted `E_*` is not. The **authentication** class is named and terminal: `10000
123
+ * Authentication error` is a token that cannot send as this domain, and no retry changes that — see
124
+ * {@link UNAUTHORIZED} for why that is a list rather than "numeric means permanent".
118
125
  *
119
- * What changed for #555 is that the **authentication** class is now named and terminal: `10000
120
- * Authentication error` is a token that cannot send as this domain, and spending five attempts on it in
121
- * silence is what hid the whole incident. See {@link UNAUTHORIZED} for why that is a list rather than
122
- * "numeric means permanent" — the latter was this fix's first shape, and it made a momentary numeric
123
- * failure permanent as a side effect.
126
+ * `context.fromAddress` is the job's sender. When the code says its domain cannot send, the detail names the
127
+ * domain, so the operator knows which one to onboard.
124
128
  */
125
- export function classifySendError(err: unknown): ClassifiedSendError {
129
+ export function classifySendError(err: unknown, context: { fromAddress?: string } = {}): ClassifiedSendError {
126
130
  const { code, message } = readError(err);
127
- const detail = `email send failed: ${code}${message ? ` — ${message}` : ""}`;
131
+ const domain = SENDER_DOMAIN.has(code) && context.fromAddress ? domainOf(context.fromAddress) : null;
132
+ const detail = `email send failed: ${code}${message ? ` — ${message}` : ""}${
133
+ domain ? ` (${domain} is not set up for sending on Email Service)` : ""
134
+ }`;
128
135
 
129
136
  if (code === "E_RECIPIENT_SUPPRESSED") {
130
137
  return {
@@ -73,11 +73,11 @@ export interface SendDeps {
73
73
  /** This worker's environment name, stamped on each send (X-Pithy-Env) so the single inbound worker can route. */
74
74
  environment?: string;
75
75
  /**
76
- * When this pass began — **stable across a Workflow resume** (pithy-sh/pithy#327).
76
+ * When this pass began — **stable across a Workflow resume**.
77
77
  *
78
78
  * Everything that dates the work reads this: `sentAt`, the redaction stamp, the events, and how long a
79
79
  * tracked link stays valid. A driver body re-executes from the top on a resume, so a clock read there
80
- * answers with the resume — and a batch that backed off overnight dated its remaining jobs, and the
80
+ * answers with the resume — a batch that backed off overnight would date its remaining jobs, and the
81
81
  * expiry of every link in them, a day late. `runSendBatch` journals this in a step so a resume reads
82
82
  * back the instant the batch began.
83
83
  *
@@ -294,7 +294,7 @@ export async function runSend(deps: SendDeps, jobId: string): Promise<SendOutcom
294
294
 
295
295
  return { jobId, status: "sent", messageId: result.messageId };
296
296
  } catch (err) {
297
- const classified = classifySendError(err);
297
+ const classified = classifySendError(err, { fromAddress: job.fromAddress });
298
298
 
299
299
  if (classified.suppressed) {
300
300
  await patchJob(deps, jobId, { status: "suppressed", error: classified.code, bounceCode: classified.code });
@@ -313,10 +313,9 @@ export async function runSend(deps: SendDeps, jobId: string): Promise<SendOutcom
313
313
  throw classified.error;
314
314
  }
315
315
 
316
- // **`detail`, not `code`.** The column is described as "the last error code/message", and it held only
317
- // the code — so a magic link that failed five times recorded `E_UNKNOWN` five times, and the one
318
- // sentence naming the cause was discarded with the error object (pithy-sh/pithy#555, and #534's
319
- // family). `detail` leads with the code, so nothing a reader had before is lost.
316
+ // **`detail`, not `code`.** The column is "the last error code/message", and the bare code says nothing
317
+ // about why — `detail` leads with the code and adds the provider's words and, for a domain that cannot
318
+ // send, the domain. The job keeps its own sender: nothing is retried as another one.
320
319
  await patchJob(deps, jobId, { status: "failed", error: classified.detail });
321
320
  await recordEvent(deps.db, { jobId, recipient, type: "failed", detail: classified.detail }, deps.passStartedAt);
322
321
  return { jobId, status: "failed" };
@@ -129,6 +129,10 @@ export interface SuppressionListFilter {
129
129
  reason?: SuppressionReason;
130
130
  /** Look one address up exactly, rather than paging the list. */
131
131
  email?: string;
132
+ /** The blocks in force at `now` (`true`), or the ones whose expiry has passed (`false`). Every row when absent. */
133
+ active?: boolean;
134
+ /** The instant `active` is judged at. Defaults to the moment of the read. */
135
+ now?: Date;
132
136
  /** The previous page's `nextCursor`. A malformed one is a first page. */
133
137
  cursor?: string;
134
138
  /** How many rows to return, clamped into range. */
@@ -182,6 +186,15 @@ export async function listSuppressions(
182
186
  // neighbors would be a way to enumerate the list one query at a time while looking like a question
183
187
  // about a single address.
184
188
  if (filter.email) query = query.where("email", "=", normalizeAddress(filter.email));
189
+ if (filter.active !== undefined) {
190
+ // The expiry is exclusive, as `suppressionView` reads it: at the instant it names, the block is over.
191
+ const at = SQLiteDate.encode(filter.now ?? new Date());
192
+ query = query.where((eb) =>
193
+ filter.active
194
+ ? eb.or([eb("expiresAt", "is", null), eb("expiresAt", ">", at)])
195
+ : eb.and([eb("expiresAt", "is not", null), eb("expiresAt", "<=", at)]),
196
+ );
197
+ }
185
198
  if (after) {
186
199
  query = query.where((eb) =>
187
200
  eb.or([eb("createdAt", "<", after.sort), eb.and([eb("createdAt", "=", after.sort), eb("id", "<", after.id)])]),
@@ -13,4 +13,4 @@
13
13
  export const PACKAGE_NAME = "@pithy-sh/email";
14
14
 
15
15
  /** This package's version, stamped from its own package.json at generation time. */
16
- export const PACKAGE_VERSION = "0.8.2";
16
+ export const PACKAGE_VERSION = "0.9.0";