@pithy-sh/email 0.8.2 → 0.10.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 (62) 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/crypto/signingKey.d.ts.map +1 -1
  9. package/dist/crypto/token.d.ts +43 -11
  10. package/dist/crypto/token.d.ts.map +1 -1
  11. package/dist/crypto/token.js +158 -55
  12. package/dist/http/callbacks.d.ts +8 -3
  13. package/dist/http/callbacks.d.ts.map +1 -1
  14. package/dist/http/callbacks.js +67 -12
  15. package/dist/http/guards.d.ts.map +1 -1
  16. package/dist/http/guards.js +9 -0
  17. package/dist/http/routes.d.ts +8 -4
  18. package/dist/http/routes.d.ts.map +1 -1
  19. package/dist/http/routes.js +67 -21
  20. package/dist/http/schemas.d.ts +41 -13
  21. package/dist/http/schemas.d.ts.map +1 -1
  22. package/dist/http/schemas.js +38 -15
  23. package/dist/jobs/read.d.ts +12 -9
  24. package/dist/jobs/read.d.ts.map +1 -1
  25. package/dist/jobs/read.js +6 -5
  26. package/dist/migrations/0002_job_filters.d.ts +15 -0
  27. package/dist/migrations/0002_job_filters.d.ts.map +1 -0
  28. package/dist/migrations/0002_job_filters.js +25 -0
  29. package/dist/send/enqueue.d.ts +26 -3
  30. package/dist/send/enqueue.d.ts.map +1 -1
  31. package/dist/send/enqueue.js +25 -2
  32. package/dist/send/errorMapping.d.ts +15 -20
  33. package/dist/send/errorMapping.d.ts.map +1 -1
  34. package/dist/send/errorMapping.js +33 -27
  35. package/dist/send/runSend.d.ts +2 -2
  36. package/dist/send/runSend.d.ts.map +1 -1
  37. package/dist/send/runSend.js +1 -1
  38. package/dist/send/suppression.d.ts +4 -0
  39. package/dist/send/suppression.d.ts.map +1 -1
  40. package/dist/send/suppression.js +4 -0
  41. package/dist/templates/engine.d.ts +1 -1
  42. package/dist/templates/engine.js +1 -1
  43. package/dist/version.generated.d.ts +1 -1
  44. package/dist/version.generated.d.ts.map +1 -1
  45. package/dist/version.generated.js +1 -1
  46. package/package.json +3 -3
  47. package/src/bounce/handler.ts +84 -32
  48. package/src/capability.ts +47 -27
  49. package/src/crypto/signingKey.ts +4 -2
  50. package/src/crypto/token.ts +225 -92
  51. package/src/http/callbacks.ts +100 -32
  52. package/src/http/guards.ts +9 -0
  53. package/src/http/routes.ts +96 -28
  54. package/src/http/schemas.ts +75 -24
  55. package/src/jobs/read.ts +14 -9
  56. package/src/migrations/0002_job_filters.ts +35 -0
  57. package/src/send/enqueue.ts +52 -5
  58. package/src/send/errorMapping.ts +45 -38
  59. package/src/send/runSend.ts +6 -7
  60. package/src/send/suppression.ts +13 -0
  61. package/src/templates/engine.ts +1 -1
  62. package/src/version.generated.ts +1 -1
@@ -2,7 +2,7 @@
2
2
  // SPDX-License-Identifier: MIT
3
3
  import { emailDatabase, emailSuppressionDatabase } from "../data/tables.js";
4
4
  import { listSuppressions, suppress, unsuppress } from "../send/suppression.js";
5
- import { JobIdParam, JobsQuery, SuppressRequest, SuppressionsQuery, UnsuppressRequest } from "./schemas.js";
5
+ import { JobIdParam, JobsQuery, SuppressRequest, SuppressionLookupRequest, SuppressionsQuery, UnsuppressRequest } from "./schemas.js";
6
6
  import { EMAIL_JOBS_READ_SCOPE, EMAIL_JOBS_RETRY_SCOPE, EMAIL_SUPPRESSIONS_DELETE_SCOPE, EMAIL_SUPPRESSIONS_READ_SCOPE, EMAIL_SUPPRESSIONS_WRITE_SCOPE } from "./guards.js";
7
7
  import { EmailAuditActions } from "../audit/actions.js";
8
8
  import { getJob, listJobs } from "../jobs/read.js";
@@ -50,6 +50,12 @@ const EMAIL_ADMIN_ROUTES = [
50
50
  strategy: "control-plane",
51
51
  scope: EMAIL_SUPPRESSIONS_READ_SCOPE
52
52
  },
53
+ {
54
+ method: "POST",
55
+ path: "/suppressions/lookup",
56
+ strategy: "control-plane",
57
+ scope: EMAIL_SUPPRESSIONS_READ_SCOPE
58
+ },
53
59
  {
54
60
  method: "POST",
55
61
  path: "/suppressions",
@@ -102,6 +108,26 @@ function caller(c) {
102
108
  });
103
109
  return context;
104
110
  }
