@pithy-sh/email 0.8.2 → 0.10.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 (62) hide show
  1. package/README.md +2 -0
  2. package/dist/bounce/handler.d.ts +22 -2
  3. package/dist/bounce/handler.d.ts.map +1 -1
  4. package/dist/bounce/handler.js +60 -17
  5. package/dist/capability.d.ts +12 -0
  6. package/dist/capability.d.ts.map +1 -1
  7. package/dist/capability.js +25 -15
  8. package/dist/crypto/signingKey.d.ts.map +1 -1
  9. package/dist/crypto/token.d.ts +43 -11
  10. package/dist/crypto/token.d.ts.map +1 -1
  11. package/dist/crypto/token.js +158 -55
  12. package/dist/http/callbacks.d.ts +8 -3
  13. package/dist/http/callbacks.d.ts.map +1 -1
  14. package/dist/http/callbacks.js +67 -12
  15. package/dist/http/guards.d.ts.map +1 -1
  16. package/dist/http/guards.js +9 -0
  17. package/dist/http/routes.d.ts +8 -4
  18. package/dist/http/routes.d.ts.map +1 -1
  19. package/dist/http/routes.js +67 -21
  20. package/dist/http/schemas.d.ts +41 -13
  21. package/dist/http/schemas.d.ts.map +1 -1
  22. package/dist/http/schemas.js +38 -15
  23. package/dist/jobs/read.d.ts +12 -9
  24. package/dist/jobs/read.d.ts.map +1 -1
  25. package/dist/jobs/read.js +6 -5
  26. package/dist/migrations/0002_job_filters.d.ts +15 -0
  27. package/dist/migrations/0002_job_filters.d.ts.map +1 -0
  28. package/dist/migrations/0002_job_filters.js +25 -0
  29. package/dist/send/enqueue.d.ts +26 -3
  30. package/dist/send/enqueue.d.ts.map +1 -1
  31. package/dist/send/enqueue.js +25 -2
  32. package/dist/send/errorMapping.d.ts +15 -20
  33. package/dist/send/errorMapping.d.ts.map +1 -1
  34. package/dist/send/errorMapping.js +33 -27
  35. package/dist/send/runSend.d.ts +2 -2
  36. package/dist/send/runSend.d.ts.map +1 -1
  37. package/dist/send/runSend.js +1 -1
  38. package/dist/send/suppression.d.ts +4 -0
  39. package/dist/send/suppression.d.ts.map +1 -1
  40. package/dist/send/suppression.js +4 -0
  41. package/dist/templates/engine.d.ts +1 -1
  42. package/dist/templates/engine.js +1 -1
  43. package/dist/version.generated.d.ts +1 -1
  44. package/dist/version.generated.d.ts.map +1 -1
  45. package/dist/version.generated.js +1 -1
  46. package/package.json +3 -3
  47. package/src/bounce/handler.ts +84 -32
  48. package/src/capability.ts +47 -27
  49. package/src/crypto/signingKey.ts +4 -2
  50. package/src/crypto/token.ts +225 -92
  51. package/src/http/callbacks.ts +100 -32
  52. package/src/http/guards.ts +9 -0
  53. package/src/http/routes.ts +96 -28
  54. package/src/http/schemas.ts +75 -24
  55. package/src/jobs/read.ts +14 -9
  56. package/src/migrations/0002_job_filters.ts +35 -0
  57. package/src/send/enqueue.ts +52 -5
  58. package/src/send/errorMapping.ts +45 -38
  59. package/src/send/runSend.ts +6 -7
  60. package/src/send/suppression.ts +13 -0
  61. package/src/templates/engine.ts +1 -1
  62. package/src/version.generated.ts +1 -1
@@ -5,22 +5,49 @@ import { z } from "zod";
5
5
  import { EmailInvalidTokenError } from "../error/errors";
6
6
 
