@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
@@ -9,12 +9,13 @@ import type {
9
9
  SettingsFinding,
10
10
  } from "@pithy-sh/core/src/capability/settings";
11
11
  import { hostEnvFindings } from "@pithy-sh/core/src/capability/settings";
12
+ import { type Command, personDecision, pithyCommand, remedy, workerDirOf } from "@pithy-sh/core/src/cli/command";
12
13
  import { LOCAL_ORIGIN } from "@pithy-sh/core/src/naming/domains";
13
14
  import { environmentScope, type SecretNameScope } from "@pithy-sh/core/src/naming/provisionScope";
14
- import { checkHostEnv } from "@pithy-sh/core/src/workflow/hostEnv";
15
+ import { checkHostEnv, type HostEnvReport } from "@pithy-sh/core/src/workflow/hostEnv";
15
16
  import { EMAIL_LINK_SIGNING_KEY, EMAIL_LINK_SIGNING_KEY_BINDING, emailSigningRegistry } from "../crypto/signingKey";
16
17
  import type { EmailTheme } from "../templates/theme";
17
- import { emailHostEnv } from "../workflows/hostEnv";
18
+ import { EMAIL_PROVISION, emailHostEnv } from "../workflows/hostEnv";
18
19
  import { suppressionDatabaseName } from "./provisionEmail";
19
20
 
20
21
  /**
@@ -103,7 +104,7 @@ function originOf(url: string): string | null {
103
104
  * config object per Worker, so a `BASE_URL` that is not a URL is one edit however many environments a
104
105
  * project declares. Three lines about one key is how a report stops being read.
105
106
  */
