@pithy-sh/email 0.7.0 → 0.8.1

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 (46) hide show
  1. package/README.md +8 -0
  2. package/dist/capability.d.ts +2 -2
  3. package/dist/capability.d.ts.map +1 -1
  4. package/dist/capability.js +23 -2
  5. package/dist/consent/consent.d.ts +57 -0
  6. package/dist/consent/consent.d.ts.map +1 -0
  7. package/dist/consent/consent.js +135 -0
  8. package/dist/data/emailEvent.d.ts +1 -1
  9. package/dist/data/emailEvent.d.ts.map +1 -1
  10. package/dist/data/emailEvent.js +2 -1
  11. package/dist/data/emailJob.d.ts +6 -2
  12. package/dist/data/emailJob.d.ts.map +1 -1
  13. package/dist/data/emailJob.js +8 -3
  14. package/dist/data/emailSuppression.d.ts +1 -1
  15. package/dist/data/emailSuppression.d.ts.map +1 -1
  16. package/dist/data/emailSuppression.js +2 -1
  17. package/dist/data/tables.d.ts +4 -4
  18. package/dist/http/guards.d.ts +2 -2
  19. package/dist/http/guards.d.ts.map +1 -1
  20. package/dist/http/guards.js +12 -0
  21. package/dist/processing/activities.d.ts +9 -0
  22. package/dist/processing/activities.d.ts.map +1 -0
  23. package/dist/processing/activities.js +40 -0
  24. package/dist/purge/contribution.d.ts +27 -0
  25. package/dist/purge/contribution.d.ts.map +1 -0
  26. package/dist/purge/contribution.js +67 -0
  27. package/dist/send/enqueue.d.ts +26 -7
  28. package/dist/send/enqueue.d.ts.map +1 -1
  29. package/dist/send/enqueue.js +36 -13
  30. package/dist/templates/messages.d.ts +1 -2
  31. package/dist/templates/messages.d.ts.map +1 -1
  32. package/dist/templates/messages.js +7 -10
  33. package/dist/version.generated.d.ts +1 -1
  34. package/dist/version.generated.js +1 -1
  35. package/package.json +3 -3
  36. package/src/capability.ts +33 -7
  37. package/src/consent/consent.ts +183 -0
  38. package/src/data/emailEvent.ts +2 -1
  39. package/src/data/emailJob.ts +21 -8
  40. package/src/data/emailSuppression.ts +2 -1
  41. package/src/http/guards.ts +14 -2
  42. package/src/processing/activities.ts +41 -0
  43. package/src/purge/contribution.ts +83 -0
  44. package/src/send/enqueue.ts +62 -24
  45. package/src/templates/messages.ts +10 -13
  46. package/src/version.generated.ts +1 -1