7
7
  /**
8
- * HMAC-signed callback tokens. Click, open, and unsubscribe links carry one of these so a callback
9
- * is tamper-proof: the claims (which job, which recipient, where a click goes, which campaign) are
10
- * signed, and the signature is verified constant-time via `crypto.subtle.verify` before the callback
11
- * acts. The signing secret is a **rotatable** key from `@pithy-sh/secrets`; every token records the
12
- * key version (`kid`) it was signed with, so a link in a months-old email still verifies against the
13
- * retained version set after a rotation — and is rejected once that version is pruned.
8
+ * Sealed callback tokens. Click, open, and unsubscribe links carry one of these, and a link is written to every
9
+ * request log between a mail client and the Worker: Cloudflare's, Workers observability and tail, a mail scanner, a
10
+ * proxy. So a token says nothing to anyone who holds it. Its claims (which job, which recipient, where a click goes,
11
+ * which campaign) are sealed with AES-256-GCM, which both hides them and makes them tamper-proof: a changed byte
12
+ * fails the tag, and nothing is acted on before the tag verifies.
14
13
  *
15
- * **A token also names the origin it was minted for (`aud`), and only that origin may act on it (#596).**
16
- * A link points at the environment that minted it, so nothing about the product needs a staging token to
17
- * verify on production. The key is per environment, and that alone would keep them apart — for exactly as
18
- * long as nobody misconfigures one as shared. The claim is what makes that misconfiguration harmless rather
19
- * than a staging token that 302s through production's domain, records a staging job into production's
20
- * events, and writes a staging unsubscribe into the suppression list both environments bind, stamped as
21
- * production's. The key authorizes; the audience says where.
14
+ * Each token's sealing key is derived with HKDF-SHA256 from one version of the **rotatable** link-signing key in
15
+ * `@pithy-sh/secrets`, under the label {@link SEAL_LABEL} and a random salt the token carries. One secret, one
16
+ * rotation, and a fresh key per token, so no volume of mail brings two tokens near a shared key and IV. Every token names the key version
17
+ * (`kid`) it was sealed under, so a link in a months-old email still opens against the retained version set after a
18
+ * rotation, and is rejected once that version is pruned.
19
+ *
20
+ * A token also names the origin it was minted for (`aud`), and only that origin may act on it. A link points at the
21
+ * environment that minted it, and the key is per environment; the claim keeps a key misconfigured as shared from
22
+ * letting a staging token act on production's routes.
23
+ *
24
+ * ## Two formats on read, one on write
25
+ *
26
+ * - **`3.<kid>.<sealed>`**, minted by {@link mintToken}: `kid` base64url, `sealed` the 16-byte salt, the 12-byte
27
+ * IV, then the ciphertext and tag, base64url. The kid is bound as authenticated data, so a token moved to another
28
+ * version fails.
29
+ * - **`<payload>.<signature>`**, the signed format before it: base64url JSON with `v: 2` and an HMAC-SHA-256
30
+ * signature. Its payload decodes on sight, recipient included, so nothing mints it. It is still read, because
31
+ * mail already sent carries it, and it is accepted only until its own `exp`: `LINK_TTL_DAYS` from when it was
32
+ * sent, 90 days by default. The last one expires that long after the first deploy that stopped minting them,
33
+ * and the reader can be deleted then.
22
34
  */
23
35
 
36
+ /** The HKDF label a sealing key is derived under. Versioned, so a change to the format is a change of key. */
37
+ export const SEAL_LABEL = "pithy/email/link-seal/3";
38
+
39
+ /** The first segment of a sealed token: its format version. */
40
+ const SEALED_PREFIX = "3";
41
+
42
+ /** The 16-byte HKDF salt, fresh for every token, so every token is sealed under its own key. */
43
+ const SALT_BYTES = 16;
44
+
45
+ /** The 12-byte AES-GCM initialization vector, fresh for every token. */
46
+ const IV_BYTES = 12;
47
+
48
+ /** The longest key version a token may name. A real one is a short stringified integer. */
49
+ const MAX_KID_LENGTH = 64;
50
+
24
51
  const encoder = new TextEncoder();
25
52
  const decoder = new TextDecoder();
26
53
 
@@ -29,37 +56,55 @@ export const TokenKind = z
29
56
  .describe("Which callback a token authorizes: a tracked link `click`, an open-pixel `open`, or an `unsubscribe`.");
30
57
  export type TokenKind = z.output<typeof TokenKind>;
31
58
 
32
- /** The signed claims a callback token carries. `kid`/`exp`/`v`/`aud` are set by `mintToken`; the rest are caller claims. */
59
+ /** The claims every token carries, sealed or signed. */
60
+ const claimFields = {
61
+ kid: z
62
+ .string()
63
+ .describe("The link-signing key version this token was minted under; selects the key to open it with."),
64
+ aud: z
65
+ .string()
66
+ .describe(
67
+ "The origin this token was minted for — the scheme, host and port its links point at. It verifies at that origin and nowhere else.",
68
+ ),
69
+ kind: TokenKind.describe("Which callback this token authorizes."),
70
+ jobId: z.string().describe("The `pithy_email_jobs.id` this token is bound to."),
71
+ recipient: z.string().describe("The recipient address the callback is recorded against."),
72
+ exp: z.number().int().describe("Expiry as a Unix timestamp in seconds; the callback rejects a token past it."),
73
+ destination: z
74
+ .string()
75
+ .optional()
76
+ .describe("For a `click` token, the absolute URL to 302-redirect to after recording."),
77
+ linkLabel: z
78
+ .string()
79
+ .optional()
80
+ .describe("For a `click` token, the link's identity/label, recorded for attribution."),
81
+ campaignId: z.string().optional().describe("The marketing campaign this token is attributed to, when applicable."),
82
+ };
83
+
84
+ /** The claims a callback token carries. `kid`/`exp`/`v`/`aud` are set by `mintToken`; the rest are caller claims. */
33
85
  export const CallbackToken = z
