@pithy-sh/email 0.6.0 → 0.8.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 (59) 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.es.d.ts.map +1 -1
  33. package/dist/templates/messages.es.js +28 -0
  34. package/dist/templates/messages.js +35 -10
  35. package/dist/templates/precompiled.generated.d.ts +124 -0
  36. package/dist/templates/precompiled.generated.d.ts.map +1 -1
  37. package/dist/templates/precompiled.generated.js +1618 -0
  38. package/dist/templates/registry.d.ts.map +1 -1
  39. package/dist/templates/registry.js +106 -0
  40. package/dist/templates/samples.d.ts.map +1 -1
  41. package/dist/templates/samples.js +28 -0
  42. package/dist/version.generated.d.ts +1 -1
  43. package/dist/version.generated.js +1 -1
  44. package/package.json +3 -3
  45. package/src/capability.ts +33 -7
  46. package/src/consent/consent.ts +183 -0
  47. package/src/data/emailEvent.ts +2 -1
  48. package/src/data/emailJob.ts +21 -8
  49. package/src/data/emailSuppression.ts +2 -1
  50. package/src/http/guards.ts +14 -2
  51. package/src/processing/activities.ts +41 -0
  52. package/src/purge/contribution.ts +83 -0
  53. package/src/send/enqueue.ts +62 -24
  54. package/src/templates/messages.es.ts +41 -0
  55. package/src/templates/messages.ts +52 -11
  56. package/src/templates/precompiled.generated.ts +551 -0
  57. package/src/templates/registry.ts +159 -0
  58. package/src/templates/samples.ts +11 -0
  59. package/src/version.generated.ts +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"registry.d.ts","sourceRoot":"","sources":["../../src/templates/registry.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,KAAK,EAAE,SAAS,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AAEjE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAE5C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AAEH;oFACoF;AACpF,MAAM,WAAW,QAAQ;IACvB,0FAA0F;IAC1F,IAAI,EAAE,MAAM,CAAC;IACb,8EAA8E;IAC9E,KAAK,EAAE,MAAM,CAAC;CACf;AAED,8GAA8G;AAC9G,MAAM,WAAW,aAAa;IAC5B,qEAAqE;IACrE,EAAE,EAAE,MAAM,CAAC;IACX,+GAA+G;IAC/G,QAAQ,EAAE,gBAAgB,CAAC;IAC3B;;;;;;;;;OASG;IACH,IAAI,EAAE,SAAS,CAAC;IAChB,mGAAmG;IACnG,KAAK,EAAE,YAAY,CAAC;IACpB,kFAAkF;IAClF,OAAO,EAAE,CAAC,CAAC,OAAO,CAAC;IACnB,yEAAyE;IACzE,OAAO,EAAE,MAAM,CAAC;IAChB,yFAAyF;IACzF,IAAI,EAAE,MAAM,CAAC;IACb,kFAAkF;IAClF,IAAI,EAAE,MAAM,CAAC;IACb,uEAAuE;IACvE,KAAK,EAAE,QAAQ,EAAE,CAAC;CACnB;AAuMD;;;;;;;;;;;;;;;;GAgBG;AACH,eAAO,MAAM,wBAAwB;;;;;;;;;;;;;;;;iBA2ClC,CAAC;AACJ;;;;;;GAMG;AACH,MAAM,MAAM,wBAAwB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,wBAAwB,CAAC,CAAC;AAmEhF,0CAA0C;AAC1C,eAAO,MAAM,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,aAAa,CAgPnD,CAAC"}