@@ -0,0 +1,183 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import type { D1Database } from "@cloudflare/workers-types";
5
+ import { normalizeAddress } from "@pithy-sh/core/src/address/address";
6
+ import type { ConsentPurpose } from "@pithy-sh/core/src/consent/purpose";
7
+ import type { ConsentGrant, ConsentReader, ConsentSubject, ConsentWithdrawal } from "@pithy-sh/core/src/consent/reader";
8
+ import { SQLiteBoolean, SQLiteDate } from "@pithy-sh/core/src/data/codecs";
9
+ import { emailDatabase, emailSuppressionDatabase } from "../data/tables";
10
+
11
+ /**
12
+ * Email under consent.
13
+ *
14
+ * Email does two things a law may require consent for: it tracks opens and clicks, and it sends marketing mail. It
15
+ * declares each as a purpose, and when `@pithy-sh/consent` is composed it asks before doing either. Transactional
16
+ * mail is never gated: a sign-in link answers something the person just did. Without consent composed, email
17
+ * gates nothing, and `pithy doctor` names that tracking runs with no consent record behind it.
18
+ */
19
+
20
+ /** Marketing mail: a template whose category is `marketing`. */
21
+ export const EMAIL_MARKETING_PURPOSE = "email.marketing";
22
+
23
+ /** Open and click tracking, on any template that would track. */
24
+ export const EMAIL_TRACKING_PURPOSE = "email.tracking";
25
+
26
+ /** The purposes email declares. Version 1 of each; a change to what they allow is a version bump here. */
27
+ export const EMAIL_CONSENT_PURPOSES: readonly ConsentPurpose[] = [
28
+ {
29
+ id: EMAIL_MARKETING_PURPOSE,
30
+ summary: "Send me news and offers by email.",
31
+ noticeVersion: 1,
32
+ classes: ["pii"],
33
+ explicit: false,
34
+ minimumMethod: "click",
35
+ writtenWithdrawal: false,
36
+ },
37
+ {
38
+ id: EMAIL_TRACKING_PURPOSE,
39
+ summary: "Tell the sender when I open their email or follow a link in it.",
40
+ noticeVersion: 1,
41
+ classes: ["pii"],
42
+ explicit: false,
43
+ minimumMethod: "click",
44
+ writtenWithdrawal: false,
45
+ },
46
+ ];
47
+
48
+ /** What the consent gate decided for one enqueue. */
49
+ export interface ConsentGate {
50
+ /** The purpose that withholds the message, or `null` when it may be sent. */
51
+ readonly withheld: string | null;
52
+ /** Whether open and click tracking may run. */
53
+ readonly tracking: boolean;
54
+ }
55
+
56
+ /** Ungated: no consent capability is composed, so nothing is withheld and tracking is left to the template. */
57
+ const UNGATED: ConsentGate = { withheld: null, tracking: true };
58
+
59
+ /**
60
+ * Decide, for one message, what consent allows. With no reader, nothing is gated. With one, a marketing message
61
+ * needs the subject's consent to `email.marketing` and tracking needs `email.tracking`; a message with no subject
62
+ * has nobody whose consent could be shown, so it is withheld if marketing and untracked either way. Transactional
63
+ * mail is never withheld.
64
+ */
65
+ export async function consentGate(
66
+ reader: ConsentReader | null | undefined,
67
+ subject: ConsentSubject | undefined,
68
+ marketing: boolean,
69
+ ): Promise<ConsentGate> {
70
+ if (!reader) return UNGATED;
71
+ const holds = async (purpose: string) => subject !== undefined && (await reader.hasConsent(subject, purpose));
72
+ const withheld = marketing && !(await holds(EMAIL_MARKETING_PURPOSE)) ? EMAIL_MARKETING_PURPOSE : null;
73
+ return { withheld, tracking: await holds(EMAIL_TRACKING_PURPOSE) };
74
+ }
75
+
76
+ /** The detail a withdrawal's suppression carries — and the only suppression a later grant lifts. */
77
+ const WITHDRAWAL_DETAIL = `consent withdrawn: ${EMAIL_MARKETING_PURPOSE}`;
78
+
79
+ /** The bindings the listener writes through. */
80
+ function bindingOf(env: Record<string, unknown>, name: string): D1Database | undefined {
81
+ const binding = env[name];
82
+ return typeof binding === "object" && binding !== null ? (binding as D1Database) : undefined;
83
+ }
84
+
85
+ /**
86
+ * Keep email in step with a withdrawal.
87
+ *
88
+ * - **`email.marketing`**: the address is suppressed for marketing — an `unsubscribe`, which blocks elective mail
89
+ * and never a sign-in link — so the suppression list and the consent record never disagree. The suppression it
90
+ * leaves is permanent, because it is what holds a message already scheduled. An address already suppressed for
91
+ * good keeps its row: a hard bounce is stronger than an unsubscribe and is never downgraded. A time-boxed row is
92
+ * not left to expire under the withdrawal: a lapsed one, or a live time-boxed unsubscribe, is replaced by the
93
+ * withdrawal's own; a live time-boxed bounce, complaint or manual keeps its reason and becomes permanent.
94
+ * - **`email.tracking`**: mail already queued to the address stops tracking. It was decided at enqueue, and the
95
+ * person has since said no.
96
+ *
97
+ * A visitor has no address to act on; their next enqueue is gated by the record instead.
98
+ */
99
+ export async function emailConsentWithdrawn(withdrawal: ConsentWithdrawal): Promise<void> {
100
+ const address = await withdrawal.address();
101
+ if (address === null) return;
102
+ const now = new Date();
103
+ if (withdrawal.purpose === EMAIL_MARKETING_PURPOSE) {
104
+ const suppressions = bindingOf(withdrawal.env, "EMAIL_SUPPRESSIONS");
105
+ if (!suppressions) return;
106
+ await emailSuppressionDatabase(suppressions)
107
+ .insertInto("pithyEmailSuppressions")
108
+ .values({
109
+ email: normalizeAddress(address),
110
+ reason: "unsubscribe",
111
+ jobId: null,
112
+ environment: null,
113
+ detail: WITHDRAWAL_DETAIL,
114
+ expiresAt: null,
115
+ createdAt: SQLiteDate.encode(now),
116
+ })
117
+ .onConflict((conflict) =>
118
+ conflict
119
+ .column("email")
120
+ .doUpdateSet((eb) => {
121
+ // The withdrawal takes the row when nothing stronger stands in it: the row has lapsed, or it is a
122
+ // time-boxed unsubscribe. A live time-boxed bounce, complaint or manual keeps its reason and its detail,
123
+ // and loses only its expiry, so it never weakens and the withdrawal never lapses with it.
124
+ const takes = eb.or([
125
+ eb("pithyEmailSuppressions.expiresAt", "<=", SQLiteDate.encode(now)),
126
+ eb("pithyEmailSuppressions.reason", "=", "unsubscribe"),
127
+ ]);
128
+ return {
129
+ reason: eb
130
+ .case()
131
+ .when(takes)
132
+ .then("unsubscribe" as const)
133
+ .else(eb.ref("pithyEmailSuppressions.reason"))
134
+ .end(),
135
+ detail: eb.case().when(takes).then(WITHDRAWAL_DETAIL).else(eb.ref("pithyEmailSuppressions.detail")).end(),
136
+ jobId: eb.case().when(takes).then(null).else(eb.ref("pithyEmailSuppressions.jobId")).end(),
137
+ environment: eb.case().when(takes).then(null).else(eb.ref("pithyEmailSuppressions.environment")).end(),
138
+ expiresAt: null,
139
+ };
140
+ })
141
+ // A permanent row already blocks marketing for good, whatever its reason, so it is never touched.
142
+ .where("pithyEmailSuppressions.expiresAt", "is not", null),
143
+ )
144
+ .execute();
145
+ return;
146
+ }
147
+ if (withdrawal.purpose === EMAIL_TRACKING_PURPOSE) {
148
+ const db = bindingOf(withdrawal.env, "DB");
149
+ if (!db) return;
150
+ await emailDatabase(db)
151
+ .updateTable("pithyEmailJobs")
152
+ .set({
153
+ openTracking: SQLiteBoolean.encode(false),
154
+ clickTracking: SQLiteBoolean.encode(false),
155
+ updatedAt: SQLiteDate.encode(now),
156
+ })
157
+ .where("recipientKey", "=", normalizeAddress(address))
158
+ .where("status", "in", ["pending", "scheduled", "undispatched"])
159
+ .execute();
160
+ }
161
+ }
162
+
163
+ /**
164
+ * Keep email in step with a grant: the other half of {@link emailConsentWithdrawn}.
165
+ *
166
+ * Granting `email.marketing` again lifts the suppression a withdrawal wrote — an `unsubscribe` whose detail is the
167
+ * withdrawal's own sentence — so the person's yes is heard. Nothing else is ever lifted: a bounce, a complaint, an
168
+ * unsubscribe from a mail's own link, and an operator's manual suppression all stand, because none of them was the
169
+ * consent record's to begin with.
170
+ */
171
+ export async function emailConsentGranted(grant: ConsentGrant): Promise<void> {
172
+ if (grant.purpose !== EMAIL_MARKETING_PURPOSE) return;
173
+ const address = await grant.address();
174
+ if (address === null) return;
175
+ const suppressions = bindingOf(grant.env, "EMAIL_SUPPRESSIONS");
176
+ if (!suppressions) return;
177
+ await emailSuppressionDatabase(suppressions)
178
+ .deleteFrom("pithyEmailSuppressions")
179
+ .where("email", "=", normalizeAddress(address))
180
+ .where("reason", "=", "unsubscribe")
181
+ .where("detail", "=", WITHDRAWAL_DETAIL)
182
+ .execute();
183
+ }
@@ -2,6 +2,7 @@
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
4
  import { SQLiteDate } from "@pithy-sh/core/src/data/codecs";
