@pithy-sh/email 0.3.11 → 0.5.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 (39) hide show
  1. package/dist/capability.d.ts.map +1 -1
  2. package/dist/capability.js +20 -1
  3. package/dist/crypto/signingKey.d.ts +4 -0
  4. package/dist/crypto/signingKey.d.ts.map +1 -1
  5. package/dist/crypto/signingKey.js +5 -1
  6. package/dist/http/callbacks.d.ts.map +1 -1
  7. package/dist/http/callbacks.js +26 -5
  8. package/dist/http/routes.d.ts +1 -1
  9. package/dist/http/routes.d.ts.map +1 -1
  10. package/dist/http/routes.js +42 -10
  11. package/dist/provision/provisionEmail.d.ts +16 -2
  12. package/dist/provision/provisionEmail.d.ts.map +1 -1
  13. package/dist/provision/provisionEmail.js +7 -2
  14. package/dist/provision/resolveEmailConfig.d.ts +7 -0
  15. package/dist/provision/resolveEmailConfig.d.ts.map +1 -1
  16. package/dist/provision/resolveEmailConfig.js +14 -1
  17. package/dist/provision/settingsCheck.d.ts.map +1 -1
  18. package/dist/provision/settingsCheck.js +44 -7
  19. package/dist/send/enqueue.d.ts +16 -0
  20. package/dist/send/enqueue.d.ts.map +1 -1
  21. package/dist/send/enqueue.js +14 -0
  22. package/dist/version.generated.d.ts +1 -1
  23. package/dist/version.generated.d.ts.map +1 -1
  24. package/dist/version.generated.js +1 -1
  25. package/dist/workflows/hostEnv.d.ts +41 -0
  26. package/dist/workflows/hostEnv.d.ts.map +1 -1
  27. package/dist/workflows/hostEnv.js +14 -7
  28. package/package.json +6 -6
  29. package/src/capability.ts +18 -1
  30. package/src/crypto/signingKey.ts +6 -0
  31. package/src/http/callbacks.ts +41 -12
  32. package/src/http/routes.ts +49 -11
  33. package/src/http/schemas.ts +1 -1
  34. package/src/provision/provisionEmail.ts +19 -5
  35. package/src/provision/resolveEmailConfig.ts +12 -0
  36. package/src/provision/settingsCheck.ts +48 -9
  37. package/src/send/enqueue.ts +28 -0
  38. package/src/version.generated.ts +1 -1
  39. package/src/workflows/hostEnv.ts +13 -6
@@ -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.3.11";
6
+ export declare const PACKAGE_VERSION = "0.5.0";
7
7
  //# sourceMappingURL=version.generated.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"version.generated.d.ts","sourceRoot":"","sources":["../src/version.generated.ts"],"names":[],"mappings":"AAWA,qEAAqE;AACrE,eAAO,MAAM,YAAY,oBAAoB,CAAC;AAE9C,oFAAoF;AACpF,eAAO,MAAM,eAAe,WAAW,CAAC"}
1
+ {"version":3,"file":"version.generated.d.ts","sourceRoot":"","sources":["../src/version.generated.ts"],"names":[],"mappings":"AAWA,qEAAqE;AACrE,eAAO,MAAM,YAAY,oBAAoB,CAAC;AAE9C,oFAAoF;AACpF,eAAO,MAAM,eAAe,UAAU,CAAC"}
@@ -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.3.11";
7
+ const PACKAGE_VERSION = "0.5.0";
8
8
  //#endregion
9
9
  export { PACKAGE_NAME, PACKAGE_VERSION };
@@ -5,6 +5,47 @@ import type { SecretBinding } from "@pithy-sh/secrets/src/env/bindings";
5
5
  import { z } from "zod";
6
6
  import type { EmailSender } from "../send/sender";
7
7
  import type { SendWorkflowInstances } from "./instances";