34
86
  .object({
35
87
  v: z
36
- .literal(2)
37
- .describe(
38
- "Token format version, so the scheme can evolve without ambiguity. `2` added `aud`; a `1` token names no audience and is refused.",
39
- ),
40
- kid: z.string().describe("The signing-key version this token was signed with; selects the key to verify against."),
41
- aud: z
42
- .string()
88
+ .literal(3)
43
89
  .describe(
44
- "The origin this token was minted for — the scheme, host and port its links point at. It verifies at that origin and nowhere else.",
90
+ "Token format version. `3` is sealed with AES-256-GCM; `2`, the signed format, is read and never minted.",
45
91
  ),
46
- kind: TokenKind.describe("Which callback this token authorizes."),
47
- jobId: z.string().describe("The `pithy_email_jobs.id` this token is bound to."),
48
- recipient: z.string().describe("The recipient address the callback is recorded against."),
49
- exp: z.number().int().describe("Expiry as a Unix timestamp in seconds; the callback rejects a token past it."),
50
- destination: z
51
- .string()
52
- .optional()
53
- .describe("For a `click` token, the absolute URL to 302-redirect to after recording."),
54
- linkLabel: z
55
- .string()
56
- .optional()
57
- .describe("For a `click` token, the link's identity/label, recorded for attribution."),
58
- campaignId: z.string().optional().describe("The marketing campaign this token is attributed to, when applicable."),
92
+ ...claimFields,
59
93
  })
60
- .describe("The signed claims carried by an email callback token (click/open/unsubscribe).");
94
+ .describe("The sealed claims carried by an email callback token (click/open/unsubscribe).");
61
95
  export type CallbackToken = z.output<typeof CallbackToken>;
62
96
 
97
+ /** The claims of a token in the signed format, which is read until its links expire and never minted. */
98
+ const SignedCallbackToken = z
99
+ .object({
100
+ v: z.literal(2).describe("The signed format. `1` named no audience and is refused."),
101
+ ...claimFields,
102
+ })
103
+ .describe("The signed, unsealed claims of a callback token minted before tokens were sealed.");
104
+
105
+ /** The claims a verified token hands back, whichever format it arrived in. */
106
+ export type VerifiedCallbackToken = Omit<CallbackToken, "v"> & { v: 2 | 3 };
107
+
63
108
  /** The caller-supplied claims for a token — everything except the fields `mintToken` fills in. */
64
109
  export type TokenClaims = Omit<CallbackToken, "v" | "kid" | "exp" | "aud">;
65
110
 
@@ -85,7 +130,8 @@ function base64UrlEncode(bytes: Uint8Array): string {
85
130
  return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
86
131
  }
87
132
 