5
+ import { pii } from "@pithy-sh/core/src/privacy/classes";
5
6
  import { z } from "zod";
6
7
  import { EmailEventType } from "./enums";
7
8
 
@@ -14,7 +15,7 @@ export const EmailEvent = z
14
15
  .object({
15
16
  id: z.number().int().describe("Surrogate primary key, autoincremented by SQLite."),
16
17
  jobId: z.string().describe("The `pithy_email_jobs.id` this event belongs to."),
17
- recipient: z.string().describe("The recipient address the event is about."),
18
+ recipient: pii(z.string().describe("The recipient address the event is about.")),
18
19
  type: EmailEventType.describe(
19
20
  "What happened: sent, open, click, bounce, complaint, unsubscribe, suppressed, or failed.",
20
21
  ),
@@ -3,6 +3,7 @@
3
3
 
4
4
  import { SQLiteBoolean, SQLiteDate, sqliteJson } from "@pithy-sh/core/src/data/codecs";
5
5
  import { Locale } from "@pithy-sh/core/src/i18n/locale";
6
+ import { pii } from "@pithy-sh/core/src/privacy/classes";
6
7
  import { z } from "zod";
7
8
  import { EmailJobStatus, SendMode, TemplateCategory } from "./enums";
8
9
 
@@ -41,14 +42,18 @@ export const EmailJob = z
41
42
  .describe(
42
43
  "UUID primary key. Text, not autoincrement, so a job id embedded in a tracking link cannot be enumerated.",
43
44
  ),
44
- toAddress: z
45
- .string()
46
- .describe("The recipient's email address. Lowercased and checked against the suppression list before sending."),
47
- recipientKey: z
48
- .string()
49
- .describe(
50
- "The recipient under `normalizeAddress` — the one form every comparison in the kit is against, and the only column anything matches a recipient on. `toAddress` deliberately keeps what the caller typed, because an operator diagnosing a send needs to see the string that was actually addressed; that makes it useless as a key, since `Ada@example.com` and `ada@example.com` are one mailbox and two rows. Doing the folding in SQL instead would not work: SQLite's `lower()` is ASCII-only while `normalizeAddress` is `toLowerCase()`, so the two disagree on exactly the addresses nobody tests with. The same value `pithy_email_events.recipient` is keyed on, so a job and its events agree on who the person is.",
51
- ),
45
+ toAddress: pii(
46
+ z
47
+ .string()
48
+ .describe("The recipient's email address. Lowercased and checked against the suppression list before sending."),
49
+ ),
50
+ recipientKey: pii(
51
+ z
52
+ .string()
53
+ .describe(
54
+ "The recipient under `normalizeAddress` — the one form every comparison in the kit is against, and the only column anything matches a recipient on. `toAddress` deliberately keeps what the caller typed, because an operator diagnosing a send needs to see the string that was actually addressed; that makes it useless as a key, since `Ada@example.com` and `ada@example.com` are one mailbox and two rows. Doing the folding in SQL instead would not work: SQLite's `lower()` is ASCII-only while `normalizeAddress` is `toLowerCase()`, so the two disagree on exactly the addresses nobody tests with. The same value `pithy_email_events.recipient` is keyed on, so a job and its events agree on who the person is.",
55
+ ),
56
+ ),
52
57
  fromAddress: z.string().describe("The sender address. Must use a domain onboarded onto Cloudflare Email Service."),
53
58
  fromName: z.string().describe("The sender display name recipients see in their inbox."),
54
59
  subject: z.string().describe("The rendered subject line."),
@@ -136,3 +141,11 @@ export const EmailJob = z
136
141
  })
