@pithy-sh/email 0.1.2 → 0.1.4

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 (176) hide show
  1. package/dist/analytics.d.ts +21 -0
  2. package/dist/analytics.d.ts.map +1 -0
  3. package/dist/analytics.js +15 -0
  4. package/dist/audit/actions.d.ts +47 -0
  5. package/dist/audit/actions.d.ts.map +1 -0
  6. package/dist/audit/actions.js +47 -0
  7. package/dist/bounce/classify.d.ts +40 -0
  8. package/dist/bounce/classify.d.ts.map +1 -0
  9. package/dist/bounce/classify.js +48 -0
  10. package/dist/bounce/handler.d.ts +34 -0
  11. package/dist/bounce/handler.d.ts.map +1 -0
  12. package/dist/bounce/handler.js +83 -0
  13. package/dist/capability.d.ts +160 -0
  14. package/dist/capability.d.ts.map +1 -0
  15. package/dist/capability.js +257 -0
  16. package/dist/crypto/signingKey.d.ts +38 -0
  17. package/dist/crypto/signingKey.d.ts.map +1 -0
  18. package/dist/crypto/signingKey.js +38 -0
  19. package/dist/crypto/token.d.ts +49 -0
  20. package/dist/crypto/token.d.ts.map +1 -0
  21. package/dist/crypto/token.js +101 -0
  22. package/dist/data/emailEvent.d.ts +30 -0
  23. package/dist/data/emailEvent.d.ts.map +1 -0
  24. package/dist/data/emailEvent.js +24 -0
  25. package/dist/data/emailJob.d.ts +78 -0
  26. package/dist/data/emailJob.d.ts.map +1 -0
  27. package/dist/data/emailJob.js +64 -0
  28. package/dist/data/emailSuppression.d.ts +25 -0
  29. package/dist/data/emailSuppression.d.ts.map +1 -0
  30. package/dist/data/emailSuppression.js +23 -0
  31. package/dist/data/enums.d.ts +78 -0
  32. package/dist/data/enums.d.ts.map +1 -0
  33. package/dist/data/enums.js +67 -0
  34. package/dist/data/tables.d.ts +116 -0
  35. package/dist/data/tables.d.ts.map +1 -0
  36. package/dist/data/tables.js +32 -0
  37. package/dist/error/errors.d.ts +62 -0
  38. package/dist/error/errors.d.ts.map +1 -0
  39. package/dist/error/errors.js +84 -0
  40. package/dist/http/callbacks.d.ts +23 -0
  41. package/dist/http/callbacks.d.ts.map +1 -0
  42. package/dist/http/callbacks.js +112 -0
  43. package/dist/http/guards.d.ts +101 -0
  44. package/dist/http/guards.d.ts.map +1 -0
  45. package/dist/http/guards.js +146 -0
  46. package/dist/http/responses.d.ts +297 -0
  47. package/dist/http/responses.d.ts.map +1 -0
  48. package/dist/http/responses.js +117 -0
  49. package/dist/http/routes.d.ts +73 -0
  50. package/dist/http/routes.d.ts.map +1 -0
  51. package/dist/http/routes.js +294 -0
  52. package/dist/http/schemas.d.ts +92 -0
  53. package/dist/http/schemas.d.ts.map +1 -0
  54. package/dist/http/schemas.js +93 -0
  55. package/dist/http/view.d.ts +80 -0
  56. package/dist/http/view.d.ts.map +1 -0
  57. package/dist/http/view.js +132 -0
  58. package/dist/index.d.ts +48 -0
  59. package/dist/index.d.ts.map +1 -0
  60. package/dist/index.js +13 -0
  61. package/dist/jobs/read.d.ts +193 -0
  62. package/dist/jobs/read.d.ts.map +1 -0
  63. package/dist/jobs/read.js +145 -0
  64. package/dist/jobs/retry.d.ts +101 -0
  65. package/dist/jobs/retry.d.ts.map +1 -0
  66. package/dist/jobs/retry.js +69 -0
  67. package/dist/migrations/0001_init.d.ts +34 -0
  68. package/dist/migrations/0001_init.d.ts.map +1 -0
  69. package/dist/migrations/0001_init.js +62 -0
  70. package/dist/migrations/0001_suppressions.d.ts +12 -0
  71. package/dist/migrations/0001_suppressions.d.ts.map +1 -0
  72. package/dist/migrations/0001_suppressions.js +22 -0
  73. package/dist/provision/devDelivery.d.ts +34 -0
  74. package/dist/provision/devDelivery.d.ts.map +1 -0
  75. package/dist/provision/devDelivery.js +39 -0
  76. package/dist/provision/hostCatalogs.d.ts +12 -0
  77. package/dist/provision/hostCatalogs.d.ts.map +1 -0
  78. package/dist/provision/hostCatalogs.js +80 -0
  79. package/dist/provision/provisionEmail.d.ts +145 -0
  80. package/dist/provision/provisionEmail.d.ts.map +1 -0
  81. package/dist/provision/provisionEmail.js +120 -0
  82. package/dist/provision/resolveEmailConfig.d.ts +124 -0
  83. package/dist/provision/resolveEmailConfig.d.ts.map +1 -0
  84. package/dist/provision/resolveEmailConfig.js +126 -0
  85. package/dist/provision/settingsCheck.d.ts +42 -0
  86. package/dist/provision/settingsCheck.d.ts.map +1 -0
  87. package/dist/provision/settingsCheck.js +140 -0
  88. package/dist/send/batchIdentity.d.ts +44 -0
  89. package/dist/send/batchIdentity.d.ts.map +1 -0
  90. package/dist/send/batchIdentity.js +48 -0
  91. package/dist/send/enqueue.d.ts +218 -0
  92. package/dist/send/enqueue.d.ts.map +1 -0
  93. package/dist/send/enqueue.js +155 -0
  94. package/dist/send/errorMapping.d.ts +29 -0
  95. package/dist/send/errorMapping.d.ts.map +1 -0
  96. package/dist/send/errorMapping.js +54 -0
  97. package/dist/send/events.d.ts +17 -0
  98. package/dist/send/events.d.ts.map +1 -0
  99. package/dist/send/events.js +19 -0
  100. package/dist/send/fromComposition.d.ts +49 -0
  101. package/dist/send/fromComposition.d.ts.map +1 -0
  102. package/dist/send/fromComposition.js +55 -0
  103. package/dist/send/retryPolicy.d.ts +34 -0
  104. package/dist/send/retryPolicy.d.ts.map +1 -0
  105. package/dist/send/retryPolicy.js +41 -0
  106. package/dist/send/runSend.d.ts +108 -0
  107. package/dist/send/runSend.d.ts.map +1 -0
  108. package/dist/send/runSend.js +220 -0
  109. package/dist/send/sendAt.d.ts +8 -0
  110. package/dist/send/sendAt.d.ts.map +1 -0
  111. package/dist/send/sendAt.js +64 -0
  112. package/dist/send/sender.d.ts +44 -0
  113. package/dist/send/sender.d.ts.map +1 -0
  114. package/dist/send/sender.js +2 -0
  115. package/dist/send/senderBinding.d.ts +46 -0
  116. package/dist/send/senderBinding.d.ts.map +1 -0
  117. package/dist/send/senderBinding.js +23 -0
  118. package/dist/send/suppression.d.ts +95 -0
  119. package/dist/send/suppression.d.ts.map +1 -0
  120. package/dist/send/suppression.js +134 -0
  121. package/dist/templates/engine.d.ts +111 -0
  122. package/dist/templates/engine.d.ts.map +1 -0
  123. package/dist/templates/engine.js +260 -0
  124. package/dist/templates/messages.d.ts +96 -0
  125. package/dist/templates/messages.d.ts.map +1 -0
  126. package/dist/templates/messages.es.d.ts +31 -0
  127. package/dist/templates/messages.es.d.ts.map +1 -0
  128. package/dist/templates/messages.es.js +84 -0
  129. package/dist/templates/messages.js +268 -0
  130. package/dist/templates/partials.d.ts +7 -0
  131. package/dist/templates/partials.d.ts.map +1 -0
  132. package/dist/templates/partials.js +61 -0
  133. package/dist/templates/precompiled.generated.d.ts +268 -0
  134. package/dist/templates/precompiled.generated.d.ts.map +1 -0
  135. package/dist/templates/precompiled.generated.js +4041 -0
  136. package/dist/templates/registry.d.ts +120 -0
  137. package/dist/templates/registry.d.ts.map +1 -0
  138. package/dist/templates/registry.js +325 -0
  139. package/dist/templates/samples.d.ts +9 -0
  140. package/dist/templates/samples.d.ts.map +1 -0
  141. package/dist/templates/samples.js +100 -0
  142. package/dist/templates/severity.d.ts +42 -0
  143. package/dist/templates/severity.d.ts.map +1 -0
  144. package/dist/templates/severity.js +83 -0
  145. package/dist/templates/theme.d.ts +195 -0
  146. package/dist/templates/theme.d.ts.map +1 -0
  147. package/dist/templates/theme.js +170 -0
  148. package/dist/version.generated.d.ts +7 -0
  149. package/dist/version.generated.d.ts.map +1 -0
  150. package/dist/version.generated.js +9 -0
  151. package/dist/workflows/hostApp.d.ts +35 -0
  152. package/dist/workflows/hostApp.d.ts.map +1 -0
  153. package/dist/workflows/hostApp.js +21 -0
  154. package/dist/workflows/hostEnv.d.ts +131 -0
  155. package/dist/workflows/hostEnv.d.ts.map +1 -0
  156. package/dist/workflows/hostEnv.js +149 -0
  157. package/dist/workflows/instanceLiveness.d.ts +5 -0
  158. package/dist/workflows/instanceLiveness.d.ts.map +1 -0
  159. package/dist/workflows/instanceLiveness.js +39 -0
  160. package/dist/workflows/instances.d.ts +20 -0
  161. package/dist/workflows/instances.d.ts.map +1 -0
  162. package/dist/workflows/instances.js +2 -0
  163. package/dist/workflows/params.d.ts +25 -0
  164. package/dist/workflows/params.d.ts.map +1 -0
  165. package/dist/workflows/params.js +23 -0
  166. package/dist/workflows/scheduler.d.ts +84 -0
  167. package/dist/workflows/scheduler.d.ts.map +1 -0
  168. package/dist/workflows/scheduler.js +113 -0
  169. package/dist/workflows/sendBatch.d.ts +87 -0
  170. package/dist/workflows/sendBatch.d.ts.map +1 -0
  171. package/dist/workflows/sendBatch.js +52 -0
  172. package/dist/workflows/worker.d.ts +102 -0
  173. package/dist/workflows/worker.d.ts.map +1 -0
  174. package/dist/workflows/worker.js +119 -0
  175. package/package.json +22 -11
  176. package/src/version.generated.ts +1 -1