111
+ /**
112
+ * Audit a read of the suppression list. The heaviest read in the capability: this database is global, so
113
+ * a page of it is a page of every environment's bounces, complaints, and opt-outs. Audited with whether
114
+ * it was a lookup or a walk, because those are very different events.
115
+ */
116
+ async function auditSuppressionsRead(c, metadata) {
117
+ const who = caller(c);
118
+ await c.var.emit({
119
+ action: EmailAuditActions.suppressionsRead,
120
+ outcome: "success",
121
+ actorType: "control-plane",
122
+ actorId: who.subject,
123
+ resourceType: "email_suppression",
124
+ resourceId: null,
125
+ metadata: {
126
+ connectionId: who.connectionId,
127
+ ...metadata
128
+ }
129
+ });
130
+ }
105
131
  /** Register the email management sub-router. Composed alongside the public callbacks. */
106
132
  function registerEmailAdminRoutes(options) {
107
133
  const base = options.basePath;
@@ -126,6 +152,8 @@ function registerEmailAdminRoutes(options) {
126
152
  metadata: {
127
153
  connectionId: who.connectionId,
128
154
  status: query.status ?? null,
155
+ template: query.template ?? null,
156
+ category: query.category ?? null,
129
157
  returned: page.items.length,
130
158
  paged: Boolean(query.cursor)
131
159
  }
@@ -202,29 +230,47 @@ function registerEmailAdminRoutes(options) {
202
230
  });
203
231
  });