88
- function base64UrlDecode(value: string): Uint8Array {
133
+ function base64UrlDecode(value: string): Uint8Array<ArrayBuffer> {
134
+ if (!/^[A-Za-z0-9_-]*$/.test(value)) throw new EmailInvalidTokenError({ detail: "token segment is not base64url" });
89
135
  const padded = value.replace(/-/g, "+").replace(/_/g, "/") + "=".repeat((4 - (value.length % 4)) % 4);
90
136
  const binary = atob(padded);
91
137
  const bytes = new Uint8Array(binary.length);
@@ -93,17 +139,52 @@ function base64UrlDecode(value: string): Uint8Array {
93
139
  return bytes;
94
140
  }
95
141
 
96
- async function importKey(secret: string): Promise<CryptoKey> {
97
- return crypto.subtle.importKey("raw", encoder.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, [
98
- "sign",
99
- "verify",
142
+ /** The authenticated data a sealed token binds: its format and its key version. */
143
+ function sealedContext(kid: string): Uint8Array<ArrayBuffer> {
144
+ return Uint8Array.from(encoder.encode(`${SEAL_LABEL}:${kid}`));
145
+ }
146
+
147
+ /** The AES-256-GCM key for one token: HKDF-SHA256 over a link-signing key version, its salt and {@link SEAL_LABEL}. */
148
+ async function sealingKey(
149
+ secret: string,
150
+ salt: Uint8Array<ArrayBuffer>,
151
+ usage: "encrypt" | "decrypt",
152
+ ): Promise<CryptoKey> {
153
+ const material = await crypto.subtle.importKey("raw", Uint8Array.from(encoder.encode(secret)), "HKDF", false, [
154
+ "deriveKey",
100
155
  ]);
156
+ return crypto.subtle.deriveKey(
157
+ { name: "HKDF", hash: "SHA-256", salt, info: Uint8Array.from(encoder.encode(SEAL_LABEL)) },
158
+ material,
159
+ { name: "AES-GCM", length: 256 },
160
+ false,
161
+ [usage],
162
+ );
163
+ }
164
+
165
+ async function hmacKey(secret: string): Promise<CryptoKey> {
166
+ return crypto.subtle.importKey("raw", encoder.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["verify"]);
101
167
  }
102
168
 
103
169
  /**
104
- * Mint a signed token. The claims plus `kid`/`exp`/`v` are JSON-encoded and base64url-packed, then
105
- * HMAC-SHA-256 signed with `key`. The token is `<payload>.<signature>`; `kid` rides inside the signed
106
- * payload so the verifier knows which key to check without trusting an unsigned header.
170
+ * The secret for `kid`, or a refusal. An own property only: a bracket lookup with an attacker-controlled `kid` like
171
+ * `__proto__` or `constructor` would resolve up the prototype chain to a truthy non-string, which the key import would
172
+ * coerce to a fixed string an attacker knows.
173
+ */
174
+ function secretFor(keys: { versions: Record<string, string> }, kid: string): string {
175
+ const secret = Object.hasOwn(keys.versions, kid) ? keys.versions[kid] : undefined;
176
+ if (typeof secret !== "string") {
177
+ // The kid is a stranger's string: bounded before it reaches a log line.
178
+ throw new EmailInvalidTokenError({
179
+ detail: `token kid '${kid.slice(0, 16).replace(/[^\x20-\x7e]/g, "?")}' is not in the valid key set`,
180
+ });
181
+ }
182
+ return secret;
183
+ }
184
+
185
+ /**
186
+ * Mint a sealed token: the claims plus `v`/`kid`/`aud`/`exp`, JSON-encoded and sealed with AES-256-GCM under the key
187
+ * derived from `key`. Nothing in the result decodes to a claim.
107
188
  */
108
189
  export async function mintToken(
109
190
  claims: TokenClaims,
@@ -118,68 +199,88 @@ export async function mintToken(
118
199
  const payload: CallbackToken = {
119
200
  ...claims,
120
201
  // After the caller's claims, so nothing spread in can overwrite what this function is the authority on.
121
- v: 2,
202
+ v: 3,
122
203
  kid: options.kid,
123
204
  aud: tokenAudience(options.audience),
124
205
  exp: Math.floor(options.expiresAt.getTime() / 1000),
125
206
  };
126
- const payloadB64 = base64UrlEncode(encoder.encode(JSON.stringify(payload)));
127
- const key = await importKey(options.key);
128
- const signature = new Uint8Array(await crypto.subtle.sign("HMAC", key, encoder.encode(payloadB64)));
129
- return `${payloadB64}.${base64UrlEncode(signature)}`;
207
+ const salt = crypto.getRandomValues(new Uint8Array(SALT_BYTES));
208
+ const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES));
209
+ const key = await sealingKey(options.key, salt, "encrypt");
210
+ const ciphertext = new Uint8Array(
211
+ await crypto.subtle.encrypt(
212
+ { name: "AES-GCM", iv, additionalData: sealedContext(options.kid) },
213
+ key,
214
+ Uint8Array.from(encoder.encode(JSON.stringify(payload))),
215
+ ),
216
+ );
217
+ const sealed = new Uint8Array(SALT_BYTES + IV_BYTES + ciphertext.length);
218
+ sealed.set(salt, 0);
219
+ sealed.set(iv, SALT_BYTES);
220
+ sealed.set(ciphertext, SALT_BYTES + IV_BYTES);
221
+ return `${SEALED_PREFIX}.${base64UrlEncode(encoder.encode(options.kid))}.${base64UrlEncode(sealed)}`;
130
222
  }
131
223
 
132
- /**
133
- * Verify a token against the valid signing-key version set (`@pithy-sh/secrets`' `getVersions` shape)
134
- * and return its claims. Rejects — as `email/invalid_token` — a malformed token, an unknown/pruned
135
- * `kid`, a bad signature (constant-time via `crypto.subtle.verify`), a token minted for another origin,
136
- * or an expired token. The order is deliberate: structure, then signature, then audience, then expiry,
137
- * so a forged token never reaches a claim check.
138
- *
139
- * `audience` is **required**, and is the URL the token arrived on — the request's own. A verifier that
140
- * could omit it would be a verifier that accepts every origin, which is the hole the claim closes.
141
- *
142
- * **What the check cannot see:** where the caller got the URL. It compares against the string it is handed,
143
- * so a caller that passed a value read out of the token, or a header a client controls, would pass every
144
- * token. `http/callbacks.ts` hands it the request's own URL, and its route test plants a staging token on
145
- * each route to hold that; a new verifying caller needs the same.
146
- */
147
- export async function verifyToken(
148
- token: string,
224
+ /** Open a `3.<kid>.<sealed>` token, or refuse it. */
225
+ async function openSealed(
226
+ kidB64: string,
227
+ sealedB64: string,
149
228
  keys: { versions: Record<string, string> },
150
- now: Date,
151
- audience: string,
152
- ): Promise<CallbackToken> {
153
- const parts = token.split(".");
154
- if (parts.length !== 2 || !parts[0] || !parts[1]) {
155
- throw new EmailInvalidTokenError({ detail: "token is not in <payload>.<signature> form" });
229
+ ): Promise<VerifiedCallbackToken> {
230
+ let kid: string;
231
+ let sealed: Uint8Array<ArrayBuffer>;
232
+ try {
233
+ kid = decoder.decode(base64UrlDecode(kidB64));
234
+ sealed = base64UrlDecode(sealedB64);
235
+ } catch (cause) {
236
+ throw new EmailInvalidTokenError({ detail: "token segments are not base64url" }, { cause });
237
+ }
238
+ if (kid.length === 0 || kid.length > MAX_KID_LENGTH) {
239
+ throw new EmailInvalidTokenError({ detail: "token kid is empty or too long" });
240
+ }
241
+ if (sealed.length <= SALT_BYTES + IV_BYTES) throw new EmailInvalidTokenError({ detail: "sealed token is too short" });
242
+ const key = await sealingKey(secretFor(keys, kid), sealed.slice(0, SALT_BYTES), "decrypt");
243
+ let plaintext: ArrayBuffer;
244
+ try {
245
+ plaintext = await crypto.subtle.decrypt(
246
+ { name: "AES-GCM", iv: sealed.slice(SALT_BYTES, SALT_BYTES + IV_BYTES), additionalData: sealedContext(kid) },
247
+ key,
248
+ sealed.slice(SALT_BYTES + IV_BYTES),
249
+ );
250
+ } catch (cause) {
251
+ throw new EmailInvalidTokenError({ detail: "sealed token did not open" }, { cause });
156
252
  }
157
- const [payloadB64, signatureB64] = parts;
253
+ let raw: unknown;
254
+ try {
255
+ raw = JSON.parse(decoder.decode(plaintext));
256
+ } catch (cause) {
257
+ throw new EmailInvalidTokenError({ detail: "sealed token payload is not JSON" }, { cause });
258
+ }
259
+ const parsed = CallbackToken.safeParse(raw);
260
+ // The tag covered the kid as authenticated data; the copy inside must agree with it.
261
+ if (!parsed.success || parsed.data.kid !== kid) {
262
+ throw new EmailInvalidTokenError({ detail: "token payload does not match the claim schema" });
263
+ }
264
+ return parsed.data;
265
+ }
158
266
 
267
+ /** Verify a `<payload>.<signature>` token in the signed format, or refuse it. */
268
+ async function openSigned(
269
+ payloadB64: string,
270
+ signatureB64: string,
271
+ keys: { versions: Record<string, string> },
272
+ ): Promise<VerifiedCallbackToken> {
159
273
  let raw: unknown;
160
274
  try {
161
275
  raw = JSON.parse(decoder.decode(base64UrlDecode(payloadB64)));
162
276
  } catch (cause) {
163
277
  throw new EmailInvalidTokenError({ detail: "token payload is not valid base64url JSON" }, { cause });
164
278
  }
165
-
166
- const parsed = CallbackToken.safeParse(raw);
279
+ const parsed = SignedCallbackToken.safeParse(raw);
167
280
  if (!parsed.success) {
168
281
  throw new EmailInvalidTokenError({ detail: "token payload does not match the claim schema" });
169
282
  }
170
-
171
- // Look the key up as an OWN property only — a bracket lookup with an attacker-controlled `kid`
172
- // like `__proto__`/`constructor` would otherwise resolve up the prototype chain to a truthy
173
- // non-string (Object.prototype / the Object function), pass an `if (!secret)` check, and let
174
- // `importKey` coerce it to a fixed, attacker-known key string — forging the signature. The
175
- // own-property + string-type checks close that off.
176
- const versions = keys.versions;
177
- const secret = Object.hasOwn(versions, parsed.data.kid) ? versions[parsed.data.kid] : undefined;
178
- if (typeof secret !== "string") {
179
- throw new EmailInvalidTokenError({ detail: `token kid '${parsed.data.kid}' is not in the valid key set` });
180
- }
181
-
182
- const key = await importKey(secret);
283
+ const key = await hmacKey(secretFor(keys, parsed.data.kid));
183
284
  let valid: boolean;
184
285
  try {
185
286
  valid = await crypto.subtle.verify("HMAC", key, base64UrlDecode(signatureB64), encoder.encode(payloadB64));
@@ -189,17 +290,49 @@ export async function verifyToken(
189
290
  if (!valid) {
190
291
  throw new EmailInvalidTokenError({ detail: "token signature did not verify" });
191
292
  }
293
+ return parsed.data;
294
+ }
295
+
296
+ /**
297
+ * Verify a token against the valid key version set (`@pithy-sh/secrets`' `getVersions` shape) and return its claims.
298
+ * Rejects — as `email/invalid_token` — a malformed token, an unknown or pruned `kid`, a token whose seal or signature
299
+ * does not verify, a token minted for another origin, or an expired token. The order is deliberate: structure, then
300
+ * the cryptographic check, then audience, then expiry, so a forged token never reaches a claim check.
301
+ *
302
+ * `audience` is **required**, and is the URL the token arrived on — the request's own. A verifier that
303
+ * could omit it would be a verifier that accepts every origin, which is the hole the claim closes.
304
+ *
305
+ * **What the check cannot see:** where the caller got the URL. It compares against the string it is handed,
306
+ * so a caller that passed a value read out of the token, or a header a client controls, would pass every
307
+ * token. `http/callbacks.ts` hands it the request's own URL, and its route test plants a staging token on
308
+ * each route to hold that; a new verifying caller needs the same.
309
+ */
310
+ export async function verifyToken(
311
+ token: string,
312
+ keys: { versions: Record<string, string> },
313
+ now: Date,
314
+ audience: string,
315
+ ): Promise<VerifiedCallbackToken> {
316
+ const parts = token.split(".");
317
+ let claims: VerifiedCallbackToken;
318
+ if (parts.length === 3 && parts[0] === SEALED_PREFIX && parts[1] && parts[2]) {
319
+ claims = await openSealed(parts[1], parts[2], keys);
320
+ } else if (parts.length === 2 && parts[0] && parts[1]) {
321
+ claims = await openSigned(parts[0], parts[1], keys);
322
+ } else {
323
+ throw new EmailInvalidTokenError({ detail: "token is not in a callback token form" });
324
+ }
192
325
 
193
326
  const expected = tokenAudience(audience);
194
- if (parsed.data.aud !== expected) {
327
+ if (claims.aud !== expected) {
195
328
  throw new EmailInvalidTokenError({
196
- detail: `token was minted for '${parsed.data.aud}' and presented at '${expected}'`,
329
+ detail: `token was minted for '${claims.aud}' and presented at '${expected}'`,
197
330
  });
198
331
  }
199
332
 
200
- if (parsed.data.exp * 1000 <= now.getTime()) {
333
+ if (claims.exp * 1000 <= now.getTime()) {
201
334
  throw new EmailInvalidTokenError({ detail: "token has expired" });
202
335
  }
203
336
 
204
- return parsed.data;
337
+ return claims;
205
338
  }
@@ -7,9 +7,9 @@ import type { PithyHonoEnv } from "@pithy-sh/core/src/capability/capability";
7
7
  import { describeRoute } from "@pithy-sh/core/src/http/routeSpec";
8
8
  import { validate } from "@pithy-sh/core/src/http/validation";
9
9
  import type { SecretsStoreEnv } from "@pithy-sh/secrets/src/env/bindings";
10
- import type { Hono } from "hono";
10
+ import type { Hono, MiddlewareHandler } from "hono";
11
11
  import { resolveSigningKeys } from "../crypto/signingKey";
12
- import { type CallbackToken, type TokenKind, verifyToken } from "../crypto/token";
12
+ import { type TokenKind, type VerifiedCallbackToken, verifyToken } from "../crypto/token";
13
13
  import {
14
14
  type EmailDatabase,
15
15
  type EmailSuppressionDatabase,
@@ -20,32 +20,34 @@ import { EmailInvalidTokenError } from "../error/errors";
20
20
  import { recordEvent } from "../send/events";
21
21
  import { suppress } from "../send/suppression";
22
22
  import { CALLBACK_BASE } from "../templates/engine";
23
- import { CallbackTokenParam, UnsubscribeQuery } from "./schemas";
23
+ import { CallbackTokenParam, UnsubscribeForm } from "./schemas";
24
24
 
25
25
  /**
26
26
  * The callback routes — click, open, and unsubscribe. Every link in a tracked email points here with
27
- * an HMAC-signed token (see `crypto/token`). The routes are **public + signed-token**: they take no
28
- * session, and the token's signature is the only gate. A forged, altered, or expired token is rejected
29
- * (`email/invalid_token` → 400) before anything is recorded. The click route only ever 302-redirects to
30
- * an `http(s)` destination carried inside the signed token, so it cannot be turned into an open redirect.
27
+ * a sealed token (see `crypto/token`) that decodes to nothing, so the URL a request log records names no one.
28
+ * The routes are **public + sealed token**: they take no session, and the token's seal is the only gate. A forged,
29
+ * altered, or expired token is rejected (`email/invalid_token` → 400) before anything is recorded. The click route
30
+ * only ever 302-redirects to an `http(s)` destination carried inside the token, so it cannot be turned into an open
31
+ * redirect.
31
32
  *
32
33
  * | Method | Path | Strategy | Validates |
33
34
  * |--------|-------------------------------|---------------|-----------|
34
- * | GET | /_pithy/email/c/:token | signed token | param `CallbackTokenParam` |
35
- * | GET | /_pithy/email/o/:token | signed token | param `CallbackTokenParam` |
36
- * | GET | /_pithy/email/u/:token | signed token | param `CallbackTokenParam`, query `UnsubscribeQuery` |
37
- * | POST | /_pithy/email/u/:token | signed token | param `CallbackTokenParam`, query `UnsubscribeQuery` |
35
+ * | GET | /_pithy/email/c/:token | sealed token | param `CallbackTokenParam` |
36
+ * | GET | /_pithy/email/o/:token | sealed token | param `CallbackTokenParam` |
37
+ * | GET | /_pithy/email/u/:token | sealed token | param `CallbackTokenParam` |
38
+ * | POST | /_pithy/email/u/:token | sealed token | param `CallbackTokenParam`, form `UnsubscribeForm` |
38
39
  *
39
- * The unsubscribe route answers POST as well as GET because elective mail carries
40
- * `List-Unsubscribe-Post: List-Unsubscribe=One-Click` (RFC 8058) — the mail client posts to the URL
41
- * itself, with no human ever loading the page, and Gmail's and Yahoo's bulk-sender rules require that to
42
- * work. Same handler: the underlying write is an upsert, so the two methods cannot disagree and a
43
- * client that retries costs nothing.
40
+ * **The unsubscribe GET changes nothing.** It renders a page whose one button posts back to the same URL, because
41
+ * a GET is what a mail scanner or a link preview fetches on its own, and an opt-out nobody asked for is still an
42
+ * opt-out. The POST does the work, and it is what elective mail's `List-Unsubscribe-Post: List-Unsubscribe=One-Click`
43
+ * (RFC 8058) has a mail client send, with no human loading the page. The write is an upsert, so a client that
44
+ * retries costs nothing.
44
45
  *
45
- * The validators bound shape and size only — the signature check stays in the handler, so a well-formed
46
- * token that is forged or expired is still `email/invalid_token` (400), not `validation/invalid_input`.
47
- * No route reads a body, the one-click POST included: RFC 8058 fixes its body to a constant, so parsing
48
- * it could only ever restate what the method and the signed token already say.
46
+ * **No route reads a query string.** The one value a caller supplies, the recipient's `reason`, is in the POST's
47
+ * form body, since a query string is written to every request log on the way. A `?reason=` on a link is never read.
48
+ *
49
+ * The validators bound shape and size only — the seal check stays in the handler, so a well-formed token that is
50
+ * forged or expired is still `email/invalid_token` (400), not `validation/invalid_input`.
49
51
  *
50
52
  * Every token names the origin it was minted for, and a handler refuses one presented anywhere else — see
51
53
  * `crypto/token`'s `aud`. That is what keeps a key misconfigured as shared from letting a staging link act
@@ -91,7 +93,7 @@ async function verify(
91
93
  request: CallbackRequest,
92
94
  expected: TokenKind,
93
95
  now: Date,
94
- ): Promise<CallbackToken> {
96
+ ): Promise<VerifiedCallbackToken> {
95
97
  const claims = await verifyToken(request.token, keys, now, request.url);
96
98
  if (claims.kind !== expected) {
97
99
  throw new EmailInvalidTokenError({ detail: `token kind '${claims.kind}' does not match callback '${expected}'` });
@@ -99,7 +101,7 @@ async function verify(
99
101
  return claims;
100
102
  }
101
103
 
102
- /** Handle a click: record it, then 302-redirect to the signed http(s) destination. */
104
+ /** Handle a click: record it, then 302-redirect to the sealed http(s) destination. */
103
105
  export async function handleClick(
104
106
  db: EmailDatabase,
105
107
  keys: SigningKeys,
@@ -150,10 +152,32 @@ export async function handleOpen(
150
152
  });
151
153
  }
152
154
 
155
+ /** The unsubscribe confirmation page. One button, posting back to this URL; nothing in it names the recipient. */
156
+ const UNSUBSCRIBE_PAGE =
157
+ '<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Unsubscribe</title></head><body style="font-family:system-ui,-apple-system,sans-serif;max-width:34rem;margin:12vh auto;padding:0 1.5rem;line-height:1.55"><p>Unsubscribe from everything but the mail you ask for? A sign-in link or a security notice still arrives.</p><form method="post"><button type="submit">Unsubscribe</button></form></body></html>';
158
+
159
+ /**
160
+ * Render the unsubscribe page for a valid token, recording nothing. A forged, expired or misdirected token is refused
161
+ * here exactly as the POST would refuse it, so the page never offers a button that cannot work.
162
+ */
163
+ export async function handleUnsubscribePage(keys: SigningKeys, request: CallbackRequest, now: Date): Promise<Response> {
164
+ await verify(keys, request, "unsubscribe", now);
165
+ return new Response(UNSUBSCRIBE_PAGE, {
166
+ status: 200,
167
+ headers: {
168
+ "content-type": "text/html; charset=utf-8",
169
+ "cache-control": "no-store, max-age=0",
170
+ "referrer-policy": "no-referrer",
171
+ "content-security-policy":
172
+ "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; frame-ancestors 'none'",
173
+ },
174
+ });
175
+ }
176
+
153
177
  /**
154
178
  * Handle an unsubscribe: suppress the address (shared DB), record the opt-out event (app DB), confirm.
155
- * An optional `reason` — supplied by the app's own unsubscribe/preferences flow via the `?reason=` query
156
- * param — is stored on the suppression `detail` and the event, so a project can capture *why* someone
179
+ * An optional `reason` — supplied by the app's own unsubscribe/preferences flow in the POST's form body —
180
+ * is stored on the suppression `detail` and the event, so a project can capture *why* someone
157
181
  * opted out using its own logic. It is length-bounded so the link can't be used to stuff the column.
158
182
  */
159
183
  export async function handleUnsubscribe(
@@ -185,10 +209,36 @@ export async function handleUnsubscribe(
185
209
  "<p>You've been unsubscribed. Messages you ask for — a sign-in link, a security notice — still arrive. Nothing else will.</p>";
186
210
  return new Response(body, {
187
211
  status: 200,
188
- headers: { "content-type": "text/html; charset=utf-8" },
212
+ headers: {
213
+ "content-type": "text/html; charset=utf-8",
214
+ "cache-control": "no-store, max-age=0",
215
+ "referrer-policy": "no-referrer",
216
+ "content-security-policy": "default-src 'none'; frame-ancestors 'none'",
217
+ },
189
218
  });
190
219
  }
191
220
 
221
+ /** The first value of a form field, or nothing. */
222
+ function firstValue(field: string | string[] | undefined): string | undefined {
223
+ return Array.isArray(field) ? field[0] : field;
224
+ }
225
+
226
+ /**
227
+ * Read an unsubscribe POST's form body forgivingly: a body that will not parse reads as an empty form, so the
228
+ * validator after it sees `{}` and the opt-out still lands. Hono's form validator reads the parse this caches.
229
+ */
230
+ const forgivingForm: MiddlewareHandler = async (c, next) => {
231
+ const type = c.req.header("content-type") ?? "";
232
+ if (/^(multipart\/form-data|application\/x-www-form-urlencoded)/i.test(type)) {
233
+ try {
234
+ await c.req.formData();
235
+ } catch {
236
+ Object.assign(c.req.bodyCache, { formData: Promise.resolve(new FormData()) });
237
+ }
238
+ }
239
+ await next();
240
+ };
241
+
192
242
  /** Mount the click/open/unsubscribe callback routes under `${CALLBACK_BASE}` on the app's Hono router. */
193
243
  export function registerCallbacks(app: Hono<PithyHonoEnv>): void {
194
244
  const setup = async (
@@ -207,7 +257,7 @@ export function registerCallbacks(app: Hono<PithyHonoEnv>): void {
207
257
  describeRoute({
208
258
  summary: "Record a click on a tracked link, then send the reader on to it.",
209
259
  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.",
260
+ "Public: the token's seal 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 sealed into the token, never one from the request.",
211
261
  verification: "public",
212
262
  responses: { 302: { description: "A redirect to the link's destination, carried in `Location`." } },
213
263
  }),
@@ -223,7 +273,7 @@ export function registerCallbacks(app: Hono<PithyHonoEnv>): void {
223
273
  describeRoute({
224
274
  summary: "Record that an email was opened.",
225
275
  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.",
276
+ "Public: the token's seal is the only gate. The token may carry the `.png` suffix mail clients expect on an image URL.",
227
277
  verification: "public",
228
278
  responses: { 200: { description: "A 1×1 transparent PNG, never cached.", contentType: "image/png" } },
229
279
  }),
@@ -234,18 +284,36 @@ export function registerCallbacks(app: Hono<PithyHonoEnv>): void {
234
284
  },
235
285
  );
236
286
 
237
- app.on(
238
- ["GET", "POST"],
287
+ app.get(
288
+ `${CALLBACK_BASE}/u/:token`,
289
+ describeRoute({
290
+ summary: "Show the page that confirms an unsubscribe.",
291
+ description:
292
+ "Public: the token's seal is the only gate. Records nothing, so a mail scanner or a link preview fetching the link changes nothing. The page's button posts back to the same URL.",
293
+ verification: "public",
294
+ responses: {
295
+ 200: { description: "A short HTML page with one button that unsubscribes.", contentType: "text/html" },
296
+ },
297
+ }),
298
+ validate("param", CallbackTokenParam),
299
+ async (c) => {
300
+ const { keys } = await setup(c.env as unknown as CallbackEnv);
301
+ return handleUnsubscribePage(keys, { token: c.req.valid("param").token, url: c.req.url }, new Date());
302
+ },
303
+ );
304
+
305
+ app.post(
239
306
  `${CALLBACK_BASE}/u/:token`,
240
307
  describeRoute({
241
308
  summary: "Unsubscribe the recipient from everything but the mail they ask for.",
242
309
  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.",
310
+ "Public: the token's seal is the only gate. The page's button and a mail client's one-click unsubscribe both post here; an empty body works as well as `List-Unsubscribe=One-Click`. The address joins the suppression list shared by every environment.",
244
311
  verification: "public",
245
312
  responses: { 200: { description: "A short HTML page confirming the opt-out.", contentType: "text/html" } },
246
313
  }),
247
314
  validate("param", CallbackTokenParam),
248
- validate("query", UnsubscribeQuery),
315
+ forgivingForm,
316
+ validate("form", UnsubscribeForm),
249
317
  async (c) => {
250
318
  const env = c.env as unknown as CallbackEnv;
251
319
  const { db, suppressionDb, keys } = await setup(env);
@@ -255,7 +323,7 @@ export function registerCallbacks(app: Hono<PithyHonoEnv>): void {
255
323
  keys,
256
324
  { token: c.req.valid("param").token, url: c.req.url },
257
325
  new Date(),
258
- c.req.valid("query").reason,
326
+ firstValue(c.req.valid("form").reason),
259
327
  env.ENVIRONMENT,
260
328
  );
261
329
  },
@@ -146,6 +146,15 @@ export function emailAdminRoutes(basePath: string): AdminRouteDeclaration[] {
146
146
  kind: "reads",
147
147
  summary: "Addresses this project will not send to, and why. Global — every environment shares it.",
148
148
  },
149
+ {
150
+ method: "POST",
151
+ operation: "suppressions.lookup",
152
+ path: `${basePath}/suppressions/lookup`,
153
+ scope: EMAIL_SUPPRESSIONS_READ_SCOPE,
154
+ kind: "reads",
155
+ readInBody: true,
156
+ summary: "Whether one address is on the list, and why. The address travels in the body, never the URL.",
157
+ },
149
158
  {
150
159
  method: "POST",
151
160
  operation: "suppressions.add",