@@ -0,0 +1,117 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { EmailJobStatus, SendMode, SuppressionReason, TemplateCategory } from "../data/enums.js";
4
+ import { z } from "zod";
5
+ //#region src/http/responses.ts
6
+ /**
7
+ * What the email management routes return, as Zod objects a management client can validate against.
8
+ *
9
+ * `schemas.ts` bounds what a caller may send; this file states what it gets back. Both halves are
10
+ * runtime values for the same reason: a management client reading a customer's Worker is crossing a
11
+ * trust boundary and must validate what comes back, and a TypeScript interface is erased before it
12
+ * can help. Every client that had only an interface hand-wrote a mirror of these, and the mirror
13
+ * drifted the first time a field landed here.
14
+ *
15
+ * **No codecs, and no transform anywhere in this file.** These describe JSON on the wire, so parsing
16
+ * one hands back exactly what went in — which is what lets `responses.test.ts` compare a parsed value
17
+ * with the projection's output and fail on a field either side forgot.
18
+ *
19
+ * The projections live in `view.ts`, which documents *why* the list masks a recipient and the detail
20
+ * does not, and why `payload` appears in neither. This file is the shape; that file is the argument.
21
+ *
22
+ * **A field added here later is `.optional()`, not merely `.nullable()`.** This module is read across a
23
+ * version boundary — a management client validates a response with this schema against a customer's
24
+ * Worker at whatever kit version it is on — so an additive required key fails `safeParse` for everyone
25
+ * below that release and takes the whole pane with it (#450). Absent then means *this Worker cannot
26
+ * say*, which is a different fact from `null`.
27
+ */
28
+ /** Where a page resumes, or the end of the list. */
29
+ const NextCursor = z.string().nullable().describe("Where the next page resumes. Null at the end of the list. Opaque — pass it back verbatim.");
30
+ /** One job as the list shows it: enough to scan, not enough to harvest. */
31
+ const EmailJobListItem = z.object({
32
+ id: z.string().describe("The job id — what the detail and retry routes take."),
33
+ recipient: z.string().describe("The recipient, masked (`ad***@example.com`). The detail route has the whole address."),
34
+ template: z.string().describe("The template that produced this email. Structural, so it names the kind of mail with no content."),
35
+ category: TemplateCategory.describe("`transactional` or `marketing`."),
36
+ locale: z.string().nullable().optional().describe("The language this message was written in, as a BCP-47 tag; null when the recipient never chose one and it went out in the kit's English, and absent when the Worker that answered predates the field (#450)."),
37
+ status: EmailJobStatus.describe("The lifecycle state."),
38
+ mode: SendMode.describe("How the send time was decided."),
39
+ attempts: z.number().int().describe("How many send attempts have been made."),
40
+ campaignId: z.string().nullable().describe("The campaign this belongs to; null for transactional mail."),
41
+ bounceType: z.string().nullable().describe("How a bounce was classified (`hard` | `soft` | `complaint` | `auto_reply`), when one arrived. A loose string rather than the enum, because the column is one: a response schema that narrowed what the table admits would reject a row this Worker can legitimately hold, and the place to close that is the column, not the wire."),
42
+ failed: z.boolean().describe("Whether the row carries an error, without carrying it — a provider error routinely embeds the recipient, so the text is on the detail route."),
43
+ sendAt: z.iso.datetime().describe("When this job is (or was) due to send, ISO-8601."),
44
+ createdAt: z.iso.datetime().describe("When the row was created, ISO-8601. The list's sort key."),
45
+ sentAt: z.iso.datetime().nullable().describe("When the send succeeded, ISO-8601; null until then.")
46
+ }).describe("One email job as the send log lists it. The recipient is masked and no rendered content appears.");
47
+ /**
48
+ * One job in full.
49
+ *
50
+ * Re-described after `.omit()`/`.extend()`: each builds a new schema, and a description does not
51
+ * follow it.
52
+ *
53
+ * `locale` is **not** re-declared below. It is on the list item, so the detail inherits it and there is
54
+ * one sentence describing the tag rather than two free to drift — and the fact the detail's own copy
55
+ * used to carry, that null means nobody chose, is the fact the list needs most.
56
+ */
57
+ const EmailJobDetail = EmailJobListItem.omit({
58
+ recipient: true,
59
+ failed: true
60
+ }).extend({
61
+ toAddress: z.string().describe("The recipient, in full. Disclosed one job at a time, and audited as such."),
62
+ subject: z.string().describe("The rendered subject line — the one piece of rendered content a send cannot be diagnosed without."),
63
+ fromAddress: z.string().describe("The sending identity — the adopter's own configuration."),
64
+ fromName: z.string().describe("The sender display name recipients saw."),
65
+ messageId: z.string().nullable().describe("The Email Service message id a later bounce is attributed through."),
66
+ error: z.string().nullable().describe("The last error recorded against this job; null when healthy."),
67
+ bounceCode: z.string().nullable().describe("The SMTP or Email Service code from a bounce; null unless it bounced."),
68
+ timezone: z.string().nullable().describe("The recipient's IANA timezone, for a `timezone`-mode send."),
69
+ localTime: z.string().nullable().describe("The recipient-local time-of-day, for a `timezone`-mode send."),
70
+ openTracking: z.boolean().describe("Whether an open-tracking pixel was injected."),
71
+ clickTracking: z.boolean().describe("Whether links were rewritten to tracked callbacks."),
72
+ updatedAt: z.iso.datetime().describe("When the row was last written, ISO-8601.")
73
+ }).describe("One email job in full. Never the template payload — that is the sign-in link and the OTP.");
74
+ /** One suppressed address, as a management client sees it. */
75
+ const EmailSuppressionView = z.object({
76
+ id: z.number().int().describe("The row's surrogate key — the handle the audit trail names."),
77
+ email: z.string().describe("The blocked address, in full. The record is the address, so there is nothing to mask."),
78
+ reason: SuppressionReason.describe("Why it is blocked: hard bounce, complaint, unsubscribe, or a manual block."),
79
+ environment: z.string().nullable().describe("The environment the triggering job came from; the block itself applies everywhere."),
80
+ jobId: z.string().nullable().describe("The job that triggered it, when one did."),
81
+ detail: z.string().nullable().describe("Free-form context — the bounce code, or what an operator typed."),
82
+ createdAt: z.iso.datetime().describe("When the address was blocked, ISO-8601."),
83
+ expiresAt: z.iso.datetime().nullable().describe("When a temporary block lifts, ISO-8601; null when permanent."),
84
+ active: z.boolean().describe("Whether the block is in force right now. Computed here, so no client re-implements the comparison the send path already makes.")
85
+ }).describe("One suppressed address, with the block's provenance and whether it is in force.");
86
+ /** `GET {base}/jobs`. */
87
+ const EmailJobsResponse = z.object({
88
+ jobs: z.array(EmailJobListItem).describe("The page, newest first."),
89
+ nextCursor: NextCursor
90
+ }).describe("A page of the send log.");
91
+ /** `GET {base}/jobs/:id`. */
92
+ const EmailJobResponse = z.object({ job: EmailJobDetail.describe("The job, whole recipient included.") }).describe("One email job in full.");
93
+ /** `POST {base}/jobs/:id/retry`. */
94
+ const EmailJobRetryResponse = z.object({
95
+ job: EmailJobDetail.describe("The job as the retry left it."),
96
+ dispatched: z.boolean().describe("Whether a send Workflow actually started. False when no sender is bound — the row is queued, and nothing was mailed.")
97
+ }).describe("The retried job, and whether a send actually started.");
98
+ /** `GET {base}/suppressions`. */
99
+ const EmailSuppressionsResponse = z.object({
100
+ suppressions: z.array(EmailSuppressionView).describe("The page, newest first."),
101
+ nextCursor: NextCursor
102
+ }).describe("A page of the suppression list.");
103
+ /** `POST {base}/suppressions`. */
104
+ const EmailSuppressResponse = z.object({ suppression: EmailSuppressionView.nullable().describe("The row as stored, read back so the response is the truth rather than the request echoed. Null only if the read-back found nothing.") }).describe("The address as the suppression list now holds it.");
105
+ /**
106
+ * `POST {base}/suppressions/remove`.
107
+ *
108
+ * The address is echoed because the caller sent it, normalized so the client learns which row was
109
+ * addressed rather than guessing at the lowercasing. Nothing about the block that was lifted appears:
110
+ * that is in the audit trail, where reading it needs its own grant.
111
+ */
112
+ const EmailUnsuppressResponse = z.object({
113
+ email: z.string().describe("The address, normalized the way the suppression list stores it."),
114
+ removed: z.boolean().describe("Whether a row was removed. False when the address was not on the list.")
115
+ }).describe("Which address was unblocked, and whether there was anything to unblock.");
116
+ //#endregion
117
+ export { EmailJobDetail, EmailJobListItem, EmailJobResponse, EmailJobRetryResponse, EmailJobsResponse, EmailSuppressResponse, EmailSuppressionView, EmailSuppressionsResponse, EmailUnsuppressResponse };
@@ -0,0 +1,73 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import type { PithyHonoEnv } from "@pithy-sh/core/src/capability/capability";
4
+ import type { ControlPlaneScope } from "@pithy-sh/core/src/controlPlane/scope/scope";
5
+ import type { VerificationStrategy } from "@pithy-sh/core/src/http/verification";
6
+ import type { Hono } from "hono";
7
+ /**
8
+ * The email management routes, their declared verification strategies, and what each accepts:
9
+ *
10
+ * GET /email/jobs → the send log (control-plane: email:jobs:read) query
11
+ * GET /email/jobs/:id → one job in full (control-plane: email:jobs:read) param
12
+ * POST /email/jobs/:id/retry → queue it again (control-plane: email:jobs:retry) param
13
+ * GET /email/suppressions → who we won't mail (control-plane: email:suppressions:read) query
14
+ * POST /email/suppressions → block an address (control-plane: email:suppressions:write) json
15
+ * POST /email/suppressions/remove → unblock one (control-plane: email:suppressions:delete) json
16
+ *
17
+ * **Every route here is `control-plane`, and there is no end-user surface in this file.** A recipient
18
+ * interacts with email by receiving it; the three routes a recipient does call — click, open,
19
+ * unsubscribe — live in `callbacks.ts`, are public, and are gated by the signature on the token in the
20
+ * path. Nothing below has any business answering an ordinary user, and with the seam uncomposed every
21
+ * one of them answers 403 `controlplane/not_connected`.
22
+ *
23
+ * **Validators sit after the gate on every line.** A validator ahead of it turns a 403 into a 400 and
24
+ * tells an unverified caller which requests were well-formed — on this surface that is a live oracle
25
+ * for the shape of the send log and, worse, a way to learn that a given address parses as one this
26
+ * deployment would accept.
27
+ *
28
+ * **Every response has an exported schema**, in `responses.ts`, and each `c.json` below is
29
+ * `satisfies`-checked against its envelope. A management client imports the same object and validates
30
+ * with it rather than hand-writing a mirror that drifts. The check is at compile time on purpose:
31
+ * parsing every response would spend a validation pass on rows this Worker just read, and would turn a
32
+ * shape mistake into a 500 in production rather than a red build.
33
+ *
34
+ * **Removal is a POST with a body, not `DELETE /suppressions/:email`.** An address in a path is an
35
+ * address in every access log, every proxy, every trace, and every referrer between the client and the
36
+ * Worker. The record is personal data whether or not it is a person's current address, so it travels in
37
+ * a body. Testers' `POST /remove` is the same call made for the same reason.
38
+ */
39
+ /** What every route this capability mounts declares: its path, its strategy, and the scope it checks. */
40
+ export interface EmailRouteDeclaration {
41
+ readonly method: "GET" | "POST";
42
+ /** The path relative to the configured `basePath`, e.g. `/jobs`. */
43
+ readonly path: string;
44
+ readonly strategy: VerificationStrategy;
45
+ /** The control-plane scope this route checks. */
46
+ readonly scope: ControlPlaneScope;
47
+ }
48
+ /**
49
+ * Every management route, and how it is gated.
50
+ *
51
+ * Exported so a test can assert against the declaration rather than against a middleware count. A count
52
+ * proves that *something* runs before the handler — a bare `zValidator` satisfies it — and cannot prove
53
+ * *what*. `routeContract.test.ts` checks this list against the paths Hono actually registered, in both
54
+ * directions, so a route added without an entry and an entry without a route both fail.
55
+ */
56
+ export declare const EMAIL_ADMIN_ROUTES: readonly EmailRouteDeclaration[];
57
+ /** How the email management sub-router is built. */
58
+ export interface EmailAdminRoutesOptions {
59
+ /**
60
+ * Where the routes mount.
61
+ *
62
+ * Required, with no default of its own. The manifest advertises these paths and a client composes its
63
+ * calls from the manifest, so the mount point and the advertised path must come from one value — a
64
+ * default here and a default in the config is two, and the day they disagree every management call
65
+ * 404s against exactly the adopters who customized anything.
66
+ */
67
+ basePath: string;
68
+ /** The clock. Injected so retried timestamps are deterministic in tests. */
69
+ now?: () => Date;
70
+ }
71
+ /** Register the email management sub-router. Composed alongside the public callbacks. */
72
+ export declare function registerEmailAdminRoutes(options: EmailAdminRoutesOptions): (app: Hono<PithyHonoEnv>) => void;
73
+ //# sourceMappingURL=routes.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"routes.d.ts","sourceRoot":"","sources":["../../src/http/routes.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,0CAA0C,CAAC;AAG7E,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,6CAA6C,CAAC;AAGrF,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,sCAAsC,CAAC;AACjF,OAAO,KAAK,EAAW,IAAI,EAAE,MAAM,MAAM,CAAC;AA+B1C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AAEH,yGAAyG;AACzG,MAAM,WAAW,qBAAqB;IACpC,QAAQ,CAAC,MAAM,EAAE,KAAK,GAAG,MAAM,CAAC;IAChC,oEAAoE;IACpE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,QAAQ,EAAE,oBAAoB,CAAC;IACxC,iDAAiD;IACjD,QAAQ,CAAC,KAAK,EAAE,iBAAiB,CAAC;CACnC;AAED;;;;;;;GAOG;AACH,eAAO,MAAM,kBAAkB,EAAE,SAAS,qBAAqB,EAY9D,CAAC;AAaF,oDAAoD;AACpD,MAAM,WAAW,uBAAuB;IACtC;;;;;;;OAOG;IACH,QAAQ,EAAE,MAAM,CAAC;IACjB,4EAA4E;IAC5E,GAAG,CAAC,EAAE,MAAM,IAAI,CAAC;CAClB;AAiDD,yFAAyF;AACzF,wBAAgB,wBAAwB,CAAC,OAAO,EAAE,uBAAuB,GAAG,CAAC,GAAG,EAAE,IAAI,CAAC,YAAY,CAAC,KAAK,IAAI,CA2R5G"}
@@ -0,0 +1,294 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { emailDatabase, emailSuppressionDatabase } from "../data/tables.js";
4
+ import { listSuppressions, suppress, unsuppress } from "../send/suppression.js";
5
+ import { JobIdParam, JobsQuery, SuppressRequest, SuppressionsQuery, UnsuppressRequest } from "./schemas.js";
6
+ import { EMAIL_JOBS_READ_SCOPE, EMAIL_JOBS_RETRY_SCOPE, EMAIL_SUPPRESSIONS_DELETE_SCOPE, EMAIL_SUPPRESSIONS_READ_SCOPE, EMAIL_SUPPRESSIONS_WRITE_SCOPE } from "./guards.js";
7
+ import { EmailAuditActions } from "../audit/actions.js";
8
+ import { getJob, listJobs } from "../jobs/read.js";
9
+ import { retryJob } from "../jobs/retry.js";
10
+ import { emailSenderBinding } from "../send/senderBinding.js";
11
+ import { jobDetailView, jobListView, suppressionView } from "./view.js";
12
+ import { ConflictError, InternalError, NotFoundError, ValidationError } from "@pithy-sh/core/src/error/pithyError";
13
+ import { normalizeAddress } from "@pithy-sh/core/src/address/address";
14
+ import { zValidator } from "@hono/zod-validator";
15
+ import { validationHook } from "@pithy-sh/core/src/http/validation";
16
+ import { requireControlPlane } from "@pithy-sh/core/src/controlPlane/http/guard";
17
+ //#region src/http/routes.ts
18
+ /**
19
+ * Every management route, and how it is gated.
20
+ *
21
+ * Exported so a test can assert against the declaration rather than against a middleware count. A count
22
+ * proves that *something* runs before the handler — a bare `zValidator` satisfies it — and cannot prove
23
+ * *what*. `routeContract.test.ts` checks this list against the paths Hono actually registered, in both
24
+ * directions, so a route added without an entry and an entry without a route both fail.
25
+ */
26
+ const EMAIL_ADMIN_ROUTES = [
27
+ {
28
+ method: "GET",
29
+ path: "/jobs",
30
+ strategy: "control-plane",
31
+ scope: EMAIL_JOBS_READ_SCOPE
32
+ },
33
+ {
34
+ method: "GET",
35
+ path: "/jobs/:id",
36
+ strategy: "control-plane",
37
+ scope: EMAIL_JOBS_READ_SCOPE
38
+ },
39
+ {
40
+ method: "POST",
41
+ path: "/jobs/:id/retry",
42
+ strategy: "control-plane",
43
+ scope: EMAIL_JOBS_RETRY_SCOPE
44
+ },
45
+ {
46
+ method: "GET",
47
+ path: "/suppressions",
48
+ strategy: "control-plane",
49
+ scope: EMAIL_SUPPRESSIONS_READ_SCOPE
50
+ },
51
+ {
52
+ method: "POST",
53
+ path: "/suppressions",
54
+ strategy: "control-plane",
55
+ scope: EMAIL_SUPPRESSIONS_WRITE_SCOPE
56
+ },
57
+ {
58
+ method: "POST",
59
+ path: "/suppressions/remove",
60
+ strategy: "control-plane",
61
+ scope: EMAIL_SUPPRESSIONS_DELETE_SCOPE
62
+ }
63
+ ];
64
+ /**
65
+ * A required D1 binding, or a stated wiring failure.
66
+ *
67
+ * `email()` declares both databases in `requiredBindings`, so an absent one is a Worker assembled
68
+ * wrong rather than a request doing anything unusual — hence a 500 that names the fix, not a 4xx that
69
+ * blames the caller.
70
+ */
71
+ function d1(c, binding) {
72
+ const found = c.env[binding];
73
+ if (!found) throw new InternalError({
74
+ message: "Email is not fully configured on this Worker.",
75
+ action: `Bind a D1 database named ${binding} in wrangler.jsonc, then run pithy migrate.`,
76
+ detail: `the email management routes require a \`${binding}\` D1 binding; none was present on env`
77
+ });
78
+ return found;
79
+ }
80
+ /** The per-environment jobs database. */
81
+ function jobs(c) {
82
+ return emailDatabase(d1(c, "DB"));
83
+ }
84
+ /** The global suppression database. */
85
+ function suppressions(c) {
86
+ return emailSuppressionDatabase(d1(c, "EMAIL_SUPPRESSIONS"));
87
+ }
88
+ /**
89
+ * The verified management caller.
90
+ *
91
+ * `requireControlPlane()` has run on every route in this file, so a null here is a route mounted
92
+ * without its gate — a programming error, not an unauthenticated request, and therefore an internal
93
+ * error rather than a 401 that would imply a credential could fix it.
94
+ */
95
+ function caller(c) {
96
+ const context = c.var.controlPlane;
97
+ if (!context) throw new InternalError({
98
+ message: "Email could not identify the management caller.",
99
+ detail: "requireControlPlane() must run before an email handler reads the caller."
100
+ });
101
+ return context;
102
+ }
103
+ /** Register the email management sub-router. Composed alongside the public callbacks. */
104
+ function registerEmailAdminRoutes(options) {
105
+ const base = options.basePath;
106
+ const clock = options.now ?? (() => /* @__PURE__ */ new Date());
107
+ return (app) => {
108
+ app.get(`${base}/jobs`, requireControlPlane(EMAIL_JOBS_READ_SCOPE), zValidator("query", JobsQuery, validationHook), async (c) => {
109
+ const query = c.req.valid("query");
110
+ const who = caller(c);
111
+ const page = await listJobs(jobs(c), query);
112
+ await c.var.emit({
113
+ action: EmailAuditActions.jobsRead,
114
+ outcome: "success",
115
+ actorType: "control-plane",
116
+ actorId: who.subject,
117
+ resourceType: "email_job",
118
+ resourceId: null,
119
+ metadata: {
120
+ connectionId: who.connectionId,
121
+ status: query.status ?? null,
122
+ returned: page.items.length,
123
+ paged: Boolean(query.cursor)
124
+ }
125
+ });
126
+ return c.json({
127
+ jobs: page.items.map(jobListView),
128
+ nextCursor: page.nextCursor
129
+ });
130
+ });
131
+ app.get(`${base}/jobs/:id`, requireControlPlane(EMAIL_JOBS_READ_SCOPE), zValidator("param", JobIdParam, validationHook), async (c) => {
132
+ const { id } = c.req.valid("param");
133
+ const who = caller(c);
134
+ const job = await getJob(jobs(c), id);
135
+ if (!job) throw new NotFoundError({
136
+ message: "No such email job.",
137
+ action: "Check the job id against the send log.",
138
+ detail: `email job '${id}' not found`
139
+ });
140
+ await c.var.emit({
141
+ action: EmailAuditActions.jobRead,
142
+ outcome: "success",
143
+ actorType: "control-plane",
144
+ actorId: who.subject,
145
+ resourceType: "email_job",
146
+ resourceId: job.id,
147
+ metadata: {
148
+ connectionId: who.connectionId,
149
+ status: job.status,
150
+ template: job.template
151
+ }
152
+ });
153
+ return c.json({ job: jobDetailView(job) });
154
+ });
155
+ app.post(`${base}/jobs/:id/retry`, requireControlPlane(EMAIL_JOBS_RETRY_SCOPE), zValidator("param", JobIdParam, validationHook), async (c) => {
156
+ const { id } = c.req.valid("param");
157
+ const who = caller(c);
158
+ const now = clock();
159
+ const db = jobs(c);
160
+ const before = await getJob(db, id);
161
+ const result = await retryJob({
162
+ db,
163
+ suppressionDb: suppressions(c),
164
+ sender: emailSenderBinding(c.env),
165
+ now
166
+ }, id);
167
+ await c.var.emit({
168
+ action: EmailAuditActions.jobRetried,
169
+ outcome: "success",
170
+ severity: "warning",
171
+ actorType: "control-plane",
172
+ actorId: who.subject,
173
+ resourceType: "email_job",
174
+ resourceId: result.job.id,
175
+ metadata: {
176
+ connectionId: who.connectionId,
177
+ from: before?.status ?? null,
178
+ template: result.job.template,
179
+ dispatched: result.dispatched
180
+ }
181
+ });
182
+ return c.json({
183
+ job: jobDetailView(result.job),
184
+ dispatched: result.dispatched
185
+ });
186
+ });
187
+ app.get(`${base}/suppressions`, requireControlPlane(EMAIL_SUPPRESSIONS_READ_SCOPE), zValidator("query", SuppressionsQuery, validationHook), async (c) => {
188
+ const query = c.req.valid("query");
189
+ const who = caller(c);
190
+ const now = clock();
191
+ const page = await listSuppressions(suppressions(c), query);
192
+ await c.var.emit({
193
+ action: EmailAuditActions.suppressionsRead,
194
+ outcome: "success",
195
+ actorType: "control-plane",
196
+ actorId: who.subject,
197
+ resourceType: "email_suppression",
198
+ resourceId: null,
199
+ metadata: {
200
+ connectionId: who.connectionId,
201
+ reason: query.reason ?? null,
202
+ lookup: Boolean(query.email),
203
+ returned: page.items.length,
204
+ paged: Boolean(query.cursor)
205
+ }
206
+ });
207
+ return c.json({
208
+ suppressions: page.items.map((row) => suppressionView(row, now)),
209
+ nextCursor: page.nextCursor
210
+ });
211
+ });
212
+ app.post(`${base}/suppressions`, requireControlPlane(EMAIL_SUPPRESSIONS_WRITE_SCOPE), zValidator("json", SuppressRequest, validationHook), async (c) => {
213
+ const input = c.req.valid("json");
214
+ const who = caller(c);
215
+ const now = clock();
216
+ const email = normalizeAddress(input.email);
217
+ const db = suppressions(c);
218
+ const expiresAt = input.expiresAt ? new Date(input.expiresAt) : null;
219
+ if (expiresAt && expiresAt.getTime() <= now.getTime()) throw new ValidationError({
220
+ message: "That expiry has already passed, so it would not block anything.",
221
+ action: "Give a future instant, or omit `expiresAt` to block permanently. To lift an existing block, use the remove route — it requires `email:suppressions:delete`.",
222
+ detail: `refused suppression for ${email} with expiresAt ${expiresAt.toISOString()} at ${now.toISOString()}`
223
+ });
224
+ const current = (await listSuppressions(db, {
225
+ email,
226
+ limit: 1
227
+ })).items[0];
228
+ if (current && current.reason !== "manual") throw new ConflictError({
229
+ message: `${email} is already suppressed as a ${current.reason}, which this route may not overwrite.`,
230
+ action: "Lift it with the remove route, which requires `email:suppressions:delete` — undoing a bounce, a complaint, or someone's own opt-out is a separate decision.",
231
+ detail: `refused manual suppression over an existing ${current.reason} for ${email}`
232
+ });
233
+ await suppress(db, {
234
+ email,
235
+ reason: "manual",
236
+ detail: input.detail ?? "blocked by a management client",
237
+ environment: c.env.ENVIRONMENT ?? null,
238
+ expiresAt
239
+ }, now);
240
+ const row = (await listSuppressions(db, {
241
+ email,
242
+ limit: 1
243
+ })).items[0];
244
+ await c.var.emit({
245
+ action: EmailAuditActions.suppressionAdded,
246
+ outcome: "success",
247
+ severity: "warning",
248
+ actorType: "control-plane",
249
+ actorId: who.subject,
250
+ resourceType: "email_suppression",
251
+ resourceId: row ? String(row.id) : null,
252
+ metadata: {
253
+ connectionId: who.connectionId,
254
+ email,
255
+ reason: "manual",
256
+ expiresAt: input.expiresAt ?? null
257
+ }
258
+ });
259
+ return c.json({ suppression: row ? suppressionView(row, now) : null }, 200);
260
+ });
261
+ app.post(`${base}/suppressions/remove`, requireControlPlane(EMAIL_SUPPRESSIONS_DELETE_SCOPE), zValidator("json", UnsuppressRequest, validationHook), async (c) => {
262
+ const input = c.req.valid("json");
263
+ const who = caller(c);
264
+ const email = normalizeAddress(input.email);
265
+ const db = suppressions(c);
266
+ const existing = (await listSuppressions(db, {
267
+ email,
268
+ limit: 1
269
+ })).items[0];
270
+ const removed = await unsuppress(db, email);
271
+ await c.var.emit({
272
+ action: EmailAuditActions.suppressionRemoved,
273
+ outcome: "success",
274
+ severity: "warning",
275
+ actorType: "control-plane",
276
+ actorId: who.subject,
277
+ resourceType: "email_suppression",
278
+ resourceId: existing?.id ? String(existing.id) : null,
279
+ metadata: {
280
+ connectionId: who.connectionId,
281
+ email,
282
+ removed,
283
+ reason: existing?.reason ?? null
284
+ }
285
+ });
286
+ return c.json({
287
+ email,
288
+ removed
289
+ }, 200);
290
+ });
291
+ };
292
+ }
293
+ //#endregion
294
+ export { EMAIL_ADMIN_ROUTES, registerEmailAdminRoutes };
@@ -0,0 +1,92 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { z } from "zod";
4
+ /**
5
+ * The `:token` path parameter every callback route carries. A shape and size bound only — the ceiling
6
+ * is generous enough for a click token whose signed claims embed a long destination URL, so no link we
7
+ * mint can exceed it, while an unbounded segment can no longer reach the verifier.
8
+ */
9
+ export declare const CallbackTokenParam: z.ZodObject<{
10
+ token: z.ZodString;
11
+ }, z.core.$strip>;
12
+ export type CallbackTokenParam = z.output<typeof CallbackTokenParam>;
13
+ /**
14
+ * The optional `?reason=` on the unsubscribe callback — supplied by the app's own preferences flow.
15
+ * The bound is a ceiling, not the storage limit: the handler still truncates to 200 characters before
16
+ * writing, so every real value keeps behaving exactly as it did and only an absurd one is refused.
17
+ */
18
+ export declare const UnsubscribeQuery: z.ZodObject<{
19
+ reason: z.ZodOptional<z.ZodString>;
20
+ }, z.core.$strip>;
21
+ export type UnsubscribeQuery = z.output<typeof UnsubscribeQuery>;
22
+ /**
23
+ * The `:id` of one job.
24
+ *
25
+ * Shape and size, not `.uuid()`. Production ids are `crypto.randomUUID()`, but `newId` is an injected
26
+ * dependency of `enqueueEmail`, so a consumer supplying its own generator would find every one of its
27
+ * jobs answering 400 at a route that never reached the lookup. A param schema constrains the string;
28
+ * the handler still does the lookup and still raises its own 404.
29
+ */
30
+ export declare const JobIdParam: z.ZodObject<{
31
+ id: z.ZodString;
32
+ }, z.core.$strip>;
33
+ export type JobIdParam = z.output<typeof JobIdParam>;
34
+ /** The job log query. */
35
+ export declare const JobsQuery: z.ZodObject<{
36
+ status: z.ZodOptional<z.ZodEnum<{
37
+ bounced: "bounced";
38
+ canceled: "canceled";
39
+ failed: "failed";
40
+ pending: "pending";
41
+ scheduled: "scheduled";
42
+ sending: "sending";
43
+ sent: "sent";
44
+ suppressed: "suppressed";
45
+ undispatched: "undispatched";
46
+ }>>;
47
+ cursor: z.ZodOptional<z.ZodString>;
48
+ limit: z.ZodOptional<z.ZodCoercedNumber<unknown>>;
49
+ }, z.core.$strip>;
50
+ export type JobsQuery = z.output<typeof JobsQuery>;
51
+ /**
52
+ * The suppression list query.
53
+ *
54
+ * `email` is an exact-match lookup rather than a search, and that is the point: answering "is this one
55
+ * address blocked" should not require paging a list of every other person who ever unsubscribed. A
56
+ * prefix or substring search would turn the endpoint into a way to enumerate the list a page at a time
57
+ * while looking like a lookup.
58
+ */
59
+ export declare const SuppressionsQuery: z.ZodObject<{
60
+ reason: z.ZodOptional<z.ZodEnum<{
61
+ complaint: "complaint";
62
+ hard_bounce: "hard_bounce";
63
+ manual: "manual";
64
+ unsubscribe: "unsubscribe";
65
+ }>>;
66
+ email: z.ZodOptional<z.ZodString>;
67
+ cursor: z.ZodOptional<z.ZodString>;
68
+ limit: z.ZodOptional<z.ZodCoercedNumber<unknown>>;
69
+ }, z.core.$strip>;
70
+ export type SuppressionsQuery = z.output<typeof SuppressionsQuery>;
71
+ /**
72
+ * Block an address by hand.
73
+ *
74
+ * **There is no `reason` field, on purpose.** The column records *why an address is blocked*, and three
75
+ * of its four values (`hard_bounce`, `complaint`, `unsubscribe`) are facts the system observed: a
76
+ * bounce arrived, a complaint arrived, a recipient followed their own opt-out link. A management client
77
+ * observed none of them, so letting it name one would let an operator's assertion enter the record as
78
+ * an observation, and the deliverability decisions read off that column would be made on fiction. Every
79
+ * address blocked through this route is `manual`, and what the operator knows goes in `detail`.
80
+ */
81
+ export declare const SuppressRequest: z.ZodObject<{
82
+ email: z.ZodEmail;
83
+ detail: z.ZodOptional<z.ZodString>;
84
+ expiresAt: z.ZodOptional<z.ZodISODateTime>;
85
+ }, z.core.$strip>;
86
+ export type SuppressRequest = z.output<typeof SuppressRequest>;
87
+ /** Unblock an address — the undo of {@link SuppressRequest}, and of a bounce, complaint, or opt-out. */
88
+ export declare const UnsuppressRequest: z.ZodObject<{
89
+ email: z.ZodString;
90
+ }, z.core.$strip>;
91
+ export type UnsuppressRequest = z.output<typeof UnsuppressRequest>;
92
+ //# sourceMappingURL=schemas.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schemas.d.ts","sourceRoot":"","sources":["../../src/http/schemas.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AA0BxB;;;;GAIG;AACH,eAAO,MAAM,kBAAkB;;iBASoD,CAAC;AACpF,MAAM,MAAM,kBAAkB,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,kBAAkB,CAAC,CAAC;AAErE;;;;GAIG;AACH,eAAO,MAAM,gBAAgB;;iBAQqD,CAAC;AACnF,MAAM,MAAM,gBAAgB,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,gBAAgB,CAAC,CAAC;AAoDjE;;;;;;;GAOG;AACH,eAAO,MAAM,UAAU;;iBAS2C,CAAC;AACnE,MAAM,MAAM,UAAU,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,UAAU,CAAC,CAAC;AAErD,yBAAyB;AACzB,eAAO,MAAM,SAAS;;;;;;;;;;;;;;iBAQ2D,CAAC;AAClF,MAAM,MAAM,SAAS,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,SAAS,CAAC,CAAC;AAEnD;;;;;;;GAOG;AACH,eAAO,MAAM,iBAAiB;;;;;;;;;;iBAW8E,CAAC;AAC7G,MAAM,MAAM,iBAAiB,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,iBAAiB,CAAC,CAAC;AAEnE;;;;;;;;;GASG;AACH,eAAO,MAAM,eAAe;;;;iBAgBqD,CAAC;AAClF,MAAM,MAAM,eAAe,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,eAAe,CAAC,CAAC;AAE/D,wGAAwG;AACxG,eAAO,MAAM,iBAAiB;;iBAI+D,CAAC;AAC9F,MAAM,MAAM,iBAAiB,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,iBAAiB,CAAC,CAAC"}