@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.
- package/README.md +2 -0
- package/dist/bounce/handler.d.ts +22 -2
- package/dist/bounce/handler.d.ts.map +1 -1
- package/dist/bounce/handler.js +60 -17
- package/dist/capability.d.ts +12 -0
- package/dist/capability.d.ts.map +1 -1
- package/dist/capability.js +25 -15
- package/dist/crypto/signingKey.d.ts.map +1 -1
- package/dist/crypto/token.d.ts +43 -11
- package/dist/crypto/token.d.ts.map +1 -1
- package/dist/crypto/token.js +158 -55
- package/dist/http/callbacks.d.ts +8 -3
- package/dist/http/callbacks.d.ts.map +1 -1
- package/dist/http/callbacks.js +67 -12
- package/dist/http/guards.d.ts.map +1 -1
- package/dist/http/guards.js +9 -0
- package/dist/http/routes.d.ts +8 -4
- package/dist/http/routes.d.ts.map +1 -1
- package/dist/http/routes.js +67 -21
- package/dist/http/schemas.d.ts +41 -13
- package/dist/http/schemas.d.ts.map +1 -1
- package/dist/http/schemas.js +38 -15
- package/dist/jobs/read.d.ts +12 -9
- package/dist/jobs/read.d.ts.map +1 -1
- package/dist/jobs/read.js +6 -5
- package/dist/migrations/0002_job_filters.d.ts +15 -0
- package/dist/migrations/0002_job_filters.d.ts.map +1 -0
- package/dist/migrations/0002_job_filters.js +25 -0
- package/dist/send/enqueue.d.ts +26 -3
- package/dist/send/enqueue.d.ts.map +1 -1
- package/dist/send/enqueue.js +25 -2
- package/dist/send/errorMapping.d.ts +15 -20
- package/dist/send/errorMapping.d.ts.map +1 -1
- package/dist/send/errorMapping.js +33 -27
- package/dist/send/runSend.d.ts +2 -2
- package/dist/send/runSend.d.ts.map +1 -1
- package/dist/send/runSend.js +1 -1
- package/dist/send/suppression.d.ts +4 -0
- package/dist/send/suppression.d.ts.map +1 -1
- package/dist/send/suppression.js +4 -0
- package/dist/templates/engine.d.ts +1 -1
- package/dist/templates/engine.js +1 -1
- package/dist/version.generated.d.ts +1 -1
- package/dist/version.generated.d.ts.map +1 -1
- package/dist/version.generated.js +1 -1
- package/package.json +3 -3
- package/src/bounce/handler.ts +84 -32
- package/src/capability.ts +47 -27
- package/src/crypto/signingKey.ts +4 -2
- package/src/crypto/token.ts +225 -92
- package/src/http/callbacks.ts +100 -32
- package/src/http/guards.ts +9 -0
- package/src/http/routes.ts +96 -28
- package/src/http/schemas.ts +75 -24
- package/src/jobs/read.ts +14 -9
- package/src/migrations/0002_job_filters.ts +35 -0
- package/src/send/enqueue.ts +52 -5
- package/src/send/errorMapping.ts +45 -38
- package/src/send/runSend.ts +6 -7
- package/src/send/suppression.ts +13 -0
- package/src/templates/engine.ts +1 -1
- package/src/version.generated.ts +1 -1
package/src/http/routes.ts
CHANGED
|
@@ -41,7 +41,14 @@ import {
|
|
|
41
41
|
EmailSuppressResponse,
|
|
42
42
|
EmailUnsuppressResponse,
|
|
43
43
|
} from "./responses";
|
|
44
|
-
import {
|
|
44
|
+
import {
|
|
45
|
+
JobIdParam,
|
|
46
|
+
JobsQuery,
|
|
47
|
+
SuppressionLookupRequest,
|
|
48
|
+
SuppressionsQuery,
|
|
49
|
+
SuppressRequest,
|
|
50
|
+
UnsuppressRequest,
|
|
51
|
+
} from "./schemas";
|
|
45
52
|
import { jobDetailView, jobListView, suppressionView } from "./view";
|
|
46
53
|
|
|
47
54
|
/**
|
|
@@ -51,6 +58,7 @@ import { jobDetailView, jobListView, suppressionView } from "./view";
|
|
|
51
58
|
* GET /email/jobs/:id → one job in full (control-plane: email:jobs:read) param
|
|
52
59
|
* POST /email/jobs/:id/retry → queue it again (control-plane: email:jobs:retry) param
|
|
53
60
|
* GET /email/suppressions → who we won't mail (control-plane: email:suppressions:read) query
|
|
61
|
+
* POST /email/suppressions/lookup → is this one blocked (control-plane: email:suppressions:read) json
|
|
54
62
|
* POST /email/suppressions → block an address (control-plane: email:suppressions:write) json
|
|
55
63
|
* POST /email/suppressions/remove → unblock one (control-plane: email:suppressions:delete) json
|
|
56
64
|
*
|
|
@@ -71,10 +79,13 @@ import { jobDetailView, jobListView, suppressionView } from "./view";
|
|
|
71
79
|
* parsing every response would spend a validation pass on rows this Worker just read, and would turn a
|
|
72
80
|
* shape mistake into a 500 in production rather than a red build.
|
|
73
81
|
*
|
|
74
|
-
* **
|
|
75
|
-
*
|
|
76
|
-
*
|
|
77
|
-
*
|
|
82
|
+
* **An address never travels in a URL.** Removal is `POST /suppressions/remove`, not
|
|
83
|
+
* `DELETE /suppressions/:email`, and a lookup is `POST /suppressions/lookup`, not `?email=`. A path or a
|
|
84
|
+
* query string is in every access log, every proxy, every trace, and every referrer between the client
|
|
85
|
+
* and the Worker. The record is personal data whether or not it is a person's current address, so it
|
|
86
|
+
* travels in a body. Testers' `POST /remove` is the same call made for the same reason, and
|
|
87
|
+
* `addressedParameters` in `@pithy-sh/core/src/openapi/document` fails the kit's build on a route that
|
|
88
|
+
* declares one in its URL.
|
|
78
89
|
*/
|
|
79
90
|
|
|
80
91
|
/** What every route this capability mounts declares: its path, its strategy, and the scope it checks. */
|
|
@@ -100,6 +111,12 @@ export const EMAIL_ADMIN_ROUTES: readonly EmailRouteDeclaration[] = [
|
|
|
100
111
|
{ method: "GET", path: "/jobs/:id", strategy: "control-plane", scope: EMAIL_JOBS_READ_SCOPE },
|
|
101
112
|
{ method: "POST", path: "/jobs/:id/retry", strategy: "control-plane", scope: EMAIL_JOBS_RETRY_SCOPE },
|
|
102
113
|
{ method: "GET", path: "/suppressions", strategy: "control-plane", scope: EMAIL_SUPPRESSIONS_READ_SCOPE },
|
|
114
|
+
{
|
|
115
|
+
method: "POST",
|
|
116
|
+
path: "/suppressions/lookup",
|
|
117
|
+
strategy: "control-plane",
|
|
118
|
+
scope: EMAIL_SUPPRESSIONS_READ_SCOPE,
|
|
119
|
+
},
|
|
103
120
|
{ method: "POST", path: "/suppressions", strategy: "control-plane", scope: EMAIL_SUPPRESSIONS_WRITE_SCOPE },
|
|
104
121
|
{
|
|
105
122
|
method: "POST",
|
|
@@ -182,6 +199,33 @@ function caller(c: Context<PithyHonoEnv>): ControlPlaneContext {
|
|
|
182
199
|
return context;
|
|
183
200
|
}
|
|
184
201
|
|
|
202
|
+
/** What one read of the suppression list records about itself. The rows never go in. */
|
|
203
|
+
interface SuppressionsReadMetadata {
|
|
204
|
+
reason: string | null;
|
|
205
|
+
lookup: boolean;
|
|
206
|
+
active: boolean | null;
|
|
207
|
+
returned: number;
|
|
208
|
+
paged: boolean;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* Audit a read of the suppression list. The heaviest read in the capability: this database is global, so
|
|
213
|
+
* a page of it is a page of every environment's bounces, complaints, and opt-outs. Audited with whether
|
|
214
|
+
* it was a lookup or a walk, because those are very different events.
|
|
215
|
+
*/
|
|
216
|
+
async function auditSuppressionsRead(c: Context<PithyHonoEnv>, metadata: SuppressionsReadMetadata): Promise<void> {
|
|
217
|
+
const who = caller(c);
|
|
218
|
+
await c.var.emit({
|
|
219
|
+
action: EmailAuditActions.suppressionsRead,
|
|
220
|
+
outcome: "success",
|
|
221
|
+
actorType: "control-plane",
|
|
222
|
+
actorId: who.subject,
|
|
223
|
+
resourceType: "email_suppression",
|
|
224
|
+
resourceId: null,
|
|
225
|
+
metadata: { connectionId: who.connectionId, ...metadata },
|
|
226
|
+
});
|
|
227
|
+
}
|
|
228
|
+
|
|
185
229
|
/** Register the email management sub-router. Composed alongside the public callbacks. */
|
|
186
230
|
export function registerEmailAdminRoutes(options: EmailAdminRoutesOptions): (app: Hono<PithyHonoEnv>) => void {
|
|
187
231
|
const base = options.basePath;
|
|
@@ -218,6 +262,8 @@ export function registerEmailAdminRoutes(options: EmailAdminRoutesOptions): (app
|
|
|
218
262
|
metadata: {
|
|
219
263
|
connectionId: who.connectionId,
|
|
220
264
|
status: query.status ?? null,
|
|
265
|
+
template: query.template ?? null,
|
|
266
|
+
category: query.category ?? null,
|
|
221
267
|
returned: page.items.length,
|
|
222
268
|
paged: Boolean(query.cursor),
|
|
223
269
|
},
|
|
@@ -318,7 +364,7 @@ export function registerEmailAdminRoutes(options: EmailAdminRoutesOptions): (app
|
|
|
318
364
|
app.get(
|
|
319
365
|
`${base}/suppressions`,
|
|
320
366
|
describeRoute({
|
|
321
|
-
summary: "Page through the suppression list
|
|
367
|
+
summary: "Page through the suppression list.",
|
|
322
368
|
verification: "control-plane",
|
|
323
369
|
scopes: [EMAIL_SUPPRESSIONS_READ_SCOPE],
|
|
324
370
|
responses: { 200: EmailSuppressionsResponse },
|
|
@@ -327,27 +373,49 @@ export function registerEmailAdminRoutes(options: EmailAdminRoutesOptions): (app
|
|
|
327
373
|
validate("query", SuppressionsQuery),
|
|
328
374
|
async (c) => {
|
|
329
375
|
const query = c.req.valid("query");
|
|
330
|
-
const who = caller(c);
|
|
331
376
|
const now = clock();
|
|
332
|
-
const page = await listSuppressions(suppressions(c), query);
|
|
377
|
+
const page = await listSuppressions(suppressions(c), { ...query, now });
|
|
378
|
+
|
|
379
|
+
await auditSuppressionsRead(c, {
|
|
380
|
+
reason: query.reason ?? null,
|
|
381
|
+
lookup: false,
|
|
382
|
+
active: query.active ?? null,
|
|
383
|
+
returned: page.items.length,
|
|
384
|
+
paged: Boolean(query.cursor),
|
|
385
|
+
});
|
|
333
386
|
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
387
|
+
return c.json({
|
|
388
|
+
suppressions: page.items.map((row) => suppressionView(row, now)),
|
|
389
|
+
nextCursor: page.nextCursor,
|
|
390
|
+
} satisfies EmailSuppressionsResponse);
|
|
391
|
+
},
|
|
392
|
+
);
|
|
393
|
+
|
|
394
|
+
app.post(
|
|
395
|
+
`${base}/suppressions/lookup`,
|
|
396
|
+
describeRoute({
|
|
397
|
+
summary: "Look one address up on the suppression list.",
|
|
398
|
+
verification: "control-plane",
|
|
399
|
+
scopes: [EMAIL_SUPPRESSIONS_READ_SCOPE],
|
|
400
|
+
responses: { 200: EmailSuppressionsResponse },
|
|
401
|
+
}),
|
|
402
|
+
requireControlPlane(EMAIL_SUPPRESSIONS_READ_SCOPE),
|
|
403
|
+
validate("json", SuppressionLookupRequest),
|
|
404
|
+
async (c) => {
|
|
405
|
+
const input = c.req.valid("json");
|
|
406
|
+
const now = clock();
|
|
407
|
+
// `listSuppressions` matches the normalized key exactly, and `email` is unique, so this is the
|
|
408
|
+
// row or none: the listing's envelope, so a client renders it with the schema it already holds.
|
|
409
|
+
const page = await listSuppressions(suppressions(c), { email: input.email, now });
|
|
410
|
+
|
|
411
|
+
// The address stays out of the trail: the event records that one address was asked about and
|
|
412
|
+
// whether it was found, as the listing's lookup always did.
|
|
413
|
+
await auditSuppressionsRead(c, {
|
|
414
|
+
reason: null,
|
|
415
|
+
lookup: true,
|
|
416
|
+
active: null,
|
|
417
|
+
returned: page.items.length,
|
|
418
|
+
paged: false,
|
|
351
419
|
});
|
|
352
420
|
|
|
353
421
|
return c.json({
|
|
@@ -393,17 +461,17 @@ export function registerEmailAdminRoutes(options: EmailAdminRoutesOptions): (app
|
|
|
393
461
|
message: "That expiry has already passed, so it would not block anything.",
|
|
394
462
|
action:
|
|
395
463
|
"Give a future instant, or omit `expiresAt` to block permanently. To lift an existing block, use the remove route — it requires `email:suppressions:delete`.",
|
|
396
|
-
detail: `refused suppression
|
|
464
|
+
detail: `refused suppression with expiresAt ${expiresAt.toISOString()} at ${now.toISOString()}`,
|
|
397
465
|
});
|
|
398
466
|
}
|
|
399
467
|
|
|
400
468
|
const current = (await listSuppressions(db, { email, limit: 1 })).items[0];
|
|
401
469
|
if (current && current.reason !== "manual") {
|
|
402
470
|
throw new ConflictError({
|
|
403
|
-
message:
|
|
471
|
+
message: `That address is already suppressed as a ${current.reason}, which this route may not overwrite.`,
|
|
404
472
|
action:
|
|
405
473
|
"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.",
|
|
406
|
-
detail: `refused manual suppression over an existing ${current.reason}
|
|
474
|
+
detail: `refused manual suppression over an existing ${current.reason}`,
|
|
407
475
|
});
|
|
408
476
|
}
|
|
409
477
|
|
package/src/http/schemas.ts
CHANGED
|
@@ -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
|
|
@@ -22,7 +22,7 @@ import { EmailJobStatus, SuppressionReason } from "../data/enums";
|
|
|
22
22
|
|
|
23
23
|
/**
|
|
24
24
|
* The characters a callback token path segment may contain: the base64url alphabet, plus `.` — the
|
|
25
|
-
* token's own
|
|
25
|
+
* token's own segment separator, and the `.png` suffix mail clients append to an
|
|
26
26
|
* open-pixel URL (which `handleOpen` strips before verifying). Deliberately not a strict base64url
|
|
27
27
|
* check: that would 400 every tracking pixel.
|
|
28
28
|
*/
|
|
@@ -30,7 +30,7 @@ const TOKEN_SEGMENT = /^[A-Za-z0-9._-]+$/;
|
|
|
30
30
|
|
|
31
31
|
/**
|
|
32
32
|
* The `:token` path parameter every callback route carries. A shape and size bound only — the ceiling
|
|
33
|
-
* is generous enough for a click token whose
|
|
33
|
+
* is generous enough for a click token whose sealed claims embed a long destination URL, so no link we
|
|
34
34
|
* mint can exceed it, while an unbounded segment can no longer reach the verifier.
|
|
35
35
|
*/
|
|
36
36
|
export const CallbackTokenParam = z
|
|
@@ -40,26 +40,40 @@ export const CallbackTokenParam = z
|
|
|
40
40
|
.min(1)
|
|
41
41
|
.max(4096)
|
|
42
42
|
.regex(TOKEN_SEGMENT)
|
|
43
|
-
.describe("The
|
|
43
|
+
.describe("The sealed callback token from the path, optionally with the open-pixel `.png` suffix."),
|
|
44
44
|
})
|
|
45
45
|
.describe("The path parameter carrying a click/open/unsubscribe callback token.");
|
|
46
46
|
export type CallbackTokenParam = z.output<typeof CallbackTokenParam>;
|
|
47
47
|
|
|
48
|
+
/** One form field as a client may send it: a value, or a repeated field's values. Anything else reads as absent. */
|
|
49
|
+
const FormField = z
|
|
50
|
+
.union([z.string(), z.array(z.string())])
|
|
51
|
+
.optional()
|
|
52
|
+
.catch(undefined);
|
|
53
|
+
|
|
48
54
|
/**
|
|
49
|
-
* The
|
|
50
|
-
*
|
|
51
|
-
*
|
|
55
|
+
* The form body of an unsubscribe `POST`: what a mail client's one-click unsubscribe sends (RFC 8058 fixes it to
|
|
56
|
+
* `List-Unsubscribe=One-Click`), what the confirmation page's button sends, and what the app's own preferences flow
|
|
57
|
+
* sends with a `reason`.
|
|
58
|
+
*
|
|
59
|
+
* **Nothing in it can refuse the opt-out.** Every field is optional, a repeated field or one of the wrong type reads
|
|
60
|
+
* as absent or as its first value, and an over-long reason is truncated by the handler rather than refused. The
|
|
61
|
+
* token is the only gate; a body is never a reason somebody stays subscribed.
|
|
62
|
+
*
|
|
63
|
+
* The reason travels in the body because it is the recipient's own words, and a query string is written to every
|
|
64
|
+
* request log between the client and the Worker. The route reads no query at all.
|
|
52
65
|
*/
|
|
53
|
-
export const
|
|
66
|
+
export const UnsubscribeForm = z
|
|
54
67
|
.object({
|
|
55
|
-
|
|
56
|
-
.
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
68
|
+
"List-Unsubscribe": FormField.describe(
|
|
69
|
+
"`One-Click` from a mail client's RFC 8058 one-click unsubscribe. Accepted and not otherwise read.",
|
|
70
|
+
),
|
|
71
|
+
reason: FormField.describe(
|
|
72
|
+
"Why the recipient opted out; the first value is kept, truncated to 200 characters before it is stored.",
|
|
73
|
+
),
|
|
60
74
|
})
|
|
61
|
-
.describe("The optional
|
|
62
|
-
export type
|
|
75
|
+
.describe("The optional form fields an unsubscribe POST accepts.");
|
|
76
|
+
export type UnsubscribeForm = z.output<typeof UnsubscribeForm>;
|
|
63
77
|
|
|
64
78
|
/**
|
|
65
79
|
* Where the next page starts. Opaque, and a malformed one is a first page rather than a 400 — the
|
|
@@ -137,32 +151,51 @@ export const JobsQuery = z
|
|
|
137
151
|
status: EmailJobStatus.optional().describe(
|
|
138
152
|
"Filter to one lifecycle state — `failed` is the pane this capability exists for. Absent lists every state.",
|
|
139
153
|
),
|
|
154
|
+
template: z
|
|
155
|
+
.string()
|
|
156
|
+
.min(1)
|
|
157
|
+
.max(128)
|
|
158
|
+
.optional()
|
|
159
|
+
.describe(
|
|
160
|
+
"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.",
|
|
161
|
+
),
|
|
162
|
+
category: TemplateCategory.optional().describe(
|
|
163
|
+
"Filter to one category: `transactional` or `marketing`. Absent lists both.",
|
|
164
|
+
),
|
|
140
165
|
cursor: Cursor,
|
|
141
166
|
limit: Limit,
|
|
142
167
|
})
|
|
143
|
-
.describe("The send-log query: which state to filter by, and where to resume.");
|
|
168
|
+
.describe("The send-log query: which state, template and category to filter by, and where to resume.");
|
|
144
169
|
export type JobsQuery = z.output<typeof JobsQuery>;
|
|
145
170
|
|
|
146
171
|
/**
|
|
147
172
|
* The suppression list query.
|
|
148
173
|
*
|
|
149
|
-
*
|
|
150
|
-
*
|
|
151
|
-
*
|
|
152
|
-
*
|
|
174
|
+
* **No address, and an unknown key is refused.** A query string is written to every request log between
|
|
175
|
+
* the client and the Worker, so looking one address up is {@link SuppressionLookupRequest}, a `POST`
|
|
176
|
+
* with the address in its body. Strict rather than stripping, so a client still sending `?email=` is
|
|
177
|
+
* told so with a 400 instead of being handed the whole list as though it were the match.
|
|
153
178
|
*/
|
|
154
179
|
export const SuppressionsQuery = z
|
|
155
180
|
.object({
|
|
156
181
|
reason: SuppressionReason.optional().describe(
|
|
157
182
|
"Filter to one reason — hard bounce, complaint, unsubscribe, manual.",
|
|
158
183
|
),
|
|
159
|
-
|
|
160
|
-
"
|
|
161
|
-
|
|
184
|
+
active: z
|
|
185
|
+
.enum(["true", "false"])
|
|
186
|
+
.describe("`true` or `false`.")
|
|
187
|
+
.transform((value) => value === "true")
|
|
188
|
+
.optional()
|
|
189
|
+
.describe(
|
|
190
|
+
"`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.",
|
|
191
|
+
),
|
|
162
192
|
cursor: Cursor,
|
|
163
193
|
limit: Limit,
|
|
164
194
|
})
|
|
165
|
-
.
|
|
195
|
+
.strict()
|
|
196
|
+
.describe(
|
|
197
|
+
"The suppression-list query: what to filter by and where to resume. To look one address up, POST it to `/suppressions/lookup`.",
|
|
198
|
+
);
|
|
166
199
|
export type SuppressionsQuery = z.output<typeof SuppressionsQuery>;
|
|
167
200
|
|
|
168
201
|
/**
|
|
@@ -194,6 +227,24 @@ export const SuppressRequest = z
|
|
|
194
227
|
.describe("Add one address to the global suppression list, as a manual block.");
|
|
195
228
|
export type SuppressRequest = z.output<typeof SuppressRequest>;
|
|
196
229
|
|
|
230
|
+
/**
|
|
231
|
+
* Look one address up.
|
|
232
|
+
*
|
|
233
|
+
* An exact match rather than a search, and that is the point: answering "is this one address blocked"
|
|
234
|
+
* should not require paging a list of every other person who ever unsubscribed, and a prefix or substring
|
|
235
|
+
* search would enumerate the list a page at a time while looking like a lookup. A body because a query
|
|
236
|
+
* string is written to every request log between the client and the Worker.
|
|
237
|
+
*/
|
|
238
|
+
export const SuppressionLookupRequest = z
|
|
239
|
+
.object({
|
|
240
|
+
email: AddressFilter.describe(
|
|
241
|
+
"The address to look up, matched exactly against the stored key. Answers `is this person blocked` without disclosing anybody else.",
|
|
242
|
+
),
|
|
243
|
+
})
|
|
244
|
+
.strict()
|
|
245
|
+
.describe("Look one address up on the global suppression list.");
|
|
246
|
+
export type SuppressionLookupRequest = z.output<typeof SuppressionLookupRequest>;
|
|
247
|
+
|
|
197
248
|
/** Unblock an address — the undo of {@link SuppressRequest}, and of a bounce, complaint, or opt-out. */
|
|
198
249
|
export const UnsuppressRequest = z
|
|
199
250
|
.object({
|
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
|
-
*
|
|
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
|
|
137
|
-
*
|
|
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
|
|
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
|
-
*
|
|
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
|
+
};
|
package/src/send/enqueue.ts
CHANGED
|
@@ -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`
|
|
113
|
-
*
|
|
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:
|
|
374
|
-
fromName:
|
|
420
|
+
fromAddress: from.fromAddress,
|
|
421
|
+
fromName: from.fromName,
|
|
375
422
|
subject,
|
|
376
423
|
template: input.template,
|
|
377
424
|
category: template.category,
|