8
+ /**
9
+ * What the prebuilt email host worker reads out of its env — declared once, validated at boot, and
10
+ * read statically by `pithy doctor` (pithy-sh/pithy#410, #411).
11
+ *
12
+ * Nobody authors this Worker. `pithy email provision` resolves the committed template beside this
13
+ * file and deploys it, so every value here arrives as a binding, a var or a Secrets Store entry that
14
+ * a *machine* wrote — and until this module, none of it was checked. Three failures, all of them
15
+ * discovered as mail that did not arrive:
16
+ *
17
+ * - `BASE_URL` absent → every magic link in the batch pointed at `undefined/auth/…`.
18
+ * - `EMAIL_THEME` unparseable → a `JSON.parse` threw inside a render step, three retries deep,
19
+ * where the message reads as a template fault.
20
+ * - `SCHEDULER_BATCH_SIZE` written `"fifty"` → `Number(...)` gave `NaN`, the scheduler claimed
21
+ * nothing, and it did so on every tick, forever, without a line in the log.
22
+ *
23
+ * So the parse is the boot check: `z.output` is what the host actually runs on, which is why the
24
+ * coercions live in the schema rather than at the call sites. `Number(env.MAX_ATTEMPTS ?? 5)` in
25
+ * `worker.ts` was the shape of the bug — a default and a coercion restated at every reader, each free
26
+ * to disagree with the next.
27
+ *
28
+ * ## Two names, deliberately
29
+ *
30
+ * {@link EmailHostEnv} is the schema (and the type the host runs on). {@link emailHostEnv} is the
31
+ * *declaration*: the schema plus what fills each field, which is the object the CLI imports. The
32
+ * second is the one an operator's report is built from — a missing field is only actionable when
33
+ * something names the binding, var or command that writes it.
34
+ *
35
+ * Node-safe on purpose. No `cloudflare:` import and no filesystem, so `pithy doctor` can import this
36
+ * without executing the Worker — the same constraint `@pithy-sh/core`'s host modules carry.
37
+ */
38
+ /**
39
+ * The command that writes every provisioned value here. Stated once so nine action lines cannot drift.
40
+ *
41
+ * No `--env`: it spans every declared environment in one run and declares no such flag, and a flag a
42
+ * command does not declare is refused (#594) — so a remedy naming one is a remedy that cannot be followed.
43
+ *
44
+ * No `--worker` either, and only here: this is the sentence the deployed host writes into its own log, and
45
+ * a host does not know which app Worker's `apps/` directory provisioned it. `pithy doctor` reports the same
46
+ * finding for a Worker it knows, and names it there (`provision/settingsCheck.ts`, #711).
47
+ */
48
+ export declare const EMAIL_PROVISION: import("@pithy-sh/core/src/cli/command").Command;
8
49
  /** The email host's env, as the host runs on it. Every field is coerced here, never at its reader. */