106
- function localHostEnv(config: EmailSettingsInput): SettingsFinding[] {
107
+ function localHostEnv(config: EmailSettingsInput, workerDirectory: string): SettingsFinding[] {
107
108
  const candidate = {
108
109
  ...stubBindings(),
109
110
  BASE_URL: config.baseUrl,
@@ -112,7 +113,33 @@ function localHostEnv(config: EmailSettingsInput): SettingsFinding[] {
112
113
  // failure this catches.
113
114
  ...(config.theme ? { EMAIL_THEME: JSON.stringify(config.theme) } : {}),
114
115
  };
115
- return hostEnvFindings(checkHostEnv(emailHostEnv, candidate), null);
116
+ return hostEnvFindings(forWorker(checkHostEnv(emailHostEnv, candidate), workerDirectory), null);
117
+ }
118
+
119
+ /**
120
+ * **`pithy email provision` for the Worker this check ran for (#711).** It acts on one Worker, and in a project
121
+ * with several a bare one is refused `input/required`. Takes the Worker's `apps/` directory, which is what
122
+ * `--worker` takes and what that refusal lists. Not its `wrangler.jsonc` name: a scaffold deploys `apps/api` as
123
+ * `acme-api`.
124
+ */
125
+ function provisionCommand(workerDirectory: string): Command {
126
+ return pithyCommand("email provision", { flags: { "--worker": workerDirOf({ dir: workerDirectory }) } });
127
+ }
128
+
129
+ /**
130
+ * The host's own report, with its provisioning command named for this Worker by its `apps/` directory. The host
131
+ * writes the bare command into its log because it cannot know the Worker; a check that does know names it, in
132
+ * the action and the `fix` alike.
133
+ */
134
+ function forWorker(report: HostEnvReport<unknown>, workerDirectory: string): HostEnvReport<unknown> {
135
+ return {
136
+ ...report,
137
+ problems: report.problems.map((problem) =>
138
+ problem.provider.command === EMAIL_PROVISION
139
+ ? { ...problem, provider: { ...problem.provider, command: provisionCommand(workerDirectory) } }
140
+ : problem,
141
+ ),
142
+ };
116
143
  }
117
144
 
118
145
  /**
@@ -215,7 +242,8 @@ async function accountFindings(
215
242
  problem: `No D1 database named ${suppressions} exists on this account.`,
216
243
  // One database for the whole project, and one run creates it. `pithy email provision` spans every
217
244
  // declared environment and takes no `--env`, so naming one here was a flag the CLI refuses (#594).
218
- action: "Run `pithy email provision`. Nothing is suppressed until it exists.",
245
+ action: `Run \`${provisionCommand(context.workerDirectory)}\`. Nothing is suppressed until it exists.`,
246
+ fix: provisionCommand(context.workerDirectory),
219
247
  });
220
248
  }
221
249
 
@@ -245,6 +273,9 @@ async function accountFindings(
245
273
  * **What this sees:** a row under this registry name. A secret some other declaration moved off D1 has its
246
274
  * own check to write, or none; nothing here walks the vault for strays, because the vault cannot be listed.
247
275
  */
276
+ /** What creates a missing link-signing entry: a provision of every environment, production included (#711). */
277
+ const PROVISION_SECRETS = remedy("secrets provision");
278
+
248
279
  async function signingKeyFindings(context: SettingsAccountContext, environment: string): Promise<SettingsFinding[]> {
249
280
  const findings: SettingsFinding[] = [];
250
281
  const entry = environmentScope(context.project, environment).secretEntry(
@@ -256,8 +287,10 @@ async function signingKeyFindings(context: SettingsAccountContext, environment:
256
287
  setting: EMAIL_LINK_SIGNING_KEY,
257
288
  environment,
258
289
  problem: `The link-signing key has no Secrets Store entry in ${environment}, so no tracking or unsubscribe link can be signed.`,
259
- // No `--env`: the command spans every declared environment, and takes no such flag.
260
- action: "Run `pithy secrets provision`.",
290
+ // No `--env`: the command spans every declared environment, production included, and takes no such flag — so
291
+ // for one environment's entry it is a person's decision, never a `fix` (#711).
292
+ action: PROVISION_SECRETS.say((command) => `Run \`${command}\`.`),
293
+ ...(PROVISION_SECRETS.fix === undefined ? {} : { fix: PROVISION_SECRETS.fix }),
261
294
  });
262
295
  }
263
296
  if (await context.account.vaultSecret({ name: EMAIL_LINK_SIGNING_KEY, environment })) {
@@ -265,7 +298,9 @@ async function signingKeyFindings(context: SettingsAccountContext, environment:
265
298
  setting: EMAIL_LINK_SIGNING_KEY,
266
299
  environment,
267
300
  problem: `The link-signing key is still held in ${environment}'s D1 vault, where nothing reads it. Links signed with it before the move no longer verify.`,
268
- action: `Once the Secrets Store entry is bound and deployed, run \`pithy secrets rm ${EMAIL_LINK_SIGNING_KEY} --env ${environment} --backend d1\`. See docs/commands/secrets.md#moving-a-secret-off-d1.`,
301
+ action: `Once the Secrets Store entry is bound and deployed, the D1 copy can go: ${personDecision("secrets rm", { args: [EMAIL_LINK_SIGNING_KEY], flags: { "--env": environment, "--backend": "d1" } })} See docs/commands/secrets.md#moving-a-secret-off-d1.`,
302
+ // No `fix`: the removal is safe only once the entry is bound and deployed, which this check does not
303
+ // establish, so an agent running it as written could delete the only copy that still answers (#697).
269
304
  });
270
305
  }
271
306
  return findings;
@@ -274,7 +309,11 @@ async function signingKeyFindings(context: SettingsAccountContext, environment:
274
309
  /** Email's settings check, built from one composition's resolved config. Declared on the capability. */
275
310
  export function emailSettings(config: EmailSettingsInput): CapabilitySettings {
276
311
  return {
277
- local: (context) => [...localHostEnv(config), ...localForAddress(config), ...localBaseUrlOrigin(config, context)],
312
+ local: (context) => [
313
+ ...localHostEnv(config, context.workerDirectory),
314
+ ...localForAddress(config),
315
+ ...localBaseUrlOrigin(config, context),
316
+ ],
278
317
  account: (context) => accountFindings(config, context),
279
318
  };
280
319
  }
@@ -2,6 +2,7 @@
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
4
  import { normalizeAddress } from "@pithy-sh/core/src/address/address";
5
+ import type { MeterCharge, MeterSubject } from "@pithy-sh/core/src/entitlement/meter";
5
6
  import { isLocale } from "@pithy-sh/core/src/i18n/locale";
6
7
  import type { EmailJob } from "../data/emailJob";
7
8
  import { EmailJob as EmailJobSchema } from "../data/emailJob";
@@ -121,6 +122,16 @@ export interface EnqueueInput {
121
122
  inReplyTo?: string;
122
123
  /** The `References` chain, angle-bracketed and space-separated. Built by the caller from the parent. */
123
124
  references?: string;
125
+ /**
126
+ * Who this message is sent on behalf of, for the `emails` meter — the holder pair `@pithy-sh/payments`
127
+ * bills, `{ subjectType: "organization", subjectId }`.
128
+ *
129
+ * **Omit it and nothing is counted**, which is right for every message the kit sends on its own account: a
130
+ * magic link to somebody who has not signed up is not a tenant's usage. Name it on mail a customer's plan
131
+ * pays for — a campaign, a notification their workspace triggers — and, where the meter is enforced, an
132
+ * enqueue past the period's quota throws `payments/quota_exceeded` and writes no job.
133
+ */
134
+ subject?: MeterSubject;
124
135
  }
125
136
 
126
137
  /** Dependencies enqueue needs: the database, the from identity, optional send-Workflow binding, time, ids. */
@@ -149,6 +160,11 @@ export interface EnqueueDeps {
149
160
  * goes could not be consulted yet, which is strictly worse than queueing it.
150
161
  */
151
162
  suppressionDb?: EmailSuppressionDatabase;
163
+ /**
164
+ * Charge one email against the `emails` meter, or refuse — the composed provider's seam, closed over this
165
+ * request's env. Absent when no provider is composed, and then nothing is counted.
166
+ */
167
+ meter?: (charge: MeterCharge) => Promise<void>;
152
168
  now: Date;
153
169
  /** Generate a job id (a UUID in production). */
154
170
  newId: () => string;
@@ -309,6 +325,18 @@ export async function enqueueEmail(deps: EnqueueDeps, input: EnqueueInput): Prom
309
325
  */
310
326
  const batchId = sender ? (deps.newBatchId ?? mintBatchId)() : null;
311
327
 
328
+ /**
329
+ * Charge the `emails` meter **before the row exists**, so a refusal writes no job — and only for a message
330
+ * that is going to be sent. A withheld recipient costs the customer nothing, and a message the kit sends
331
+ * on nobody's account names no subject and is never counted.
332
+ *
333
+ * Before the insert rather than after it, and the cost is the right way round: an insert that fails after
334
+ * a charge over-counts by one, and over-counting briefly is recoverable where under-counting is not.
335
+ */
336
+ if (!blocked && input.subject !== undefined && deps.meter !== undefined) {
337
+ await deps.meter({ subject: input.subject, meter: "emails", amount: 1, now: deps.now });
338
+ }
339
+
312
340
  const marketing = template.category === "marketing";
313
341
  const job: EmailJob = {
314
342
  id: deps.newId(),
@@ -13,4 +13,4 @@
13
13
  export const PACKAGE_NAME = "@pithy-sh/email";
14
14
 
15
15
  /** This package's version, stamped from its own package.json at generation time. */
16
- export const PACKAGE_VERSION = "0.3.11";
16
+ export const PACKAGE_VERSION = "0.5.0";
@@ -2,6 +2,7 @@
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
4
  import type { D1Database } from "@cloudflare/workers-types";
5
+ import { pithyCommandOf, remedy } from "@pithy-sh/core/src/cli/command";
5
6
  import { defineHostEnv, type HostEnvProvider } from "@pithy-sh/core/src/workflow/hostEnv";
6
7
  import type { SecretBinding } from "@pithy-sh/secrets/src/env/bindings";
7
8
  import { z } from "zod";
@@ -46,14 +47,20 @@ import type { SendWorkflowInstances } from "./instances";
46
47
  *
47
48
  * No `--env`: it spans every declared environment in one run and declares no such flag, and a flag a
48
49
  * command does not declare is refused (#594) — so a remedy naming one is a remedy that cannot be followed.
50
+ *
51
+ * No `--worker` either, and only here: this is the sentence the deployed host writes into its own log, and
52
+ * a host does not know which app Worker's `apps/` directory provisioned it. `pithy doctor` reports the same
53
+ * finding for a Worker it knows, and names it there (`provision/settingsCheck.ts`, #711).
49
54
  */
50
- const PROVISION = "pithy email provision";
55
+ export const EMAIL_PROVISION = pithyCommandOf("email provision", {}, { runtime: true });
56
+ const PROVISION = EMAIL_PROVISION;
51
57
 
52
58
  /**
53
- * The command that writes both host secrets below. No `--env`, for the same reason: `pithy secrets provision`
54
- * provisions every declared environment in one run and declares no such flag.
59
+ * What writes both host secrets below, said as a person's decision. No `--env`, for the same reason: `pithy secrets
60
+ * provision` provisions every declared environment in one run, production included, and declares no such flag — so
61
+ * it is never a `Run` line for one host's secret (#711).
55
62
  */
56
- const SECRETS_PROVISION = "pithy secrets provision";
63
+ const SECRETS_PROVISION = remedy("secrets provision", {}, { runtime: true }).say((command) => command);
57
64
 
58
65
  /** A binding `pithy email provision` wires into the resolved `wrangler.jsonc`. */
59
66
  const binding = (name: string): HostEnvProvider => ({ kind: "binding", name, command: PROVISION });
@@ -210,12 +217,12 @@ export const emailHostEnv = defineHostEnv({
210
217
  SECRETS_ENCRYPTION_KEYS: {
211
218
  kind: "secret",
212
219
  name: "SECRETS_ENCRYPTION_KEYS",
213
- command: SECRETS_PROVISION,
220
+ decision: SECRETS_PROVISION,
214
221
  },
215
222
  [EMAIL_LINK_SIGNING_KEY_BINDING]: {
216
223
  kind: "secret",
217
224
  name: EMAIL_LINK_SIGNING_KEY,
218
- command: SECRETS_PROVISION,
225
+ decision: SECRETS_PROVISION,
219
226
  },
220
227
  EMAIL: binding("EMAIL"),
221
228
  EMAIL_SENDER: binding("EMAIL_SENDER"),