204
232
  app.get(`${base}/suppressions`, describeRoute({
205
- summary: "Page through the suppression list, or look one address up.",
233
+ summary: "Page through the suppression list.",
206
234
  verification: "control-plane",
207
235
  scopes: [EMAIL_SUPPRESSIONS_READ_SCOPE],
208
236
  responses: { 200: EmailSuppressionsResponse }
209
237
  }), requireControlPlane(EMAIL_SUPPRESSIONS_READ_SCOPE), validate("query", SuppressionsQuery), async (c) => {
210
238
  const query = c.req.valid("query");
211
- const who = caller(c);
212
239
  const now = clock();
213
- const page = await listSuppressions(suppressions(c), query);
214
- await c.var.emit({
215
- action: EmailAuditActions.suppressionsRead,
216
- outcome: "success",
217
- actorType: "control-plane",
218
- actorId: who.subject,
219
- resourceType: "email_suppression",
220
- resourceId: null,
221
- metadata: {
222
- connectionId: who.connectionId,
223
- reason: query.reason ?? null,
224
- lookup: Boolean(query.email),
225
- returned: page.items.length,
226
- paged: Boolean(query.cursor)
227
- }
240
+ const page = await listSuppressions(suppressions(c), {
241
+ ...query,
242
+ now
243
+ });
244
+ await auditSuppressionsRead(c, {
245
+ reason: query.reason ?? null,
246
+ lookup: false,
247
+ active: query.active ?? null,
248
+ returned: page.items.length,
249
+ paged: Boolean(query.cursor)
250
+ });
251
+ return c.json({
252
+ suppressions: page.items.map((row) => suppressionView(row, now)),
253
+ nextCursor: page.nextCursor
254
+ });
255
+ });
256
+ app.post(`${base}/suppressions/lookup`, describeRoute({
257
+ summary: "Look one address up on the suppression list.",
258
+ verification: "control-plane",
259
+ scopes: [EMAIL_SUPPRESSIONS_READ_SCOPE],
260
+ responses: { 200: EmailSuppressionsResponse }
261
+ }), requireControlPlane(EMAIL_SUPPRESSIONS_READ_SCOPE), validate("json", SuppressionLookupRequest), async (c) => {
262
+ const input = c.req.valid("json");
263
+ const now = clock();
264
+ const page = await listSuppressions(suppressions(c), {
265
+ email: input.email,
266
+ now
267
+ });
268
+ await auditSuppressionsRead(c, {
269
+ reason: null,
270
+ lookup: true,
271
+ active: null,
272
+ returned: page.items.length,
273
+ paged: false
228
274
  });
229
275
  return c.json({
230
276
  suppressions: page.items.map((row) => suppressionView(row, now)),
@@ -246,16 +292,16 @@ function registerEmailAdminRoutes(options) {
246
292
  if (expiresAt && expiresAt.getTime() <= now.getTime()) throw new ValidationError({
247
293
  message: "That expiry has already passed, so it would not block anything.",
248
294
  action: "Give a future instant, or omit `expiresAt` to block permanently. To lift an existing block, use the remove route — it requires `email:suppressions:delete`.",
249
- detail: `refused suppression for ${email} with expiresAt ${expiresAt.toISOString()} at ${now.toISOString()}`
295
+ detail: `refused suppression with expiresAt ${expiresAt.toISOString()} at ${now.toISOString()}`
250
296
  });
251
297
  const current = (await listSuppressions(db, {
252
298
  email,
253
299
  limit: 1
254
300
  })).items[0];
255
301
  if (current && current.reason !== "manual") throw new ConflictError({
256
- message: `${email} is already suppressed as a ${current.reason}, which this route may not overwrite.`,
302
+ message: `That address is already suppressed as a ${current.reason}, which this route may not overwrite.`,
257
303
  action: "Lift it with the remove route, which requires `email:suppressions:delete` — undoing a bounce, a complaint, or someone's own opt-out is a separate decision.",
258
- detail: `refused manual suppression over an existing ${current.reason} for ${email}`
304
+ detail: `refused manual suppression over an existing ${current.reason}`
259
305
  });
260
306
  await suppress(db, {
261
307
  email,
@@ -3,7 +3,7 @@
3
3
  import { z } from "zod";
4
4
  /**
5
5
  * The `:token` path parameter every callback route carries. A shape and size bound only — the ceiling
6
- * is generous enough for a click token whose signed claims embed a long destination URL, so no link we
6
+ * is generous enough for a click token whose sealed claims embed a long destination URL, so no link we
7
7
  * mint can exceed it, while an unbounded segment can no longer reach the verifier.
8
8
  */
9
9
  export declare const CallbackTokenParam: z.ZodObject<{
@@ -11,14 +11,22 @@ export declare const CallbackTokenParam: z.ZodObject<{
11
11
  }, z.core.$strip>;
12
12
  export type CallbackTokenParam = z.output<typeof CallbackTokenParam>;
13
13
  /**
14
- * The optional `?reason=` on the unsubscribe callback — supplied by the app's own preferences flow.
15
- * The bound is a ceiling, not the storage limit: the handler still truncates to 200 characters before
16
- * writing, so every real value keeps behaving exactly as it did and only an absurd one is refused.
14
+ * The form body of an unsubscribe `POST`: what a mail client's one-click unsubscribe sends (RFC 8058 fixes it to
15
+ * `List-Unsubscribe=One-Click`), what the confirmation page's button sends, and what the app's own preferences flow
16
+ * sends with a `reason`.
17
+ *
18
+ * **Nothing in it can refuse the opt-out.** Every field is optional, a repeated field or one of the wrong type reads
19
+ * as absent or as its first value, and an over-long reason is truncated by the handler rather than refused. The
20
+ * token is the only gate; a body is never a reason somebody stays subscribed.
21
+ *
22
+ * The reason travels in the body because it is the recipient's own words, and a query string is written to every
23
+ * request log between the client and the Worker. The route reads no query at all.
17
24
  */
18
- export declare const UnsubscribeQuery: z.ZodObject<{
19
- reason: z.ZodOptional<z.ZodString>;
25
+ export declare const UnsubscribeForm: z.ZodObject<{
26
+ "List-Unsubscribe": z.ZodCatch<z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodArray<z.ZodString>]>>>;
27
+ reason: z.ZodCatch<z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodArray<z.ZodString>]>>>;
20
28
  }, z.core.$strip>;
21
- export type UnsubscribeQuery = z.output<typeof UnsubscribeQuery>;
29
+ export type UnsubscribeForm = z.output<typeof UnsubscribeForm>;
22
30
  /**
23
31
  * The `:id` of one job.
24
32
  *
@@ -44,6 +52,11 @@ export declare const JobsQuery: z.ZodObject<{
44
52
  suppressed: "suppressed";
45
53
  undispatched: "undispatched";
46
54
  }>>;
55
+ template: z.ZodOptional<z.ZodString>;
56
+ category: z.ZodOptional<z.ZodEnum<{
57
+ marketing: "marketing";
58
+ transactional: "transactional";
59
+ }>>;
47
60
  cursor: z.ZodOptional<z.ZodString>;
48
61
  limit: z.ZodOptional<z.ZodCoercedNumber<unknown>>;
49
62
  }, z.core.$strip>;
@@ -51,10 +64,10 @@ export type JobsQuery = z.output<typeof JobsQuery>;
51
64
  /**
52
65
  * The suppression list query.
53
66
  *
54
- * `email` is an exact-match lookup rather than a search, and that is the point: answering "is this one
55
- * address blocked" should not require paging a list of every other person who ever unsubscribed. A
56
- * prefix or substring search would turn the endpoint into a way to enumerate the list a page at a time
57
- * while looking like a lookup.
67
+ * **No address, and an unknown key is refused.** A query string is written to every request log between
68
+ * the client and the Worker, so looking one address up is {@link SuppressionLookupRequest}, a `POST`
69
+ * with the address in its body. Strict rather than stripping, so a client still sending `?email=` is
70
+ * told so with a 400 instead of being handed the whole list as though it were the match.
58
71
  */
59
72
  export declare const SuppressionsQuery: z.ZodObject<{
60
73
  reason: z.ZodOptional<z.ZodEnum<{
@@ -63,10 +76,13 @@ export declare const SuppressionsQuery: z.ZodObject<{
63
76
  manual: "manual";
64
77
  unsubscribe: "unsubscribe";
65
78
  }>>;
66
- email: z.ZodOptional<z.ZodString>;
79
+ active: z.ZodOptional<z.ZodPipe<z.ZodEnum<{
80
+ false: "false";
81
+ true: "true";
82
+ }>, z.ZodTransform<boolean, "false" | "true">>>;
67
83
  cursor: z.ZodOptional<z.ZodString>;
68
84
  limit: z.ZodOptional<z.ZodCoercedNumber<unknown>>;
69
- }, z.core.$strip>;
85
+ }, z.core.$strict>;
70
86
  export type SuppressionsQuery = z.output<typeof SuppressionsQuery>;
71
87
  /**
72
88
  * Block an address by hand.
@@ -84,6 +100,18 @@ export declare const SuppressRequest: z.ZodObject<{
84
100
  expiresAt: z.ZodOptional<z.ZodISODateTime>;
85
101
  }, z.core.$strip>;
86
102
  export type SuppressRequest = z.output<typeof SuppressRequest>;
103
+ /**
104
+ * Look one address up.
105
+ *
106
+ * An exact match rather than a search, and that is the point: answering "is this one address blocked"
107
+ * should not require paging a list of every other person who ever unsubscribed, and a prefix or substring
108
+ * search would enumerate the list a page at a time while looking like a lookup. A body because a query
109
+ * string is written to every request log between the client and the Worker.
110
+ */
111
+ export declare const SuppressionLookupRequest: z.ZodObject<{
112
+ email: z.ZodString;
113
+ }, z.core.$strict>;
114
+ export type SuppressionLookupRequest = z.output<typeof SuppressionLookupRequest>;
87
115
  /** Unblock an address — the undo of {@link SuppressRequest}, and of a bounce, complaint, or opt-out. */
88
116
  export declare const UnsuppressRequest: z.ZodObject<{
89
117
  email: z.ZodString;
@@ -1 +1 @@
1
- {"version":3,"file":"schemas.d.ts","sourceRoot":"","sources":["../../src/http/schemas.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AA0BxB;;;;GAIG;AACH,eAAO,MAAM,kBAAkB;;iBASoD,CAAC;AACpF,MAAM,MAAM,kBAAkB,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e;;;iBASwC,CAAC;AACrE,MAAM,MAAM,eAAe,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,eAAe,CAAC,CAAC;AAoD/D;;;;;;;GAOG;AACH,eAAO,MAAM,UAAU;;iBAS2C,CAAC;AACnE,MAAM,MAAM,UAAU,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,UAAU,CAAC,CAAC;AAErD,yBAAyB;AACzB,eAAO,MAAM,SAAS;;;;;;;;;;;;;;;;;;;iBAmBkF,CAAC;AACzG,MAAM,MAAM,SAAS,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,SAAS,CAAC,CAAC;AAEnD;;;;;;;GAOG;AACH,eAAO,MAAM,iBAAiB;;;;;;;;;;;;;kBAmB3B,CAAC;AACJ,MAAM,MAAM,iBAAiB,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,iBAAiB,CAAC,CAAC;AAEnE;;;;;;;;;GASG;AACH,eAAO,MAAM,eAAe;;;;iBAgBqD,CAAC;AAClF,MAAM,MAAM,eAAe,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,eAAe,CAAC,CAAC;AAE/D;;;;;;;GAOG;AACH,eAAO,MAAM,wBAAwB;;kBAO6B,CAAC;AACnE,MAAM,MAAM,wBAAwB,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,wBAAwB,CAAC,CAAC;AAEjF,wGAAwG;AACxG,eAAO,MAAM,iBAAiB;;iBAI+D,CAAC;AAC9F,MAAM,MAAM,iBAAiB,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,iBAAiB,CAAC,CAAC"}
@@ -1,20 +1,32 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: MIT
3
- import { EmailJobStatus, SuppressionReason } from "../data/enums.js";
3
+ import { EmailJobStatus, SuppressionReason, TemplateCategory } from "../data/enums.js";
4
4
  import { z } from "zod";
5
5
  import { MAX_PAGE_SIZE } from "@pithy-sh/core/src/data/cursor";
6
6
  /**
7
7
  * The `:token` path parameter every callback route carries. A shape and size bound only — the ceiling
8
- * is generous enough for a click token whose signed claims embed a long destination URL, so no link we
8
+ * is generous enough for a click token whose sealed claims embed a long destination URL, so no link we
9
9
  * mint can exceed it, while an unbounded segment can no longer reach the verifier.
10
10
  */
11
- const CallbackTokenParam = z.object({ token: z.string().min(1).max(4096).regex(/^[A-Za-z0-9._-]+$/).describe("The signed callback token from the path, optionally with the open-pixel `.png` suffix.") }).describe("The path parameter carrying a click/open/unsubscribe callback token.");
11
+ const CallbackTokenParam = z.object({ token: z.string().min(1).max(4096).regex(/^[A-Za-z0-9._-]+$/).describe("The sealed callback token from the path, optionally with the open-pixel `.png` suffix.") }).describe("The path parameter carrying a click/open/unsubscribe callback token.");
12
+ /** One form field as a client may send it: a value, or a repeated field's values. Anything else reads as absent. */
13
+ const FormField = z.union([z.string(), z.array(z.string())]).optional().catch(void 0);
12
14
  /**
13
- * The optional `?reason=` on the unsubscribe callback — supplied by the app's own preferences flow.
14
- * The bound is a ceiling, not the storage limit: the handler still truncates to 200 characters before
15
- * writing, so every real value keeps behaving exactly as it did and only an absurd one is refused.
15
+ * The form body of an unsubscribe `POST`: what a mail client's one-click unsubscribe sends (RFC 8058 fixes it to
16
+ * `List-Unsubscribe=One-Click`), what the confirmation page's button sends, and what the app's own preferences flow
17
+ * sends with a `reason`.
18
+ *
19
+ * **Nothing in it can refuse the opt-out.** Every field is optional, a repeated field or one of the wrong type reads
20
+ * as absent or as its first value, and an over-long reason is truncated by the handler rather than refused. The
21
+ * token is the only gate; a body is never a reason somebody stays subscribed.
22
+ *
23
+ * The reason travels in the body because it is the recipient's own words, and a query string is written to every
24
+ * request log between the client and the Worker. The route reads no query at all.
16
25
  */
17
- const UnsubscribeQuery = z.object({ reason: z.string().max(2e3).optional().describe("Why the recipient opted out; truncated to 200 characters before it is stored.") }).describe("The optional query parameters accepted by the unsubscribe callback.");
26
+ const UnsubscribeForm = z.object({
27
+ "List-Unsubscribe": FormField.describe("`One-Click` from a mail client's RFC 8058 one-click unsubscribe. Accepted and not otherwise read."),
28
+ reason: FormField.describe("Why the recipient opted out; the first value is kept, truncated to 200 characters before it is stored.")
29
+ }).describe("The optional form fields an unsubscribe POST accepts.");
18
30
  /**
19
31
  * Where the next page starts. Opaque, and a malformed one is a first page rather than a 400 — the
20
32
  * decode lives in `@pithy-sh/core/src/data/cursor` and collapses every failure mode to the same
@@ -55,23 +67,25 @@ const JobIdParam = z.object({ id: z.string().min(1).max(128).regex(/^[A-Za-z0-9.
55
67
  /** The job log query. */
56
68
  const JobsQuery = z.object({
57
69
  status: EmailJobStatus.optional().describe("Filter to one lifecycle state — `failed` is the pane this capability exists for. Absent lists every state."),
70
+ template: z.string().min(1).max(128).optional().describe("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."),
71
+ category: TemplateCategory.optional().describe("Filter to one category: `transactional` or `marketing`. Absent lists both."),
58
72
  cursor: Cursor,
59
73
  limit: Limit
60
- }).describe("The send-log query: which state to filter by, and where to resume.");
74
+ }).describe("The send-log query: which state, template and category to filter by, and where to resume.");
61
75
  /**
62
76
  * The suppression list query.
63
77
  *
64
- * `email` is an exact-match lookup rather than a search, and that is the point: answering "is this one
65
- * address blocked" should not require paging a list of every other person who ever unsubscribed. A
66
- * prefix or substring search would turn the endpoint into a way to enumerate the list a page at a time
67
- * while looking like a lookup.
78
+ * **No address, and an unknown key is refused.** A query string is written to every request log between
79
+ * the client and the Worker, so looking one address up is {@link SuppressionLookupRequest}, a `POST`
80
+ * with the address in its body. Strict rather than stripping, so a client still sending `?email=` is
81
+ * told so with a 400 instead of being handed the whole list as though it were the match.
68
82
  */
69
83
  const SuppressionsQuery = z.object({
70
84
  reason: SuppressionReason.optional().describe("Filter to one reason — hard bounce, complaint, unsubscribe, manual."),
71
- email: AddressFilter.optional().describe("Look one address up, exactly. Answers `is this person blocked` without disclosing anybody else."),
85
+ active: z.enum(["true", "false"]).describe("`true` or `false`.").transform((value) => value === "true").optional().describe("`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."),
72
86
  cursor: Cursor,
73
87
  limit: Limit
74
- }).describe("The suppression-list query: what to filter by, which address to look up, and where to resume.");
88
+ }).strict().describe("The suppression-list query: what to filter by and where to resume. To look one address up, POST it to `/suppressions/lookup`.");
75
89
  /**
76
90
  * Block an address by hand.
77
91
  *
@@ -87,7 +101,16 @@ const SuppressRequest = z.object({
87
101
  detail: z.string().min(1).max(200).optional().describe("Why you are blocking it, in your own words. Stored verbatim on the row and in the audit trail."),
88
102
  expiresAt: z.iso.datetime().optional().describe("When the block lifts, as an ISO-8601 instant. **Must be in the future** — checked in the handler against its injected clock rather than here, because a schema reading the wall clock would ignore the clock the route was given. Absent blocks permanently; a time-boxed block expires on its own rather than waiting for somebody to remember it. A past instant is refused because the send path decides purely on `expiresAt <= now`, so backdating one is exactly equivalent to lifting the block — an act this route's scope deliberately does not confer.")
89
103
  }).describe("Add one address to the global suppression list, as a manual block.");
104
+ /**
105
+ * Look one address up.
106
+ *
107
+ * An exact match rather than a search, and that is the point: answering "is this one address blocked"
108
+ * should not require paging a list of every other person who ever unsubscribed, and a prefix or substring
109
+ * search would enumerate the list a page at a time while looking like a lookup. A body because a query
110
+ * string is written to every request log between the client and the Worker.
111
+ */
112
+ const SuppressionLookupRequest = z.object({ email: AddressFilter.describe("The address to look up, matched exactly against the stored key. Answers `is this person blocked` without disclosing anybody else.") }).strict().describe("Look one address up on the global suppression list.");
90
113
  /** Unblock an address — the undo of {@link SuppressRequest}, and of a bounce, complaint, or opt-out. */
91
114
  const UnsuppressRequest = z.object({ email: AddressFilter.describe("The address to unblock, matched exactly against the stored key.") }).describe("Remove one address from the global suppression list, re-opening sending to it.");
92
115
  //#endregion
93
- export { CallbackTokenParam, JobIdParam, JobsQuery, SuppressRequest, SuppressionsQuery, UnsubscribeQuery, UnsuppressRequest };
116
+ export { CallbackTokenParam, JobIdParam, JobsQuery, SuppressRequest, SuppressionLookupRequest, SuppressionsQuery, UnsubscribeForm, UnsuppressRequest };
@@ -2,7 +2,7 @@
2
2
  // SPDX-License-Identifier: MIT
3
3
  import type { z } from "zod";
4
4
  import { EmailJob } from "../data/emailJob";
5
- import type { EmailJobStatus } from "../data/enums";
5
+ import type { EmailJobStatus, TemplateCategory } from "../data/enums";
6
6
  import type { EmailDatabase } from "../data/tables";
7
7
  /**
8
8
  * Reading the send log: the queries behind the two `email:jobs:read` routes, and `sentSince` below.
@@ -31,6 +31,10 @@ import type { EmailDatabase } from "../data/tables";
31
31
  export interface JobListFilter {
32
32
  /** One lifecycle state, or every state when absent. */
33
33
  status?: EmailJobStatus;
34
+ /** One template id, exactly, or every template when absent. */
35
+ template?: string;
36
+ /** One category, or both when absent. */
37
+ category?: TemplateCategory;
34
38
  /** The previous page's `nextCursor`. A malformed one is a first page. */
35
39
  cursor?: string;
36
40
  /** How many rows to return, clamped into range. */
@@ -43,7 +47,7 @@ export interface JobPage {
43
47
  /** Where the next page starts, or null at the end of the list. */
44
48
  nextCursor: string | null;
45
49
  }
46
- /** One page of jobs, newest first, optionally filtered to one status. */
50
+ /** One page of jobs, newest first, optionally filtered to one status, template and category. */
47
51
  export declare function listJobs(db: EmailDatabase, filter: JobListFilter): Promise<JobPage>;
48
52
  /** One job by id, or undefined. The caller decides what a miss means. */
49
53
  export declare function getJob(db: EmailDatabase, jobId: string): Promise<EmailJob | undefined>;
@@ -59,8 +63,7 @@ export declare function getJob(db: EmailDatabase, jobId: string): Promise<EmailJ
59
63
  *
60
64
  * ## Two axes, because a template is not always one message
61
65
  *
62
- * It was `(to, template)` alone, and that could not finish its only intended consumer (pithy-sh/pithy#382).
63
- * Six account notices ride one `operationalNotice` to the same addresses, so the template id does not
66
+ * `(to, template)` alone cannot answer every send decision. Six account notices ride one `operationalNotice` to the same addresses, so the template id does not
64
67
  * separate them; `correlation` is the enqueue-side discriminator that does. See {@link SentSubject} for
65
68
  * why the two are a union and not three optional fields.
66
69
  *
@@ -83,8 +86,8 @@ export declare function getJob(db: EmailDatabase, jobId: string): Promise<EmailJ
83
86
  * - **`subject`.** Rendered content, and the temptation is specific: it is the only per-row string that
84
87
  * distinguishes two messages sharing a template, so a caller needing that discrimination would match
85
88
  * on it. That match breaks on a copy edit, silently, in the direction of sending again. Discriminating
86
- * two notices was the enqueue side's problem and now has an enqueue-side answer — `correlation`
87
- * (#382) — rather than a rendered string exported to be string-matched.
89
+ * two notices is the enqueue side's problem and has an enqueue-side answer, `correlation`, rather than
90
+ * a rendered string exported to be string-matched.
88
91
  * - **`messageId`, `error`, `bounceCode`.** The provider's own words. A provider error routinely embeds
89
92
  * the recipient, which is why the list view carries `failed` rather than the text.
90
93
  *
@@ -126,11 +129,11 @@ export type SentSummary = z.output<typeof SentSummary>;
126
129
  * Which messages are being asked about — one of the two indexed axes, and the type admits no third
127
130
  * answer.
128
131
  *
129
- * **`(to, template)`** is the original question: has this template already gone to this person. It runs
132
+ * **`(to, template)`** is the plain question: has this template already gone to this person. It runs
130
133
  * on `(recipientKey, template, createdAt)`.
131
134
  *
132
- * **`correlation`** is the question a template carrying more than one kind of message needs
133
- * (pithy-sh/pithy#382): has *this thing* already been said. Six account notices ride one
135
+ * **`correlation`** is the question a template carrying more than one kind of message needs:
136
+ * has *this thing* already been said. Six account notices ride one
134
137
  * `operationalNotice` to the same addresses, so the template id cannot separate them and the address is
135
138
  * a proxy for the account only while one person belongs to one account. It runs on
136
139
  * `(correlation, createdAt)`.
@@ -1 +1 @@
1
- {"version":3,"file":"read.d.ts","sourceRoot":"","sources":["../../src/jobs/read.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAC7B,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AACpD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAEpD;;;;;;;;;;;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ACzB,CAAC;AAEF,iEAAiE;AACjE,MAAM,WAAW,OAAO;IACtB,kEAAkE;IAClE,KAAK,EAAE,WAAW,EAAE,CAAC;IACrB,+GAA+G;IAC/G,SAAS,EAAE,OAAO,CAAC;CACpB;AAED;;;;;;;;;;;;GAYG;AACH,wBAAsB,SAAS,CAAC,EAAE,EAAE,aAAa,EAAE,MAAM,EAAE,UAAU,GAAG,OAAO,CAAC,OAAO,CAAC,CAqCvF"}
package/dist/jobs/read.js CHANGED
@@ -21,12 +21,14 @@ function jobCursor(raw) {
21
21
  id: String(cursor.id)
22
22
  };
23
23
  }
24
- /** One page of jobs, newest first, optionally filtered to one status. */
24
+ /** One page of jobs, newest first, optionally filtered to one status, template and category. */
25
25
  async function listJobs(db, filter) {
26
26
  const limit = pageLimit(filter.limit);
27
27
  const after = jobCursor(filter.cursor);
28
28
  let query = db.selectFrom("pithyEmailJobs").selectAll().orderBy("createdAt", "desc").orderBy("id", "desc").limit(limit + 1);
29
29
  if (filter.status) query = query.where("status", "=", filter.status);
30
+ if (filter.template !== void 0) query = query.where("template", "=", filter.template);
31
+ if (filter.category !== void 0) query = query.where("category", "=", filter.category);
30
32
  if (after) query = query.where((eb) => eb.or([eb("createdAt", "<", after.sort), eb.and([eb("createdAt", "=", after.sort), eb("id", "<", after.id)])]));
31
33
  const jobs = (await query.execute()).map((row) => EmailJob.parse(row));
32
34
  return toPage(jobs, limit, (job) => ({
@@ -51,8 +53,7 @@ async function getJob(db, jobId) {
51
53
  *
52
54
  * ## Two axes, because a template is not always one message
53
55
  *
54
- * It was `(to, template)` alone, and that could not finish its only intended consumer (pithy-sh/pithy#382).
55
- * Six account notices ride one `operationalNotice` to the same addresses, so the template id does not
56
+ * `(to, template)` alone cannot answer every send decision. Six account notices ride one `operationalNotice` to the same addresses, so the template id does not
56
57
  * separate them; `correlation` is the enqueue-side discriminator that does. See {@link SentSubject} for
57
58
  * why the two are a union and not three optional fields.
58
59
  *
@@ -75,8 +76,8 @@ async function getJob(db, jobId) {
75
76
  * - **`subject`.** Rendered content, and the temptation is specific: it is the only per-row string that
76
77
  * distinguishes two messages sharing a template, so a caller needing that discrimination would match
77
78
  * on it. That match breaks on a copy edit, silently, in the direction of sending again. Discriminating
78
- * two notices was the enqueue side's problem and now has an enqueue-side answer — `correlation`
79
- * (#382) — rather than a rendered string exported to be string-matched.
79
+ * two notices is the enqueue side's problem and has an enqueue-side answer, `correlation`, rather than
80
+ * a rendered string exported to be string-matched.
80
81
  * - **`messageId`, `error`, `bounceCode`.** The provider's own words. A provider error routinely embeds
81
82
  * the recipient, which is why the list view carries `failed` rather than the text.
82
83
  *
@@ -0,0 +1,15 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import type { Migration } from "kysely/migration";
4
+ /**
5
+ * The send log filtered by template or by category, newest first.
6
+ *
7
+ * `GET {base}/jobs?template=…` and `?category=…` page `pithy_email_jobs` on `(createdAt, id)` under one equality.
8
+ * Without an index led by the filtered column, SQLite walks `pithyEmailJobsCreatedIdx` and tests every job the
9
+ * project ever queued, and a template nobody has sent in a year is the whole table. `createdAt` second, so the
10
+ * filtered page is read in order and stops at the limit.
11
+ *
12
+ * **Appended, never folded into `0001`.** The email capability has shipped, so its table is history.
13
+ */
14
+ export declare const email_0002_job_filters: Migration;
15
+ //# sourceMappingURL=0002_job_filters.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"0002_job_filters.d.ts","sourceRoot":"","sources":["../../src/migrations/0002_job_filters.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAElD;;;;;;;;;GASG;AACH,eAAO,MAAM,sBAAsB,EAAE,SAkBpC,CAAC"}
@@ -0,0 +1,25 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ //#region src/migrations/0002_job_filters.ts
4
+ /**
5
+ * The send log filtered by template or by category, newest first.
6
+ *
7
+ * `GET {base}/jobs?template=…` and `?category=…` page `pithy_email_jobs` on `(createdAt, id)` under one equality.
8
+ * Without an index led by the filtered column, SQLite walks `pithyEmailJobsCreatedIdx` and tests every job the
9
+ * project ever queued, and a template nobody has sent in a year is the whole table. `createdAt` second, so the
10
+ * filtered page is read in order and stops at the limit.
11
+ *
12
+ * **Appended, never folded into `0001`.** The email capability has shipped, so its table is history.
13
+ */
14
+ const email_0002_job_filters = {
15
+ up: async (db) => {
16
+ await db.schema.createIndex("pithyEmailJobsTemplateCreatedIdx").on("pithyEmailJobs").columns(["template", "createdAt"]).execute();
17
+ await db.schema.createIndex("pithyEmailJobsCategoryCreatedIdx").on("pithyEmailJobs").columns(["category", "createdAt"]).execute();
18
+ },
19
+ down: async (db) => {
20
+ await db.schema.dropIndex("pithyEmailJobsCategoryCreatedIdx").execute();
21
+ await db.schema.dropIndex("pithyEmailJobsTemplateCreatedIdx").execute();
22
+ }
23
+ };
24
+ //#endregion
25
+ export { email_0002_job_filters };
@@ -99,11 +99,22 @@ export interface EnqueueInput {
99
99
  /**
100
100
  * The address a recipient's answer should go to, when it is not `fromAddress`.
101
101
  *
102
- * `@pithy-sh/support` is what this is for: a reply is sent as the adopter's onboarded sending
103
- * identity (Cloudflare validates the `From` domain against exactly what was onboarded) while the
104
- * conversation has to come back to the support inbox, which is usually a different subdomain.
102
+ * `@pithy-sh/support` sets it on every reply, so the customer's answer comes back to the support inbox
103
+ * whichever address the reply was sent {@link from}.
105
104
  */
106
105
  replyTo?: string;
106
+ /**
107
+ * The sender of this one message, when it is not the capability's `fromAddress` and `fromName`.
108
+ *
109
+ * Refused unless `address` is one the composing capability declared: {@link EnqueueDeps.claimedFrom}, which
110
+ * only {@link import("../capability").EmailCapability.enqueueAs} fills, and the plain `enqueue` leaves empty.
111
+ * That keeps a capability to the addresses it declared; it is not a boundary against Worker code, which can
112
+ * call `enqueueAs` itself. Cloudflare sends only from onboarded domains. `name` falls back to `fromName`.
113
+ *
114
+ * The job is sent from exactly this address. A domain Email Service cannot send from fails the job with
115
+ * the domain named; no other sender is tried.
116
+ */
117
+ from?: EnqueueFrom;
107
118
  /**
108
119
  * The `Message-ID` this job answers, angle brackets included — the `In-Reply-To` header.
109
120
  *
@@ -133,11 +144,23 @@ export interface EnqueueInput {
133
144
  */
134
145
  consentSubject?: ConsentSubject;
135
146
  }
147
+ /** A per-message sender: an address the composing capability claims, and an optional display name. */
148
+ export interface EnqueueFrom {
149
+ /** The address the message is sent from. Must be on {@link EnqueueDeps.claimedFrom}. */
150
+ address: string;
151
+ /** The display name. Absent sends under the capability's `fromName`. */
152
+ name?: string;
153
+ }
136
154
  /** Dependencies enqueue needs: the database, the from identity, optional send-Workflow binding, time, ids. */
137
155
  export interface EnqueueDeps {
138
156
  db: EmailDatabase;
139
157
  fromAddress: string;
140
158
  fromName: string;
159
+ /**
160
+ * The addresses a per-message {@link EnqueueInput.from} may name, supplied by the capability composing the
161
+ * call. Absent or empty refuses every override.
162
+ */
163
+ claimedFrom?: readonly string[];
141
164
  theme: EmailTheme;
142
165
  /**
143
166
  * Where the words for a locale come from — the composed project's catalogs.
@@ -1 +1 @@
1
- {"version":3,"file":"enqueue.d.ts","sourceRoot":"","sources":["../../src/send/enqueue.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,mCAAmC,CAAC;AACvF,OAAO,KAAK,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,sCAAsC,CAAC;AAKtF,OAAO,KAAK,EAAE,cAAc,EAAE,QAAQ,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AACjF,OAAO,KAAK,EAAE,aAAa,EAAE,wBAAwB,EAAE,MAAM,gBAAgB,CAAC;AAG9E,OAAO,EAAE,KAAK,kBAAkB,EAAmC,MAAM,uBAAuB,CAAC;AACjG,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAMrD;;;;;;;;;;;;;;;;;;;GAmBG;AAE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AAiB,CAAC,EAAE,iBAAiB,CAAC;IACtC;;;;OAIG;IACH,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OAuCG;IACH,OAAO,EAAE,MAAM,CAAC;CACjB;AAsCD,oGAAoG;AACpG,wBAAsB,YAAY,CAAC,IAAI,EAAE,WAAW,EAAE,KAAK,EAAE,YAAY,GAAG,OAAO,CAAC,aAAa,CAAC,CAmLjG"}
@@ -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,