137
142
  .describe("One email job in `pithy_email_jobs` — the auditable, retryable record of a single email.");
138
143
  export type EmailJob = z.output<typeof EmailJob>;
144
+
145
+ /** A person's email address as the email tables hold it: marked `pii`, so it never compiles into a log field. */
146
+ export type PersonalAddress = EmailJob["toAddress"];
147
+
148
+ /** Mark an address the caller handed in as the personal data it is, for a row that stores it. */
149
+ export function personalAddress(value: string): PersonalAddress {
150
+ return value as PersonalAddress;
151
+ }
@@ -2,6 +2,7 @@
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
4
  import { SQLiteDate } from "@pithy-sh/core/src/data/codecs";
5
+ import { pii } from "@pithy-sh/core/src/privacy/classes";
5
6
  import { z } from "zod";
6
7
  import { SuppressionReason } from "./enums";
7
8
 
@@ -13,7 +14,7 @@ import { SuppressionReason } from "./enums";
13
14
  export const EmailSuppression = z
14
15
  .object({
15
16
  id: z.number().int().describe("Surrogate primary key, autoincremented by SQLite."),
16
- email: z.string().describe("The suppressed address, lowercased. Uniquely indexed — one row per address."),
17
+ email: pii(z.string().describe("The suppressed address, lowercased. Uniquely indexed — one row per address.")),
17
18
  reason: SuppressionReason.describe(
18
19
  "Why the address is suppressed: hard bounce, complaint, unsubscribe, or manual.",
19
20
  ),
@@ -1,7 +1,7 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
- import type { AdminRoute } from "@pithy-sh/core/src/controlPlane/discovery/adminRoute";
4
+ import type { AdminRouteDeclaration } from "@pithy-sh/core/src/controlPlane/discovery/adminRoute";
5
5
  import type { ControlPlaneScope } from "@pithy-sh/core/src/controlPlane/scope/scope";
6
6
 
7
7
  /**
@@ -112,42 +112,54 @@ export const EMAIL_CONTROL_PLANE_SCOPES: readonly ControlPlaneScope[] = [
112
112
  * The summaries say what the operation is *for*. A client renders these next to a button somebody is
113
113
  * about to press on a real person's mail.
114
114
  */
115
- export function emailAdminRoutes(basePath: string): AdminRoute[] {
115
+ export function emailAdminRoutes(basePath: string): AdminRouteDeclaration[] {
116
116
  return [
117
117
  {
118
118
  method: "GET",
119
+ operation: "jobs.list",
119
120
  path: `${basePath}/jobs`,
120
121
  scope: EMAIL_JOBS_READ_SCOPE,
122
+ kind: "reads",
121
123
  summary: "The send log, newest first, filtered by status. Recipients are masked in the list.",
122
124
  },
123
125
  {
124
126
  method: "GET",
127
+ operation: "jobs.read",
125
128
  path: `${basePath}/jobs/:id`,
126
129
  scope: EMAIL_JOBS_READ_SCOPE,
130
+ kind: "reads",
127
131
  summary: "One job in full — the recipient, the subject, and why it failed. Never the template variables.",
128
132
  },
129
133
  {
130
134
  method: "POST",
135
+ operation: "jobs.retry",
131
136
  path: `${basePath}/jobs/:id/retry`,
132
137
  scope: EMAIL_JOBS_RETRY_SCOPE,
138
+ kind: "sends",
133
139
  summary: "Queue a failed job again with a fresh attempt budget. Sends real mail.",
134
140
  },
135
141
  {
136
142
  method: "GET",
143
+ operation: "suppressions.list",
137
144
  path: `${basePath}/suppressions`,
138
145
  scope: EMAIL_SUPPRESSIONS_READ_SCOPE,
146
+ kind: "reads",
139
147
  summary: "Addresses this project will not send to, and why. Global — every environment shares it.",
140
148
  },
141
149
  {
142
150
  method: "POST",
151
+ operation: "suppressions.add",
143
152
  path: `${basePath}/suppressions`,
144
153
  scope: EMAIL_SUPPRESSIONS_WRITE_SCOPE,
154
+ kind: "writes",
145
155
  summary: "Block an address by hand, permanently or until a date. Recorded as a manual block.",
146
156
  },
147
157
  {
148
158
  method: "POST",
159
+ operation: "suppressions.remove",
149
160
  path: `${basePath}/suppressions/remove`,
150
161
  scope: EMAIL_SUPPRESSIONS_DELETE_SCOPE,
162
+ kind: "deletes",
151
163
  summary: "Unblock an address. Re-opens sending to somebody who bounced, complained, or opted out.",
152
164
  },
153
165
  ];
@@ -0,0 +1,41 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import type { ProcessingActivityInput, ProcessingRecipientInput } from "@pithy-sh/core/src/processing/activity";
5
+ import { EMAIL_MARKETING_PURPOSE, EMAIL_TRACKING_PURPOSE } from "../consent/consent";
6
+
7
+ /** The mail provider every send goes through. */
8
+ const EMAIL_SERVICE: ProcessingRecipientInput = {
9
+ name: "Cloudflare Email Service",
10
+ receives: "Each recipient's address and the message sent to it.",
11
+ classes: ["pii"],
12
+ };
13
+
14
+ /**
15
+ * What email does with personal data: it sends the mail the Worker enqueues, and, under each purpose's consent,
16
+ * marketing mail and open and click tracking.
17
+ */
18
+ export const EMAIL_PROCESSING: readonly ProcessingActivityInput[] = [
19
+ {
20
+ id: "email.delivery",
21
+ purpose: "Send the mail a person's account needs — sign-in links, codes, notices — and keep its history.",
22
+ classes: ["pii"],
23
+ legalBasis: "contract",
24
+ recipients: [EMAIL_SERVICE],
25
+ },
26
+ {
27
+ id: "email.marketing",
28
+ purpose: "Send news and offers by email to a person who agreed to receive them.",
29
+ classes: ["pii"],
30
+ legalBasis: "consent",
31
+ consentPurpose: EMAIL_MARKETING_PURPOSE,
32
+ recipients: [EMAIL_SERVICE],
33
+ },
34
+ {
35
+ id: "email.tracking",
36
+ purpose: "Record when a person opens a message or follows a link in it, for a person who agreed to it.",
37
+ classes: ["pii"],
38
+ legalBasis: "consent",
39
+ consentPurpose: EMAIL_TRACKING_PURPOSE,
40
+ },
41
+ ];
@@ -0,0 +1,83 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import type { D1Database } from "@cloudflare/workers-types";
5
+ import { normalizeAddress } from "@pithy-sh/core/src/address/address";
6
+ import { exportRows, purgeBinding, type RetainingPurgeContribution } from "@pithy-sh/core/src/capability/purge";
7
+ import { EmailEvent } from "../data/emailEvent";
8
+ import { EmailJob } from "../data/emailJob";
9
+ import { EmailSuppression } from "../data/emailSuppression";
10
+ import { emailDatabase, emailSuppressionDatabase } from "../data/tables";
11
+
12
+ /**
13
+ * What a person's purge means for `@pithy-sh/email` (#814): **nothing is erased, and the export says so and why.**
14
+ *
15
+ * A suppression has to outlive the person. It is the record that an address bounced, complained or asked not to be
16
+ * mailed, and the list is checked before every send: erase the row and the next send — a newsletter to an address
17
+ * that unsubscribed — goes out, because nothing remembers that it should not. So this contribution **retains**, and
18
+ * the log of mail sent to the address stays beside it as the delivery record a bounce or a complaint is read
19
+ * against. The purge records the step as retained with the basis below, and erases no row.
20
+ *
21
+ * **Found by address.** Email stores no user id: the suppression list and the log are keyed by the address, in
22
+ * `normalizeAddress`'s form. The step reads the account's address (`PurgeContext.address`); with none to read there
23
+ * is nothing to find.
24
+ *
25
+ * **Never a message's payload, and never a tracked link.** A job's payload is the template's variables, and a sign-in
26
+ * mail's variables are the link that signs the person in; a click event's URL can be that link. The export carries
27
+ * what was sent, when and how it went, and leaves both out.
28
+ */
29
+
30
+ /** The one sentence the purge records with this step. */
31
+ export const EMAIL_PURGE_SUMMARY = "Keeps the user's address on the suppression list, and the log of mail sent to it.";
32
+
33
+ /** Why, in the sentence the person is told. */
34
+ export const EMAIL_RETENTION_BASIS =
35
+ "Kept so your unsubscribe holds: the address stays on the list of addresses not to mail, with the record of what was sent to it.";
36
+
37
+ /** The user contribution `email()` declares, over its two D1 bindings. */
38
+ export function emailUserPurge(database = "DB", suppressions = "EMAIL_SUPPRESSIONS"): RetainingPurgeContribution {
39
+ return {
40
+ subject: "user",
41
+ summary: EMAIL_PURGE_SUMMARY,
42
+ retain: { basis: EMAIL_RETENTION_BASIS },
43
+ export: async (context) => {
44
+ const read = await context.address?.();
45
+ if (!read) return { suppressions: [], jobs: [], events: [] };
46
+ const address = normalizeAddress(read);
47
+ const log = emailDatabase(purgeBinding<D1Database>(context.env, database, "email"));
48
+ const list = emailSuppressionDatabase(purgeBinding<D1Database>(context.env, suppressions, "email"));
49
+ const [suppressed, jobs, events] = await Promise.all([
50
+ list.selectFrom("pithyEmailSuppressions").selectAll().where("email", "=", address).execute(),
51
+ log
52
+ .selectFrom("pithyEmailJobs")
53
+ .selectAll()
54
+ .where("recipientKey", "=", address)
55
+ .orderBy("createdAt")
56
+ .orderBy("id")
57
+ .execute(),
58
+ log
59
+ .selectFrom("pithyEmailEvents")
60
+ .selectAll()
61
+ .where("recipient", "=", address)
62
+ .orderBy("createdAt")
63
+ .orderBy("id")
64
+ .execute(),
65
+ ]);
66
+ return {
67
+ suppressions: exportRows(suppressed.map((row) => EmailSuppression.parse(row))),
68
+ jobs: exportRows(
69
+ jobs.map((row) => {
70
+ const { payload: _variables, ...job } = EmailJob.parse(row);
71
+ return job;
72
+ }),
73
+ ),
74
+ events: exportRows(
75
+ events.map((row) => {
76
+ const { linkUrl: _link, ...event } = EmailEvent.parse(row);
77
+ return event;
78
+ }),
79
+ ),
80
+ };
81
+ },
82
+ };
83
+ }
@@ -2,10 +2,12 @@
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
4
  import { normalizeAddress } from "@pithy-sh/core/src/address/address";
5
+ import type { ConsentReader, ConsentSubject } from "@pithy-sh/core/src/consent/reader";
5
6
  import type { MeterCharge, MeterSubject } from "@pithy-sh/core/src/entitlement/meter";
6
7
  import { isLocale } from "@pithy-sh/core/src/i18n/locale";
8
+ import { consentGate } from "../consent/consent";
7
9
  import type { EmailJob } from "../data/emailJob";
8
- import { EmailJob as EmailJobSchema } from "../data/emailJob";
10
+ import { EmailJob as EmailJobSchema, personalAddress } from "../data/emailJob";
9
11
  import type { EmailJobStatus, SendMode, SuppressionReason } from "../data/enums";
10
12
  import type { EmailDatabase, EmailSuppressionDatabase } from "../data/tables";
11
13
  import { EmailInvalidPayloadError } from "../error/errors";
@@ -23,7 +25,7 @@ import { blockingSuppression } from "./suppression";
23
25
  * `scheduled` and `timezone` jobs are left for the every-minute scheduler to pick up. The payload is
24
26
  * validated against the template schema here, so a bad call fails at enqueue, not mid-send.
25
27
  *
26
- * **Suppression is consulted here too, and no caller asks for it** (pithy-sh/pithy#355). A blocked
28
+ * **Suppression is consulted here too, and no caller asks for it**. A blocked
27
29
  * recipient never becomes a queued send: the row is born `suppressed`, no Workflow is started, and the
28
30
  * reason comes back on the result. The point is not a second gate — `runSend` is and stays the
29
31
  * authority, because whether an address is blocked is a question about the instant of sending and a
@@ -42,7 +44,7 @@ import { blockingSuppression } from "./suppression";
42
44
  * The Workflow binding used to start a send (Cloudflare `Workflow.create`). At enqueue it sends a batch
43
45
  * of one; the scheduler's fan-out starts one instance per batch through the same binding.
44
46
  *
45
- * `id` names the instance being created, and **every dispatcher passes one** (pithy-sh/pithy#342): the
47
+ * `id` names the instance being created, and **every dispatcher passes one**: the
46
48
  * scheduler passes its batch's, an enqueue passes the one it just stamped on the row, and a retry passes
47
49
  * the one it minted to replace the failed batch's. It is optional here only because the platform allows
48
50
  * omitting it, and omitting it is what made an immediate send unattributable to any instance — so the
@@ -88,7 +90,7 @@ export interface EnqueueInput {
88
90
  /**
89
91
  * What this message is *about*, when the template id does not say it on its own.
90
92
  *
91
- * The discriminator for a template that carries more than one kind of message (pithy-sh/pithy#382).
93
+ * The discriminator for a template that carries more than one kind of message.
92
94
  * `sentSince` matches on it, so a caller deciding whether to send — or whether to send a *correction* —
93
95
  * can tell two messages apart that share a template and a recipient. Opaque: nothing here parses it,
94
96
  * renders it, or puts it on a header or a link.
@@ -132,6 +134,14 @@ export interface EnqueueInput {
132
134
  * enqueue past the period's quota throws `payments/quota_exceeded` and writes no job.
133
135
  */
134
136
  subject?: MeterSubject;
137
+ /**
138
+ * Whose consent this message is sent under, when `@pithy-sh/consent` is composed: the recipient's account,
139
+ * or the visitor id they consented under. A `marketing` template is sent only to a subject consenting to
140
+ * `email.marketing`, and opens and clicks are tracked only for one consenting to `email.tracking`. Omitted, a
141
+ * marketing message is withheld and nothing is tracked, because nobody's consent can be shown. Transactional mail
142
+ * is never gated, and without consent composed this is ignored.
143
+ */
144
+ consentSubject?: ConsentSubject;
135
145
  }
136
146
 
137
147
  /** Dependencies enqueue needs: the database, the from identity, optional send-Workflow binding, time, ids. */
@@ -165,12 +175,16 @@ export interface EnqueueDeps {
165
175
  * request's env. Absent when no provider is composed, and then nothing is counted.
166
176
  */
167
177
  meter?: (charge: MeterCharge) => Promise<void>;
178
+ /**
179
+ * The composed consent reader, or absent when no consent capability is composed — and then nothing is
180
+ * gated.
181
+ */
182
+ consent?: ConsentReader | null;
168
183
  now: Date;
169
184
  /** Generate a job id (a UUID in production). */
170
185
  newId: () => string;
171
186
  /**
172
- * Mint the id of the batch this enqueue dispatches — **the send Workflow instance's id**
173
- * (pithy-sh/pithy#342). Defaults to {@link mintBatchId}; injected only so a test can name it.
187
+ * Mint the id of the batch this enqueue dispatches — **the send Workflow instance's id**. Defaults to {@link mintBatchId}; injected only so a test can name it.
174
188
  */
175
189
  newBatchId?: () => string;
176
190
  }
@@ -183,7 +197,7 @@ export interface EnqueueResult {
183
197
  *
184
198
  * `pending` and `scheduled` both mean a send is on its way. `suppressed` means the address is
185
199
  * blocked. **`undispatched` means this composition binds no send Workflow**, so nothing was started
186
- * and nothing is coming while it stays that way (pithy-sh/pithy#410): a caller that renders "check
200
+ * and nothing is coming while it stays that way: a caller that renders "check
187
201
  * your inbox" off it is reporting a delivery that cannot happen. It is the one status here that
188
202
  * describes the *deployment* rather than the message — and the scheduler drains those rows once a
189
203
  * host exists, so it is not the end of the job.
@@ -198,9 +212,15 @@ export interface EnqueueResult {
198
212
  * operator's next move depends on.
199
213
  */
200
214
  suppressionReason?: SuppressionReason;
215
+ /**
216
+ * The consent purpose that withheld this message, when consent is composed and the subject does not hold it —
217
+ * `email.marketing`. The row is born `suppressed` and nothing is sent. Absent for every message consent
218
+ * did not withhold.
219
+ */
220
+ consentWithheld?: string;
201
221
  /**
202
222
  * The **enqueue-time** render — the sentence this call wrote to `pithy_email_jobs.subject`, in the
203
- * recipient's language, and the value the row is born with (pithy-sh/pithy#443).
223
+ * recipient's language, and the value the row is born with.
204
224
  *
205
225
  * **For the caller that has to say what it queued.** Enqueuing is what a surface does; auditing it is
206
226
  * what a surface with an administrative trail also does. Without this, that caller had to render the
@@ -271,9 +291,18 @@ export async function enqueueEmail(deps: EnqueueDeps, input: EnqueueInput): Prom
271
291
  * agreeing is what makes a hard bounce withhold an invitation while an unsubscribe does not. A caller
272
292
  * cannot influence this and is not asked to: it is the template's own declaration.
273
293
  */
274
- const blocked: SuppressionReason | null = deps.suppressionDb
294
+ const suppressed: SuppressionReason | null = deps.suppressionDb
275
295
  ? await blockingSuppression(deps.suppressionDb, input.to, deps.now, templateKind(input.template))
276
296
  : null;
297
+ /**
298
+ * What consent allows, when it is composed: a marketing message to a subject not consenting to it is
299
+ * withheld like a suppressed one, and tracking runs only for a subject consenting to it. Transactional mail is
300
+ * never withheld. With no consent composed the gate passes everything.
301
+ */
302
+ const marketing = template.category === "marketing";
303
+ const gate = await consentGate(deps.consent, input.consentSubject, marketing);
304
+ const withheld = suppressed === null ? gate.withheld : null;
305
+ const blocked = suppressed !== null || withheld !== null;
277
306
  // The match key, on the same normalization the suppression list is written and read under. The row
278
307
  // keeps the address as the caller typed it in `toAddress` — an operator diagnosing a send needs the
279
308
  // string that was actually addressed — and carries this beside it as `recipientKey`, which is what
@@ -286,7 +315,7 @@ export async function enqueueEmail(deps: EnqueueDeps, input: EnqueueInput): Prom
286
315
  // else is left for the scheduler to claim.
287
316
  const sender = !blocked && mode === "immediate" ? deps.sender : undefined;
288
317
  /**
289
- * An immediate job with nothing to dispatch it on (pithy-sh/pithy#410).
318
+ * An immediate job with nothing to dispatch it on.
290
319
  *
291
320
  * A missing binding is a **configuration fact known at compose time**, not a transient failure, and
292
321
  * the two used to be recorded identically: both left the row `pending` and told the caller "on its
@@ -309,7 +338,7 @@ export async function enqueueEmail(deps: EnqueueDeps, input: EnqueueInput): Prom
309
338
  const status: EmailJobStatus = blocked ? "suppressed" : undispatchable ? "undispatched" : scheduled;
310
339
  /**
311
340
  * The batch this enqueue is about to start — named here, before the row exists, because the row has to
312
- * carry it (pithy-sh/pithy#342).
341
+ * carry it.
313
342
  *
314
343
  * Without it the row is born naming nobody, and a row naming nobody is stranded by definition: the
315
344
  * scheduler's safety net claims any `pending` job older than `graceMs` and starts a *second* send
@@ -337,11 +366,10 @@ export async function enqueueEmail(deps: EnqueueDeps, input: EnqueueInput): Prom
337
366
  await deps.meter({ subject: input.subject, meter: "emails", amount: 1, now: deps.now });
338
367
  }
339
368
 
340
- const marketing = template.category === "marketing";
341
369
  const job: EmailJob = {
342
370
  id: deps.newId(),
343
- toAddress: input.to,
344
- recipientKey: recipient,
371
+ toAddress: personalAddress(input.to),
372
+ recipientKey: personalAddress(recipient),
345
373
  fromAddress: deps.fromAddress,
346
374
  fromName: deps.fromName,
347
375
  subject,
@@ -368,17 +396,19 @@ export async function enqueueEmail(deps: EnqueueDeps, input: EnqueueInput): Prom
368
396
  // The same shape as `renderLocale` on the send side, and for the same reason.
369
397
  locale: isLocale(input.locale ?? "") ? (input.locale ?? null) : null,
370
398
  correlation: input.correlation ?? null,
371
- openTracking: input.openTracking ?? marketing,
372
- clickTracking: input.clickTracking ?? marketing,
399
+ openTracking: (input.openTracking ?? marketing) && gate.tracking,
400
+ clickTracking: (input.clickTracking ?? marketing) && gate.tracking,
373
401
  messageId: null,
374
402
  // The same sentence `runSend` writes when it skips one, so the send log reads the same whichever
375
403
  // pass caught it — and, for the undispatchable row, the one sentence that says why it stopped
376
404
  // here. The status is the state; this column is what an operator reads next to it.
377
- error: blocked
378
- ? `recipient suppressed: ${blocked}`
379
- : undispatchable
380
- ? "no EMAIL_SENDER binding: this composition can start no send Workflow"
381
- : null,
405
+ error: suppressed
406
+ ? `recipient suppressed: ${suppressed}`
407
+ : withheld
408
+ ? `no consent: ${withheld}`
409
+ : undispatchable
410
+ ? "no EMAIL_SENDER binding: this composition can start no send Workflow"
411
+ : null,
382
412
  bounceCode: null,
383
413
  bounceType: null,
384
414
  replyTo: input.replyTo ?? null,
@@ -394,9 +424,17 @@ export async function enqueueEmail(deps: EnqueueDeps, input: EnqueueInput): Prom
394
424
  // A withheld message is on the record as an event, not merely as a status — the send log's history is
395
425
  // what an operator reads to find out that an advisory reached nobody, and a row with no event in it
396
426
  // looks exactly like a job still waiting its turn.
397
- if (blocked) {
398
- await recordEvent(deps.db, { jobId: job.id, recipient, type: "suppressed", detail: blocked }, deps.now);
399
- return { jobId: job.id, status, subject, suppressionReason: blocked };
427
+ if (suppressed) {
428
+ await recordEvent(deps.db, { jobId: job.id, recipient, type: "suppressed", detail: suppressed }, deps.now);
429
+ return { jobId: job.id, status, subject, suppressionReason: suppressed };
430
+ }
431
+ if (withheld) {
432
+ await recordEvent(
433
+ deps.db,
434
+ { jobId: job.id, recipient, type: "suppressed", detail: `consent:${withheld}` },
435
+ deps.now,
436
+ );
437
+ return { jobId: job.id, status, subject, consentWithheld: withheld };
400
438
  }
401
439
 
402
440
  // Immediate sends start the Workflow now for lowest latency, under the id the row already carries —