1
+ {"version":3,"file":"registry.d.ts","sourceRoot":"","sources":["../../src/templates/registry.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,KAAK,EAAE,SAAS,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AAEjE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAE5C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AAEH;oFACoF;AACpF,MAAM,WAAW,QAAQ;IACvB,0FAA0F;IAC1F,IAAI,EAAE,MAAM,CAAC;IACb,8EAA8E;IAC9E,KAAK,EAAE,MAAM,CAAC;CACf;AAED,8GAA8G;AAC9G,MAAM,WAAW,aAAa;IAC5B,qEAAqE;IACrE,EAAE,EAAE,MAAM,CAAC;IACX,+GAA+G;IAC/G,QAAQ,EAAE,gBAAgB,CAAC;IAC3B;;;;;;;;;OASG;IACH,IAAI,EAAE,SAAS,CAAC;IAChB,mGAAmG;IACnG,KAAK,EAAE,YAAY,CAAC;IACpB,kFAAkF;IAClF,OAAO,EAAE,CAAC,CAAC,OAAO,CAAC;IACnB,yEAAyE;IACzE,OAAO,EAAE,MAAM,CAAC;IAChB,yFAAyF;IACzF,IAAI,EAAE,MAAM,CAAC;IACb,kFAAkF;IAClF,IAAI,EAAE,MAAM,CAAC;IACb,uEAAuE;IACvE,KAAK,EAAE,QAAQ,EAAE,CAAC;CACnB;AAmRD;;;;;;;;;;;;;;;;GAgBG;AACH,eAAO,MAAM,wBAAwB;;;;;;;;;;;;;;;;iBA2ClC,CAAC;AACJ;;;;;;GAMG;AACH,MAAM,MAAM,wBAAwB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,wBAAwB,CAAC,CAAC;AAmEhF,0CAA0C;AAC1C,eAAO,MAAM,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,aAAa,CAmUnD,CAAC"}
@@ -101,6 +101,46 @@ const DeletionCompletePayload = z.object({
101
101
  name: z.string().optional().describe("The recipient's name, for a personal greeting. Optional."),
102
102
  purgedOn: z.string().describe("The date the account's data was erased, written for the reader.")
103
103
  }).describe("Inputs for the notice that an account's data was erased — sent before the address is.");
104
+ /**
105
+ * The three notices `@pithy-sh/organization` sends when an operator changes somebody's membership through
106
+ * the control plane (#624). Each names the organization, because a person in two accounts must be able to
107
+ * tell which one changed, and none carries the operator's reason: that is the trail's, written for the
108
+ * people who answer for the account, not for the person it happened to.
109
+ */
110
+ const OrganizationMemberAddedPayload = z.object({
111
+ name: z.string().optional().describe("The recipient's name, for a personal greeting. Optional."),
112
+ organizationName: z.string().describe("The organization they were added to, by display name. Tenant text, escaped like every value."),
113
+ role: z.string().describe("The role they hold there now, as the project's catalog names it.")
114
+ }).describe("Inputs for the notice that an operator added somebody to an organization.");
115
+ const OrganizationMemberRemovedPayload = z.object({
116
+ name: z.string().optional().describe("The recipient's name, for a personal greeting. Optional."),
117
+ organizationName: z.string().describe("The organization they were removed from, by display name. Tenant text, escaped like every value.")
118
+ }).describe("Inputs for the notice that an operator removed somebody from an organization.");
119
+ const OrganizationOwnershipTransferredPayload = z.object({
120
+ name: z.string().optional().describe("The recipient's name, for a personal greeting. Optional."),
121
+ organizationName: z.string().describe("The organization they now own, by display name. Tenant text, escaped like every value.")
122
+ }).describe("Inputs for the notice that an operator made somebody the owner of an organization.");
123
+ /**
124
+ * The three notices `@pithy-sh/organization` sends an organization's owners when an operator acts on the
125
+ * organization itself (#623): it was suspended, reinstated, or deleted with a date its data is erased. Each names
126
+ * the organization. The suspension carries the operator's reason, because the suspended screen tells every member
127
+ * the owners were told why.
128
+ */
129
+ const OrganizationSuspendedPayload = z.object({
130
+ name: z.string().optional().describe("The recipient's name, for a personal greeting. Optional."),
131
+ organizationName: z.string().describe("The organization that was suspended, by display name. Tenant text, escaped like every value."),
132
+ reason: z.string().optional().describe("Why it was suspended, in the operator's words. Rendered escaped. Omitted when none was given."),
133
+ until: z.string().optional().describe("When the suspension ends by itself, written for the reader. Omitted for one with no end.")
134
+ }).describe("Inputs for the notice to an owner that their organization was suspended.");
135
+ const OrganizationReinstatedPayload = z.object({
136
+ name: z.string().optional().describe("The recipient's name, for a personal greeting. Optional."),
137
+ organizationName: z.string().describe("The organization that was reinstated, by display name. Tenant text, escaped like every value.")
138
+ }).describe("Inputs for the notice to an owner that their organization's suspension was lifted.");
139
+ const OrganizationDeletionScheduledPayload = z.object({
140
+ name: z.string().optional().describe("The recipient's name, for a personal greeting. Optional."),
141
+ organizationName: z.string().describe("The organization that was deleted, by display name. Tenant text, escaped like every value."),
142
+ purgeOn: z.string().describe("When its data will be erased, written for the reader. Restorable until then.")
143
+ }).describe("Inputs for the notice to an owner that their organization was deleted and when it will be erased.");
104
144
  /** One labeled fact in an operational notice — what makes the notice specific rather than a mood. */
105
145
  const OperationalNoticeFact = z.object({
106
146
  label: z.string().describe("What this fact is: `Environment`, `Last rotated`, `Version`, `Owner`."),
@@ -320,6 +360,72 @@ const templates = {
320
360
  text: `${greeting}\n\n{{t "email/deletion_complete.text_body" app=theme.appName purgedOn=purgedOn}}\n\n{{t "email/deletion_complete.last"}}`,
321
361
  links: []
322
362
  },
363
+ organizationMemberAdded: {
364
+ id: "organizationMemberAdded",
365
+ category: "transactional",
366
+ kind: "transactional",
367
+ width: "narrow",
368
+ payload: OrganizationMemberAddedPayload,
369
+ subject: `{{t "email/organization_member_added.subject" organization=organizationName}}`,
370
+ html: layout(`${heading("{{t \"email/organization_member_added.heading\"}}")}<p style="margin:0 0 8px">${greeting} {{t "email/organization_member_added.body" organization=organizationName role=role app=theme.appName}}</p><p class="t-subtle" style="margin:16px 0 0; font-size:13px; color:{{theme.light.textSubtle}}">{{t "email/organization_member.contact"}}</p>`),
371
+ text: `${greeting}\n\n{{t "email/organization_member_added.text_body" organization=organizationName role=role app=theme.appName}}\n\n{{t "email/organization_member.contact"}}`,
372
+ links: []
373
+ },
374
+ organizationMemberRemoved: {
375
+ id: "organizationMemberRemoved",
376
+ category: "transactional",
377
+ kind: "transactional",
378
+ width: "narrow",
379
+ payload: OrganizationMemberRemovedPayload,
380
+ subject: `{{t "email/organization_member_removed.subject" organization=organizationName}}`,
381
+ html: layout(`${heading("{{t \"email/organization_member_removed.heading\"}}")}<p style="margin:0 0 8px">${greeting} {{t "email/organization_member_removed.body" organization=organizationName app=theme.appName}}</p><p class="t-subtle" style="margin:16px 0 0; font-size:13px; color:{{theme.light.textSubtle}}">{{t "email/organization_member.contact"}}</p>`),
382
+ text: `${greeting}\n\n{{t "email/organization_member_removed.text_body" organization=organizationName app=theme.appName}}\n\n{{t "email/organization_member.contact"}}`,
383
+ links: []
384
+ },
385
+ organizationOwnershipTransferred: {
386
+ id: "organizationOwnershipTransferred",
387
+ category: "transactional",
388
+ kind: "transactional",
389
+ width: "narrow",
390
+ payload: OrganizationOwnershipTransferredPayload,
391
+ subject: `{{t "email/organization_ownership_transferred.subject" organization=organizationName}}`,
392
+ html: layout(`${heading("{{t \"email/organization_ownership_transferred.heading\"}}")}<p style="margin:0 0 8px">${greeting} {{t "email/organization_ownership_transferred.body" organization=organizationName app=theme.appName}}</p><p class="t-subtle" style="margin:16px 0 0; font-size:13px; color:{{theme.light.textSubtle}}">{{t "email/organization_member.contact"}}</p>`),
393
+ text: `${greeting}\n\n{{t "email/organization_ownership_transferred.text_body" organization=organizationName app=theme.appName}}\n\n{{t "email/organization_member.contact"}}`,
394
+ links: []
395
+ },
396
+ organizationSuspended: {
397
+ id: "organizationSuspended",
398
+ category: "transactional",
399
+ kind: "transactional",
400
+ width: "narrow",
401
+ payload: OrganizationSuspendedPayload,
402
+ subject: `{{t "email/organization_suspended.subject" organization=organizationName}}`,
403
+ html: layout(`${heading("{{t \"email/organization_suspended.heading\"}}")}<p style="margin:0 0 8px">${greeting} {{t "email/organization_suspended.body" organization=organizationName app=theme.appName}}</p>{{#if reason}}<p style="margin:0 0 8px">{{t "email/organization_suspended.reason" reason=reason}}</p>{{/if}}{{#if until}}<p style="margin:0 0 8px">{{t "email/organization_suspended.until" until=until}}</p>{{/if}}<p class="t-subtle" style="margin:16px 0 0; font-size:13px; color:{{theme.light.textSubtle}}">{{t "email/organization_member.contact"}}</p>`),
404
+ text: `${greeting}\n\n{{t "email/organization_suspended.text_body" organization=organizationName app=theme.appName}}{{#if reason}}\n\n{{t "email/organization_suspended.reason" reason=reason}}{{/if}}{{#if until}}\n\n{{t "email/organization_suspended.until" until=until}}{{/if}}\n\n{{t "email/organization_member.contact"}}`,
405
+ links: []
406
+ },
407
+ organizationReinstated: {
408
+ id: "organizationReinstated",
409
+ category: "transactional",
410
+ kind: "transactional",
411
+ width: "narrow",
412
+ payload: OrganizationReinstatedPayload,
413
+ subject: `{{t "email/organization_reinstated.subject" organization=organizationName}}`,
414
+ html: layout(`${heading("{{t \"email/organization_reinstated.heading\"}}")}<p style="margin:0 0 8px">${greeting} {{t "email/organization_reinstated.body" organization=organizationName app=theme.appName}}</p><p class="t-subtle" style="margin:16px 0 0; font-size:13px; color:{{theme.light.textSubtle}}">{{t "email/organization_member.contact"}}</p>`),
415
+ text: `${greeting}\n\n{{t "email/organization_reinstated.text_body" organization=organizationName app=theme.appName}}\n\n{{t "email/organization_member.contact"}}`,
416
+ links: []
417
+ },
418
+ organizationDeletionScheduled: {
419
+ id: "organizationDeletionScheduled",
420
+ category: "transactional",
421
+ kind: "transactional",
422
+ width: "narrow",
423
+ payload: OrganizationDeletionScheduledPayload,
424
+ subject: `{{t "email/organization_deletion_scheduled.subject" organization=organizationName}}`,
425
+ html: layout(`${heading("{{t \"email/organization_deletion_scheduled.heading\"}}")}<p style="margin:0 0 8px">${greeting} {{t "email/organization_deletion_scheduled.body" organization=organizationName app=theme.appName purgeOn=purgeOn}}</p><p class="t-subtle" style="margin:16px 0 0; font-size:13px; color:{{theme.light.textSubtle}}">{{t "email/organization_deletion_scheduled.contact" purgeOn=purgeOn}}</p>`),
426
+ text: `${greeting}\n\n{{t "email/organization_deletion_scheduled.text_body" organization=organizationName app=theme.appName purgeOn=purgeOn}}\n\n{{t "email/organization_deletion_scheduled.contact" purgeOn=purgeOn}}`,
427
+ links: []
428
+ },
323
429
  operationalNotice: {
324
430
  id: "operationalNotice",
325
431
  category: "transactional",
@@ -1 +1 @@
1
- {"version":3,"file":"samples.d.ts","sourceRoot":"","sources":["../../src/templates/samples.ts"],"names":[],"mappings":"AAGA;;;;GAIG;AACH,eAAO,MAAM,cAAc,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAsElD,CAAC"}
1
+ {"version":3,"file":"samples.d.ts","sourceRoot":"","sources":["../../src/templates/samples.ts"],"names":[],"mappings":"AAGA;;;;GAIG;AACH,eAAO,MAAM,cAAc,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAiFlD,CAAC"}
@@ -68,6 +68,34 @@ const samplePayloads = {
68
68
  name: "Sam",
69
69
  purgedOn: "19 November 2026"
70
70
  },
71
+ organizationMemberAdded: {
72
+ name: "Sam",
73
+ organizationName: "Globex",
74
+ role: "admin"
75
+ },
76
+ organizationMemberRemoved: {
77
+ name: "Sam",
78
+ organizationName: "Globex"
79
+ },
80
+ organizationOwnershipTransferred: {
81
+ name: "Sam",
82
+ organizationName: "Globex"
83
+ },
84
+ organizationSuspended: {
85
+ name: "Sam",
86
+ organizationName: "Globex",
87
+ reason: "The invoice for October is unpaid.",
88
+ until: "19 November 2026"
89
+ },
90
+ organizationReinstated: {
91
+ name: "Sam",
92
+ organizationName: "Globex"
93
+ },
94
+ organizationDeletionScheduled: {
95
+ name: "Sam",
96
+ organizationName: "Globex",
97
+ purgeOn: "19 November 2026"
98
+ },
71
99
  operationalNotice: {
72
100
  severity: "warning",
73
101
  summary: "A secret has not been rotated in 90 days",
@@ -3,5 +3,5 @@
3
3
  /** This package's npm name — the join key against a release feed. */
4
4
  export declare const PACKAGE_NAME = "@pithy-sh/email";
5
5
  /** This package's version, stamped from its own package.json at generation time. */
6
- export declare const PACKAGE_VERSION = "0.6.0";
6
+ export declare const PACKAGE_VERSION = "0.8.0";
7
7
  //# sourceMappingURL=version.generated.d.ts.map
@@ -4,6 +4,6 @@
4
4
  /** This package's npm name — the join key against a release feed. */
5
5
  const PACKAGE_NAME = "@pithy-sh/email";
6
6
  /** This package's version, stamped from its own package.json at generation time. */
7
- const PACKAGE_VERSION = "0.6.0";
7
+ const PACKAGE_VERSION = "0.8.0";
8
8
  //#endregion
9
9
  export { PACKAGE_NAME, PACKAGE_VERSION };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pithy-sh/email",
3
- "version": "0.6.0",
3
+ "version": "0.8.0",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -42,8 +42,8 @@
42
42
  "postal-mime": "^3.0.0"
43
43
  },
44
44
  "peerDependencies": {
45
- "@pithy-sh/core": "^0.12.0",
46
- "@pithy-sh/secrets": "^0.6.0",
45
+ "@pithy-sh/core": "^0.14.0",
46
+ "@pithy-sh/secrets": "^0.6.2",
47
47
  "hono": "^4.13.2",
48
48
  "kysely": "^0.29.0",
49
49
  "zod": "^4.4.0"
package/src/capability.ts CHANGED
@@ -4,11 +4,13 @@
4
4
  import type { D1Database } from "@cloudflare/workers-types";
5
5
  import { type Capability, defineCapability } from "@pithy-sh/core/src/capability/capability";
6
6
  import { pithyCommandOf } from "@pithy-sh/core/src/cli/command";
7
+ import { composedConsent } from "@pithy-sh/core/src/consent/reader";
7
8
  import { composedUsageMeter, type MeterCharge, type UsageMeter } from "@pithy-sh/core/src/entitlement/meter";
8
9
  import { InternalError } from "@pithy-sh/core/src/error/pithyError";
9
10
  import type { LocaleCatalogs } from "@pithy-sh/core/src/i18n/catalog";
10
11
  import { z } from "zod";
11
12
  import { createBounceHandler } from "./bounce/handler";
13
+ import { EMAIL_CONSENT_PURPOSES, emailConsentGranted, emailConsentWithdrawn } from "./consent/consent";
12
14
  import { emailSigningRegistry } from "./crypto/signingKey";
13
15
  import {
14
16
  type EmailSuppressionDatabase,
@@ -23,9 +25,11 @@ import { emailAdminRoutes } from "./http/guards";
23
25
  import { registerEmailAdminRoutes } from "./http/routes";
24
26
  import { email_0001_init } from "./migrations/0001_init";
25
27
  import { email_0001_suppressions } from "./migrations/0001_suppressions";
28
+ import { EMAIL_PROCESSING } from "./processing/activities";
26
29
  import { DevMailDelivery } from "./provision/devDelivery";
27
30
  import { emailHostCatalogs } from "./provision/hostCatalogs";
28
31
  import { emailSettings } from "./provision/settingsCheck";
32
+ import { emailUserPurge } from "./purge/contribution";
29
33
  import { type EnqueueInput, type EnqueueResult, enqueueEmail } from "./send/enqueue";
30
34
  import { type EmailSenderEnv, emailSenderBinding } from "./send/senderBinding";
31
35
  import { EMAIL_MESSAGES, type EmailMessageLayers, kitEmailLayers } from "./templates/messages";
@@ -38,7 +42,7 @@ import { EmailScheduleParams, EmailSendParams } from "./workflows/params";
38
42
  * global suppression database. A consumer (e.g. `@pithy-sh/auth`) forwards its worker env; it never
39
43
  * names these bindings itself.
40
44
  *
41
- * **`EMAIL_SUPPRESSIONS` is on this list, and that is the whole of pithy-sh/pithy#355.** The wiring is
45
+ * **`EMAIL_SUPPRESSIONS` is on this list.** The wiring is
42
46
  * not the adopter's problem: the capability declares the binding, `pithy add email` provisions it,
43
47
  * `enqueue` reads it off the env, and no consumer config, route option, or constant names it. What an
44
48
  * adopter *may* do — because it is their database — is ask for it back through
@@ -139,7 +143,7 @@ export interface EmailCapability extends Capability {
139
143
  enqueue: (env: EmailEnqueueEnv, input: EnqueueInput) => Promise<EnqueueResult>;
140
144
  /**
141
145
  * The suppression list, from a request env — **it is the adopter's database, and this is how they open
142
- * it** (pithy-sh/pithy#355).
146
+ * it**.
143
147
  *
144
148
  * Nobody has to call this to be protected: `enqueue` consults the list on its own and `runSend`
145
149
  * refuses a blocked recipient regardless. This exists for the adopter who genuinely wants to look —
@@ -201,12 +205,17 @@ export function email(config: EmailConfigInput): EmailCapability {
201
205
  * exactly as it always was: nothing is counted and nothing is refused.
202
206
  */
203
207
  let meter: UsageMeter | undefined;
208
+ /**
209
+ * Every composed capability, kept by `compose` so an enqueue can find the consent reader over its own env.
210
+ * Empty until then, which is a composition with no consent: nothing is gated.
211
+ */
212
+ let composition: readonly Capability[] = [];
204
213
  const capability = defineCapability({
205
214
  name: "email",
206
215
  // The package this capability ships in and the version it ships at, both stamped by
207
216
  // `scripts/stampVersions.ts` — a Worker cannot read its own package.json. Reported per capability by
208
217
  // the control-plane manifest, and reported together: a release feed is keyed by package name, so the
209
- // version alone leaves a client guessing the key (#626).
218
+ // version alone leaves a client guessing the key.
210
219
  version: PACKAGE_VERSION,
211
220
  package: PACKAGE_NAME,
212
221
  // The link-signing key is read through @pithy-sh/secrets, so the secrets capability must be
@@ -218,7 +227,7 @@ export function email(config: EmailConfigInput): EmailCapability {
218
227
  * This capability's own copy — the seven templates whose words the kit owns, plus the shell's
219
228
  * severity vocabulary and its opt-out link. All under `email/`, which `composeMessages` enforces.
220
229
  *
221
- * **In every language it is written in, not English alone (#442).** The send Worker is a separate
230
+ * **In every language it is written in, not English alone.** The send Worker is a separate
222
231
  * deploy with no request and no config, so anything it does not bundle is stamped into it as a
223
232
  * variable — and the kit's own translations were doing that on every provision run. Held here,
224
233
  * they are built into the host and only an adopter's diff travels.
@@ -243,6 +252,7 @@ export function email(config: EmailConfigInput): EmailCapability {
243
252
  */
244
253
  compose: ({ capabilities }) => {
245
254
  meter = composedUsageMeter(capabilities);
255
+ composition = capabilities;
246
256
  for (const composed of capabilities) {
247
257
  if (composed.name !== "i18n") continue;
248
258
  const candidate = (composed as { layersFor?: unknown }).layersFor;
@@ -277,10 +287,24 @@ export function email(config: EmailConfigInput): EmailCapability {
277
287
  },
278
288
  // Every address that bounced, complained or unsubscribed. Dropping it is not a schema change — the
279
289
  // next send goes to people who asked not to be mailed, and the list cannot be rebuilt from anywhere.
280
- // Declared retained, so no `down` runs against it while it holds rows unless counted (#588).
290
+ // Declared retained, so no `down` runs against it while it holds rows unless counted.
281
291
  retained: emailSuppressionsRetainedTables,
282
292
  },
283
293
  },
294
+ // A person's suppression and the log of mail sent to them are kept through their purge, so an unsubscribe holds,
295
+ // and exported on an access request with the basis that keeps them.
296
+ purge: [emailUserPurge()],
297
+ processing: EMAIL_PROCESSING,
298
+ /**
299
+ * What email processes under consent: marketing mail and open and click tracking. With
300
+ * `@pithy-sh/consent` composed, an enqueue asks before either; without it, nothing is gated and `pithy doctor`
301
+ * says tracking runs with no consent record behind it.
302
+ */
303
+ consentPurposes: EMAIL_CONSENT_PURPOSES,
304
+ // A withdrawal from marketing suppresses the address for marketing; one from tracking stops tracking mail
305
+ // already queued. The suppression list and the consent record never disagree.
306
+ consentWithdrawn: emailConsentWithdrawn,
307
+ consentGranted: emailConsentGranted,
284
308
  /**
285
309
  * The two durable jobs email owns. Both classes live in the prebuilt email worker
286
310
  * (`workflows/worker.ts`), never in the app worker — the app only ever dispatches into `send`.
@@ -296,7 +320,7 @@ export function email(config: EmailConfigInput): EmailCapability {
296
320
  className: "EmailSendWorkflow",
297
321
  // The same object the host's own registry and its dispatch route validate against
298
322
  // (`workflows/params.ts`). One schema, three readers: what the app dispatches, what the host
299
- // deploys, and what a loopback dispatch is checked against at the door (#410).
323
+ // deploys, and what a loopback dispatch is checked against at the door.
300
324
  params: EmailSendParams,
301
325
  },
302
326
  schedule: {
@@ -331,7 +355,7 @@ export function email(config: EmailConfigInput): EmailCapability {
331
355
  */
332
356
  adminRoutes: emailAdminRoutes(resolved.basePath),
333
357
  /**
334
- * How `pithy doctor` checks that these settings **work**, not merely that they are written (#411).
358
+ * How `pithy doctor` checks that these settings **work**, not merely that they are written.
335
359
  *
336
360
  * Built from the resolved config, on the instance, so discovery needs no `pithy.manifest.json` and no
337
361
  * import of this package by the CLI. The local half runs `workflows/hostEnv.ts` — the very declaration
@@ -382,6 +406,8 @@ export function email(config: EmailConfigInput): EmailCapability {
382
406
  suppressionDb: env.EMAIL_SUPPRESSIONS ? emailSuppressionDatabase(env.EMAIL_SUPPRESSIONS) : undefined,
383
407
  // Read through the closure for the reason `layersFor` is: `compose` fills it after this is defined.
384
408
  meter: chargeFor(env),
409
+ // Read through the closure for the same reason: `compose` fills the composition after this is defined.
410
+ consent: composedConsent(composition, env as unknown as Record<string, unknown>),
385
411
  now: new Date(),
386
412
  newId: () => crypto.randomUUID(),
387
413
  },
@@ -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
  ),