9
50
  export declare const EmailHostEnv: z.ZodObject<{
10
51
  DB: z.ZodType<D1Database, unknown, z.core.$ZodTypeInternals<D1Database, unknown>>;
@@ -1 +1 @@
1
- {"version":3,"file":"hostEnv.d.ts","sourceRoot":"","sources":["../../src/workflows/hostEnv.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,2BAA2B,CAAC;AAE5D,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oCAAoC,CAAC;AACxE,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAElD,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAC;AAgFzD,sGAAsG;AACtG,eAAO,MAAM,YAAY;;;;;;;;;kBA+BiB,OAAO,CAAC,OAAO,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA4D6C,CAAC;AACxG,MAAM,MAAM,YAAY,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,YAAY,CAAC,CAAC;AAEzD,kGAAkG;AAClG,KAAK,kBAAkB,GAAG;IACxB,MAAM,CAAC,OAAO,EAAE;QAAE,EAAE,CAAC,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE;YAAE,MAAM,EAAE,MAAM,EAAE,CAAA;SAAE,CAAA;KAAE,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;CAClF,GAAG,qBAAqB,CAAC;AAO1B;;;;;;GAMG;AACH,eAAO,MAAM,YAAY;;;;;;;;;kBAhFiB,OAAO,CAAC,OAAO,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;kBAsHxD,CAAC"}
1
+ {"version":3,"file":"hostEnv.d.ts","sourceRoot":"","sources":["../../src/workflows/hostEnv.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,2BAA2B,CAAC;AAG5D,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oCAAoC,CAAC;AACxE,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAElD,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAC;AAEzD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AAEH;;;;;;;;;GASG;AACH,eAAO,MAAM,eAAe,kDAA2D,CAAC;AA2CxF,sGAAsG;AACtG,eAAO,MAAM,YAAY;;;;;;;;;kBA+BiB,OAAO,CAAC,OAAO,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA4D6C,CAAC;AACxG,MAAM,MAAM,YAAY,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,YAAY,CAAC,CAAC;AAEzD,kGAAkG;AAClG,KAAK,kBAAkB,GAAG;IACxB,MAAM,CAAC,OAAO,EAAE;QAAE,EAAE,CAAC,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE;YAAE,MAAM,EAAE,MAAM,EAAE,CAAA;SAAE,CAAA;KAAE,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;CAClF,GAAG,qBAAqB,CAAC;AAO1B;;;;;;GAMG;AACH,eAAO,MAAM,YAAY;;;;;;;;;kBAhFiB,OAAO,CAAC,OAAO,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;kBAsHxD,CAAC"}
@@ -3,6 +3,7 @@
3
3
  import { EMAIL_LINK_SIGNING_KEY, EMAIL_LINK_SIGNING_KEY_BINDING } from "../crypto/signingKey.js";
4
4
  import { EmailTheme, defaultTheme } from "../templates/theme.js";
5
5
  import { z } from "zod";
6
+ import { pithyCommandOf, remedy } from "@pithy-sh/core/src/cli/command";
6
7
  import { defineHostEnv } from "@pithy-sh/core/src/workflow/hostEnv";
7
8
  //#region src/workflows/hostEnv.ts
8
9
  /**
@@ -40,13 +41,19 @@ import { defineHostEnv } from "@pithy-sh/core/src/workflow/hostEnv";
40
41
  *
41
42
  * No `--env`: it spans every declared environment in one run and declares no such flag, and a flag a
42
43
  * command does not declare is refused (#594) — so a remedy naming one is a remedy that cannot be followed.
44
+ *
45
+ * No `--worker` either, and only here: this is the sentence the deployed host writes into its own log, and
46
+ * a host does not know which app Worker's `apps/` directory provisioned it. `pithy doctor` reports the same
47
+ * finding for a Worker it knows, and names it there (`provision/settingsCheck.ts`, #711).
43
48
  */
44
- const PROVISION = "pithy email provision";
49
+ const EMAIL_PROVISION = pithyCommandOf("email provision", {}, { runtime: true });
50
+ const PROVISION = EMAIL_PROVISION;
45
51
  /**
46
- * The command that writes both host secrets below. No `--env`, for the same reason: `pithy secrets provision`
47
- * provisions every declared environment in one run and declares no such flag.
52
+ * What writes both host secrets below, said as a person's decision. No `--env`, for the same reason: `pithy secrets
53
+ * provision` provisions every declared environment in one run, production included, and declares no such flag — so
54
+ * it is never a `Run` line for one host's secret (#711).
48
55
  */
49
- const SECRETS_PROVISION = "pithy secrets provision";
56
+ const SECRETS_PROVISION = remedy("secrets provision", {}, { runtime: true }).say((command) => command);
50
57
  /** A binding `pithy email provision` wires into the resolved `wrangler.jsonc`. */
51
58
  const binding = (name) => ({
52
59
  kind: "binding",
@@ -136,12 +143,12 @@ const emailHostEnv = defineHostEnv({
136
143
  SECRETS_ENCRYPTION_KEYS: {
137
144
  kind: "secret",
138
145
  name: "SECRETS_ENCRYPTION_KEYS",
139
- command: SECRETS_PROVISION
146
+ decision: SECRETS_PROVISION
140
147
  },
141
148
  [EMAIL_LINK_SIGNING_KEY_BINDING]: {
142
149
  kind: "secret",
143
150
  name: EMAIL_LINK_SIGNING_KEY,
144
- command: SECRETS_PROVISION
151
+ decision: SECRETS_PROVISION
145
152
  },
146
153
  EMAIL: binding("EMAIL"),
147
154
  EMAIL_SENDER: binding("EMAIL_SENDER"),
@@ -163,4 +170,4 @@ const emailHostEnv = defineHostEnv({
163
170
  }
164
171
  });
165
172
  //#endregion
166
- export { EmailHostEnv, emailHostEnv };
173
+ export { EMAIL_PROVISION, EmailHostEnv, emailHostEnv };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pithy-sh/email",
3
- "version": "0.3.11",
3
+ "version": "0.5.0",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -27,7 +27,7 @@
27
27
  "scripts": {
28
28
  "precompile": "bun scripts/precompile.ts",
29
29
  "build": "bun run precompile && tsdown && tsc -p tsconfig.build.json && bun ../../tooling/build/src/stampDeclarations.ts",
30
- "typecheck": "tsc -p tsconfig.json",
30
+ "typecheck": "bun check -p tsconfig.json",
31
31
  "test": "bun run precompile && vitest run",
32
32
  "test:node": "bun run precompile && vitest run --project=node",
33
33
  "test:workers": "bun run precompile && vitest run --project=workers",
@@ -42,14 +42,14 @@
42
42
  "postal-mime": "^3.0.0"
43
43
  },
44
44
  "peerDependencies": {
45
- "@pithy-sh/core": "^0.9.0",
46
- "@pithy-sh/secrets": "^0.3.2",
45
+ "@pithy-sh/core": "^0.11.0",
46
+ "@pithy-sh/secrets": "^0.5.0",
47
47
  "hono": "^4.13.2",
48
48
  "kysely": "^0.29.0",
49
49
  "zod": "^4.4.0"
50
50
  },
51
51
  "devDependencies": {
52
- "@cloudflare/vitest-plugin": "^1.0.0",
52
+ "@cloudflare/vitest-plugin": "^1.4.2",
53
53
  "@pithy-sh/cloudflare": "workspace:*",
54
54
  "@pithy-sh/core": "workspace:*",
55
55
  "@pithy-sh/secrets": "workspace:*",
@@ -62,7 +62,7 @@
62
62
  "tsdown": "^0.23.0",
63
63
  "typescript": "^7.0.2",
64
64
  "vitest": "^4.1.0",
65
- "wrangler": "^4.115.0",
65
+ "wrangler": "^4.151.0",
66
66
  "zod": "^4.4.0"
67
67
  }
68
68
  }
package/src/capability.ts CHANGED
@@ -3,6 +3,8 @@
3
3
 
4
4
  import type { D1Database } from "@cloudflare/workers-types";
5
5
  import { type Capability, defineCapability } from "@pithy-sh/core/src/capability/capability";
6
+ import { pithyCommandOf } from "@pithy-sh/core/src/cli/command";
7
+ import { composedUsageMeter, type MeterCharge, type UsageMeter } from "@pithy-sh/core/src/entitlement/meter";
6
8
  import { InternalError } from "@pithy-sh/core/src/error/pithyError";
7
9
  import type { LocaleCatalogs } from "@pithy-sh/core/src/i18n/catalog";
8
10
  import { z } from "zod";
@@ -193,6 +195,12 @@ export function email(config: EmailConfigInput): EmailCapability {
193
195
  * capability's own config, and this is the only thing that knows it.
194
196
  */
195
197
  let supportedLocales: readonly string[] = [];
198
+ /**
199
+ * The usage meter a composed provider exposes — `@pithy-sh/payments`, when it is composed — found in
200
+ * `compose` by core's structural predicate. Undefined with no provider, which is the email capability
201
+ * exactly as it always was: nothing is counted and nothing is refused.
202
+ */
203
+ let meter: UsageMeter | undefined;
196
204
  const capability = defineCapability({
197
205
  name: "email",
198
206
  // The package this capability ships in and the version it ships at, both stamped by
@@ -234,6 +242,7 @@ export function email(config: EmailConfigInput): EmailCapability {
234
242
  * project sends what it always sent.
235
243
  */
236
244
  compose: ({ capabilities }) => {
245
+ meter = composedUsageMeter(capabilities);
237
246
  for (const composed of capabilities) {
238
247
  if (composed.name !== "i18n") continue;
239
248
  const candidate = (composed as { layersFor?: unknown }).layersFor;
@@ -345,12 +354,18 @@ export function email(config: EmailConfigInput): EmailCapability {
345
354
  if (!binding) {
346
355
  throw new InternalError({
347
356
  message: "The suppression list is not available.",
348
- action: "Run `pithy add email` to provision it, or bind the EMAIL_SUPPRESSIONS D1 database.",
357
+ action: `Run \`${pithyCommandOf("add", { args: ["email"], flags: { "--with-prerequisites": true } }, { runtime: true })}\` to provision it, or bind the EMAIL_SUPPRESSIONS D1 database.`,
349
358
  detail: "email.suppressions() was called with an env carrying no `EMAIL_SUPPRESSIONS` D1 binding.",
350
359
  });
351
360
  }
352
361
  return emailSuppressionDatabase(binding);
353
362
  };
363
+ /** The meter charge for one env, or undefined when no provider is composed. */
364
+ const chargeFor = (env: EmailEnqueueEnv): ((charge: MeterCharge) => Promise<void>) | undefined => {
365
+ const composed = meter;
366
+ if (composed === undefined) return undefined;
367
+ return (charge) => composed.charge(env as unknown as Record<string, unknown>, charge);
368
+ };
354
369
  const enqueue = (env: EmailEnqueueEnv, input: EnqueueInput): Promise<EnqueueResult> =>
355
370
  enqueueEmail(
356
371
  {
@@ -365,6 +380,8 @@ export function email(config: EmailConfigInput): EmailCapability {
365
380
  // Read straight off the env the consumer forwarded. This one line is what makes suppression
366
381
  // automatic: a consumer names nothing, and a hard-bounced address is never queued for a send.
367
382
  suppressionDb: env.EMAIL_SUPPRESSIONS ? emailSuppressionDatabase(env.EMAIL_SUPPRESSIONS) : undefined,
383
+ // Read through the closure for the reason `layersFor` is: `compose` fills it after this is defined.
384
+ meter: chargeFor(env),
368
385
  now: new Date(),
369
386
  newId: () => crypto.randomUUID(),
370
387
  },
@@ -52,6 +52,12 @@ export const emailSigningRegistry = defineSecretRegistry({
52
52
  // the entry when it is absent and never replaces one — and `local` to replace.
53
53
  origin: { kind: "minted", recipe: { kind: "random", bytes: 32, encoding: "base64url" } },
54
54
  rotation: { kind: "local" },
55
+ // **A rotation keeps the previous key for as long as a link lives (#602).** A link is minted into mail
56
+ // nobody can recall and stays valid for `LINK_TTL_DAYS` — 90 by default — so a key retired sooner breaks
57
+ // an unsubscribe that was valid when it was sent. A host that raises `LINK_TTL_DAYS` wants a longer
58
+ // overlap than this, declared in the project's own registry. Nothing is sealed under this key at rest:
59
+ // it signs, and a signature expires with its link.
60
+ overlap: { days: 90, minimumDays: 90 },
55
61
  },
56
62
  });
57
63
 
@@ -2,10 +2,10 @@
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
4
  import type { D1Database } from "@cloudflare/workers-types";
5
- import { zValidator } from "@hono/zod-validator";
6
5
  import { normalizeAddress } from "@pithy-sh/core/src/address/address";
7
6
  import type { PithyHonoEnv } from "@pithy-sh/core/src/capability/capability";
8
- import { validationHook } from "@pithy-sh/core/src/http/validation";
7
+ import { describeRoute } from "@pithy-sh/core/src/http/routeSpec";
8
+ import { validate } from "@pithy-sh/core/src/http/validation";
9
9
  import type { SecretsStoreEnv } from "@pithy-sh/secrets/src/env/bindings";
10
10
  import type { Hono } from "hono";
11
11
  import { resolveSigningKeys } from "../crypto/signingKey";
@@ -202,21 +202,50 @@ export function registerCallbacks(app: Hono<PithyHonoEnv>): void {
202
202
  };
203
203
  };
204
204
 
205
- app.get(`${CALLBACK_BASE}/c/:token`, zValidator("param", CallbackTokenParam, validationHook), async (c) => {
206
- const { db, keys } = await setup(c.env as unknown as CallbackEnv);
207
- return handleClick(db, keys, { token: c.req.valid("param").token, url: c.req.url }, new Date());
208
- });
205
+ app.get(
206
+ `${CALLBACK_BASE}/c/:token`,
207
+ describeRoute({
208
+ summary: "Record a click on a tracked link, then send the reader on to it.",
209
+ description:
210
+ "Public: the HMAC signature on the token is the only gate. A forged, altered, or expired token answers `email/invalid_token` (400) before anything is recorded, and the destination is the http(s) URL signed into the token, never one from the request.",
211
+ verification: "public",
212
+ responses: { 302: { description: "A redirect to the link's destination, carried in `Location`." } },
213
+ }),
214
+ validate("param", CallbackTokenParam),
215
+ async (c) => {
216
+ const { db, keys } = await setup(c.env as unknown as CallbackEnv);
217
+ return handleClick(db, keys, { token: c.req.valid("param").token, url: c.req.url }, new Date());
218
+ },
219
+ );
209
220
 
210
- app.get(`${CALLBACK_BASE}/o/:token`, zValidator("param", CallbackTokenParam, validationHook), async (c) => {
211
- const { db, keys } = await setup(c.env as unknown as CallbackEnv);
212
- return handleOpen(db, keys, { token: c.req.valid("param").token, url: c.req.url }, new Date());
213
- });
221
+ app.get(
222
+ `${CALLBACK_BASE}/o/:token`,
223
+ describeRoute({
224
+ summary: "Record that an email was opened.",
225
+ description:
226
+ "Public: the HMAC signature on the token is the only gate. The token may carry the `.png` suffix mail clients expect on an image URL.",
227
+ verification: "public",
228
+ responses: { 200: { description: "A 1×1 transparent PNG, never cached.", contentType: "image/png" } },
229
+ }),
230
+ validate("param", CallbackTokenParam),
231
+ async (c) => {
232
+ const { db, keys } = await setup(c.env as unknown as CallbackEnv);
233
+ return handleOpen(db, keys, { token: c.req.valid("param").token, url: c.req.url }, new Date());
234
+ },
235
+ );
214
236
 
215
237
  app.on(
216
238
  ["GET", "POST"],
217
239
  `${CALLBACK_BASE}/u/:token`,
218
- zValidator("param", CallbackTokenParam, validationHook),
219
- zValidator("query", UnsubscribeQuery, validationHook),
240
+ describeRoute({
241
+ summary: "Unsubscribe the recipient from everything but the mail they ask for.",
242
+ description:
243
+ "Public: the HMAC signature on the token is the only gate. Answers GET for the link in the message and POST for one-click unsubscribe. The address joins the suppression list shared by every environment.",
244
+ verification: "public",
245
+ responses: { 200: { description: "A short HTML page confirming the opt-out.", contentType: "text/html" } },
246
+ }),
247
+ validate("param", CallbackTokenParam),
248
+ validate("query", UnsubscribeQuery),
220
249
  async (c) => {
221
250
  const env = c.env as unknown as CallbackEnv;
222
251
  const { db, suppressionDb, keys } = await setup(env);
@@ -2,15 +2,17 @@
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
4
  import type { D1Database } from "@cloudflare/workers-types";
5
- import { zValidator } from "@hono/zod-validator";
6
5
  import { normalizeAddress } from "@pithy-sh/core/src/address/address";
7
6
  import type { PithyHonoEnv } from "@pithy-sh/core/src/capability/capability";
8
7
  import type { ControlPlaneContext } from "@pithy-sh/core/src/controlPlane/context";
9
8
  import { requireControlPlane } from "@pithy-sh/core/src/controlPlane/http/guard";
10
9
  import type { ControlPlaneScope } from "@pithy-sh/core/src/controlPlane/scope/scope";
10
+ import type { AmbientEnv } from "@pithy-sh/core/src/env/ambient";
11
11
  import { ConflictError, InternalError, NotFoundError, ValidationError } from "@pithy-sh/core/src/error/pithyError";
12
- import { validationHook } from "@pithy-sh/core/src/http/validation";
12
+ import { describeRoute } from "@pithy-sh/core/src/http/routeSpec";
13
+ import { validate } from "@pithy-sh/core/src/http/validation";
13
14
  import type { VerificationStrategy } from "@pithy-sh/core/src/http/verification";
15
+ import { migrateStep } from "@pithy-sh/core/src/migrations/migrateStep";
14
16
  import type { Context, Hono } from "hono";
15
17
  import { EmailAuditActions } from "../audit/actions";
16
18
  import {
@@ -31,7 +33,7 @@ import {
31
33
  EMAIL_SUPPRESSIONS_READ_SCOPE,
32
34
  EMAIL_SUPPRESSIONS_WRITE_SCOPE,
33
35
  } from "./guards";
34
- import type {
36
+ import {
35
37
  EmailJobResponse,
36
38
  EmailJobRetryResponse,
37
39
  EmailJobsResponse,
@@ -89,7 +91,7 @@ export interface EmailRouteDeclaration {
89
91
  * Every management route, and how it is gated.
90
92
  *
91
93
  * Exported so a test can assert against the declaration rather than against a middleware count. A count
92
- * proves that *something* runs before the handler — a bare `zValidator` satisfies it — and cannot prove
94
+ * proves that *something* runs before the handler — a bare `validate` satisfies it — and cannot prove
93
95
  * *what*. `routeContract.test.ts` checks this list against the paths Hono actually registered, in both
94
96
  * directions, so a route added without an entry and an entry without a route both fail.
95
97
  */
@@ -145,7 +147,7 @@ function d1(c: Context<PithyHonoEnv>, binding: "DB" | "EMAIL_SUPPRESSIONS"): D1D
145
147
  if (!found) {
146
148
  throw new InternalError({
147
149
  message: "Email is not fully configured on this Worker.",
148
- action: `Bind a D1 database named ${binding} in wrangler.jsonc, then run pithy migrate.`,
150
+ action: `Bind a D1 database named ${binding} in wrangler.jsonc, then ${migrateStep(c.env as AmbientEnv)}.`,
149
151
  detail: `the email management routes require a \`${binding}\` D1 binding; none was present on env`,
150
152
  });
151
153
  }
@@ -190,8 +192,14 @@ export function registerEmailAdminRoutes(options: EmailAdminRoutesOptions): (app
190
192
 
191
193
  app.get(
192
194
  `${base}/jobs`,
195
+ describeRoute({
196
+ summary: "Page through the send log.",
197
+ verification: "control-plane",
198
+ scopes: [EMAIL_JOBS_READ_SCOPE],
199
+ responses: { 200: EmailJobsResponse },
200
+ }),
193
201
  requireControlPlane(EMAIL_JOBS_READ_SCOPE),
194
- zValidator("query", JobsQuery, validationHook),
202
+ validate("query", JobsQuery),
195
203
  async (c) => {
196
204
  const query = c.req.valid("query");
197
205
  const who = caller(c);
@@ -221,8 +229,14 @@ export function registerEmailAdminRoutes(options: EmailAdminRoutesOptions): (app
221
229
 
222
230
  app.get(
223
231
  `${base}/jobs/:id`,
232
+ describeRoute({
233
+ summary: "Read one email job in full, recipient included.",
234
+ verification: "control-plane",
235
+ scopes: [EMAIL_JOBS_READ_SCOPE],
236
+ responses: { 200: EmailJobResponse },
237
+ }),
224
238
  requireControlPlane(EMAIL_JOBS_READ_SCOPE),
225
- zValidator("param", JobIdParam, validationHook),
239
+ validate("param", JobIdParam),
226
240
  async (c) => {
227
241
  const { id } = c.req.valid("param");
228
242
  const who = caller(c);
@@ -254,8 +268,14 @@ export function registerEmailAdminRoutes(options: EmailAdminRoutesOptions): (app
254
268
 
255
269
  app.post(
256
270
  `${base}/jobs/:id/retry`,
271
+ describeRoute({
272
+ summary: "Queue a job to send again.",
273
+ verification: "control-plane",
274
+ scopes: [EMAIL_JOBS_RETRY_SCOPE],
275
+ responses: { 200: EmailJobRetryResponse },
276
+ }),
257
277
  requireControlPlane(EMAIL_JOBS_RETRY_SCOPE),
258
- zValidator("param", JobIdParam, validationHook),
278
+ validate("param", JobIdParam),
259
279
  async (c) => {
260
280
  const { id } = c.req.valid("param");
261
281
  const who = caller(c);
@@ -297,8 +317,14 @@ export function registerEmailAdminRoutes(options: EmailAdminRoutesOptions): (app
297
317
 
298
318
  app.get(
299
319
  `${base}/suppressions`,
320
+ describeRoute({
321
+ summary: "Page through the suppression list, or look one address up.",
322
+ verification: "control-plane",
323
+ scopes: [EMAIL_SUPPRESSIONS_READ_SCOPE],
324
+ responses: { 200: EmailSuppressionsResponse },
325
+ }),
300
326
  requireControlPlane(EMAIL_SUPPRESSIONS_READ_SCOPE),
301
- zValidator("query", SuppressionsQuery, validationHook),
327
+ validate("query", SuppressionsQuery),
302
328
  async (c) => {
303
329
  const query = c.req.valid("query");
304
330
  const who = caller(c);
@@ -333,8 +359,14 @@ export function registerEmailAdminRoutes(options: EmailAdminRoutesOptions): (app
333
359
 
334
360
  app.post(
335
361
  `${base}/suppressions`,
362
+ describeRoute({
363
+ summary: "Block an address by hand.",
364
+ verification: "control-plane",
365
+ scopes: [EMAIL_SUPPRESSIONS_WRITE_SCOPE],
366
+ responses: { 200: EmailSuppressResponse },
367
+ }),
336
368
  requireControlPlane(EMAIL_SUPPRESSIONS_WRITE_SCOPE),
337
- zValidator("json", SuppressRequest, validationHook),
369
+ validate("json", SuppressRequest),
338
370
  async (c) => {
339
371
  const input = c.req.valid("json");
340
372
  const who = caller(c);
@@ -425,8 +457,14 @@ export function registerEmailAdminRoutes(options: EmailAdminRoutesOptions): (app
425
457
 
426
458
  app.post(
427
459
  `${base}/suppressions/remove`,
460
+ describeRoute({
461
+ summary: "Lift the block on an address.",
462
+ verification: "control-plane",
463
+ scopes: [EMAIL_SUPPRESSIONS_DELETE_SCOPE],
464
+ responses: { 200: EmailUnsuppressResponse },
465
+ }),
428
466
  requireControlPlane(EMAIL_SUPPRESSIONS_DELETE_SCOPE),
429
- zValidator("json", UnsuppressRequest, validationHook),
467
+ validate("json", UnsuppressRequest),
430
468
  async (c) => {
431
469
  const input = c.req.valid("json");
432
470
  const who = caller(c);
@@ -8,7 +8,7 @@ import { EmailJobStatus, SuppressionReason } from "../data/enums";
8
8
  /**
9
9
  * The request schemas for every email route — the three public callbacks and the six control-plane
10
10
  * admin routes. Validation happens at the HTTP boundary (CLAUDE.md §Zod), declared on the route line
11
- * with `zValidator(target, Schema, validationHook)` — so reading `callbacks.ts` or `routes.ts` tells
11
+ * with `validate(target, Schema)` — so reading `callbacks.ts` or `routes.ts` tells
12
12
  * you what each route accepts without opening a handler.
13
13
  *
14
14
  * The callback schemas bound a value that already reaches the handler as free-form text. Neither tries
@@ -124,8 +124,11 @@ export interface EmailProvisioner {
124
124
  * Throws a clear, actionable error so provisioning fails fast and clean rather than mid-deploy.
125
125
  */
126
126
  preflight(): Promise<void>;
127
- /** Create (or reuse) the project's suppression D1; returns its id. Idempotent. Runs once, before any env. */
128
- ensureSuppressionDatabase(): Promise<{ databaseId: string }>;
127
+ /**
128
+ * Create (or reuse) the project's suppression D1; returns its id, and whether this call created it. Idempotent.
129
+ * Runs once, before any env.
130
+ */
131
+ ensureSuppressionDatabase(): Promise<{ databaseId: string; created: boolean }>;
129
132
  /** Run the `email_0001_suppressions` migration against the suppression D1. Idempotent (applied ones skip). */
130
133
  migrateSuppression(databaseId: string): Promise<void>;
131
134
  /** Deploy the prebuilt email worker for this environment, wired to the suppression DB and the env's own resources. */
@@ -142,6 +145,8 @@ export interface EmailProvisioner {
142
145
  /** What provisioning produced. */
143
146
  export interface EmailProvisionResult {
144
147
  suppressionDatabaseId: string;
148
+ /** Whether this run created the suppression database, or found one an earlier run made. */
149
+ suppressionDatabaseCreated: boolean;
145
150
  environments: ManagedEnvironment[];
146
151
  /** Whether the inbound routing rule was created, already present, or skipped (not configured). */
147
152
  routing: { created: boolean; skipped: boolean };
@@ -166,7 +171,7 @@ export async function provisionEmail(
166
171
  environments: DeclaredEnvironments | readonly string[],
167
172
  ): Promise<EmailProvisionResult> {
168
173
  await provisioner.preflight();
169
- const { databaseId } = await provisioner.ensureSuppressionDatabase();
174
+ const { databaseId, created } = await provisioner.ensureSuppressionDatabase();
170
175
  await provisioner.migrateSuppression(databaseId);
171
176
  const deployed = managedEnvironments(environments);
172
177
  for (const env of deployed) {
@@ -177,7 +182,7 @@ export async function provisionEmail(
177
182
  // was never deployed, which is the window this ordering exists to close.
178
183
  const routing =
179
184
  deployed.length > 0 ? await provisioner.ensureRoutingRule() : { created: false, skipped: true as const };
180
- return { suppressionDatabaseId: databaseId, environments: deployed, routing };
185
+ return { suppressionDatabaseId: databaseId, suppressionDatabaseCreated: created, environments: deployed, routing };
181
186
  }
182
187
 
183
188
  /** The teardown seam — the inverse of {@link EmailProvisioner}. Every step idempotent (a missing resource is a no-op). */
@@ -192,6 +197,11 @@ export interface EmailDeprovisioner {
192
197
  * before it deletes the list they share (#591).
193
198
  */
194
199
  hasWorker(env: ManagedEnvironment): Promise<boolean>;
200
+ /**
201
+ * Delete the env's send and schedule Workflows, by `emailWorkflowNames`. Idempotent (a Workflow already gone is
202
+ * a no-op). Deleting the worker leaves them registered, so they go first (#789).
203
+ */
204
+ deleteWorkflows(env: ManagedEnvironment): Promise<void>;
195
205
  /** Delete the env's email worker. Idempotent (a missing worker is a no-op). */
196
206
  deleteWorker(env: ManagedEnvironment): Promise<void>;
197
207
  /**
@@ -225,7 +235,10 @@ export interface EmailDeprovisionOptions {
225
235
  * 2. With `deleteSuppression` only: refuse while any other declared environment still runs an email worker
226
236
  * (`assertSharedLeavesLast`). The list is one per project, and a staging teardown must not take production's.
227
237
  * 3. Count the list, and refuse unless the operator counted the same (`assertRetainedAgreed`, #588's guard).
228
- * 4. Delete the environment's worker (it binds the list), then — only when asked — the list.
238
+ * 4. Delete the environment's Workflows (#789), then its worker (it binds the list), then — only when asked — the list.
239
+ *
240
+ * It never deletes the environment's link-signing key. `pithy secrets provision` creates that entry and binds it
241
+ * into the app Worker, which is still deployed, and every link already sent is signed with it (#596).
229
242
  *
230
243
  * Idempotent end to end: a missing worker or database is a no-op.
231
244
  */
@@ -246,6 +259,7 @@ export async function deprovisionEmail(
246
259
  "anything was deleted",
247
260
  );
248
261
  }
262
+ await deprovisioner.deleteWorkflows(env);
249
263
  await deprovisioner.deleteWorker(env);
250
264
  if (options.deleteSuppression) await deprovisioner.deleteSuppressionDatabase();
251
265
  return { env };
@@ -78,6 +78,18 @@ export const emailWorkflowRegistry: WorkflowRegistry = Object.fromEntries(
78
78
  }),
79
79
  );
80
80
 
81
+ /**
82
+ * The Workflows one environment's email worker is deployed with — `<project>-<env>-email-send` and
83
+ * `<project>-<env>-email-schedule`. Derived by the call {@link resolveEmailConfig} deploys with, so teardown
84
+ * deletes the names provision created and no others (#789). Deleting a Worker does not delete the Workflows
85
+ * registered against it.
86
+ */
87
+ export function emailWorkflowNames(project: string, env: ManagedEnvironment): string[] {
88
+ return hostWorkflowsFor(emailWorkflowRegistry, { project, capability: EMAIL_CAPABILITY, env }).workflows.map(
89
+ (workflow) => workflow.name,
90
+ );
91
+ }
92
+
81
93
  /**
82
94
  * The most one Cloudflare Worker variable holds. **Per variable, and that is the whole design.**
83
95
  *