@pithy-sh/email 0.9.0 → 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.
@@ -1 +1 @@
1
- {"version":3,"file":"signingKey.d.ts","sourceRoot":"","sources":["../../src/crypto/signingKey.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,oCAAoC,CAAC;AAE1E,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,oCAAoC,CAAC;AAG1E;;;;GAIG;AACH,eAAO,MAAM,sBAAsB,2BAA2B,CAAC;AAE/D;;;;GAIG;AACH,eAAO,MAAM,8BAA8B,0BAA4C,CAAC;AAExF,gHAAgH;AAChH,eAAO,MAAM,oBAAoB;;;;;;;;;;;;;;;;;;;;;;;CAqC/B,CAAC;AAEH;;;;GAIG;AACH,wBAAsB,kBAAkB,CACtC,GAAG,EAAE,eAAe,GACnB,OAAO,CAAC,eAAe,CAAC,CAAC,OAAO,oBAAoB,CAAC,CAAC,OAAO,sBAAsB,CAAC,CAAC,CAAC,CAGxF"}
1
+ {"version":3,"file":"signingKey.d.ts","sourceRoot":"","sources":["../../src/crypto/signingKey.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,oCAAoC,CAAC;AAE1E,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,oCAAoC,CAAC;AAG1E;;;;GAIG;AACH,eAAO,MAAM,sBAAsB,2BAA2B,CAAC;AAE/D;;;;GAIG;AACH,eAAO,MAAM,8BAA8B,0BAA4C,CAAC;AAExF,gHAAgH;AAChH,eAAO,MAAM,oBAAoB;;;;;;;;;;;;;;;;;;;;;;;CAuC/B,CAAC;AAEH;;;;GAIG;AACH,wBAAsB,kBAAkB,CACtC,GAAG,EAAE,eAAe,GACnB,OAAO,CAAC,eAAe,CAAC,CAAC,OAAO,oBAAoB,CAAC,CAAC,OAAO,sBAAsB,CAAC,CAAC,CAAC,CAGxF"}
@@ -1,15 +1,44 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: MIT
3
3
  import { z } from "zod";
4
+ /**
5
+ * Sealed callback tokens. Click, open, and unsubscribe links carry one of these, and a link is written to every
6
+ * request log between a mail client and the Worker: Cloudflare's, Workers observability and tail, a mail scanner, a
7
+ * proxy. So a token says nothing to anyone who holds it. Its claims (which job, which recipient, where a click goes,
8
+ * which campaign) are sealed with AES-256-GCM, which both hides them and makes them tamper-proof: a changed byte
9
+ * fails the tag, and nothing is acted on before the tag verifies.
10
+ *
11
+ * Each token's sealing key is derived with HKDF-SHA256 from one version of the **rotatable** link-signing key in
12
+ * `@pithy-sh/secrets`, under the label {@link SEAL_LABEL} and a random salt the token carries. One secret, one
13
+ * 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
14
+ * (`kid`) it was sealed under, so a link in a months-old email still opens against the retained version set after a
15
+ * rotation, and is rejected once that version is pruned.
16
+ *
17
+ * A token also names the origin it was minted for (`aud`), and only that origin may act on it. A link points at the
18
+ * environment that minted it, and the key is per environment; the claim keeps a key misconfigured as shared from
19
+ * letting a staging token act on production's routes.
20
+ *
21
+ * ## Two formats on read, one on write
22
+ *
23
+ * - **`3.<kid>.<sealed>`**, minted by {@link mintToken}: `kid` base64url, `sealed` the 16-byte salt, the 12-byte
24
+ * IV, then the ciphertext and tag, base64url. The kid is bound as authenticated data, so a token moved to another
25
+ * version fails.
26
+ * - **`<payload>.<signature>`**, the signed format before it: base64url JSON with `v: 2` and an HMAC-SHA-256
27
+ * signature. Its payload decodes on sight, recipient included, so nothing mints it. It is still read, because
28
+ * mail already sent carries it, and it is accepted only until its own `exp`: `LINK_TTL_DAYS` from when it was
29
+ * sent, 90 days by default. The last one expires that long after the first deploy that stopped minting them,
30
+ * and the reader can be deleted then.
31
+ */
32
+ /** The HKDF label a sealing key is derived under. Versioned, so a change to the format is a change of key. */
33
+ export declare const SEAL_LABEL = "pithy/email/link-seal/3";
4
34
  export declare const TokenKind: z.ZodEnum<{
5
35
  click: "click";
6
36
  open: "open";
7
37
  unsubscribe: "unsubscribe";
8
38
  }>;
9
39
  export type TokenKind = z.output<typeof TokenKind>;
10
- /** The signed claims a callback token carries. `kid`/`exp`/`v`/`aud` are set by `mintToken`; the rest are caller claims. */
40
+ /** The claims a callback token carries. `kid`/`exp`/`v`/`aud` are set by `mintToken`; the rest are caller claims. */
11
41
  export declare const CallbackToken: z.ZodObject<{
12
- v: z.ZodLiteral<2>;
13
42
  kid: z.ZodString;
14
43
  aud: z.ZodString;
15
44
  kind: z.ZodEnum<{
@@ -23,8 +52,13 @@ export declare const CallbackToken: z.ZodObject<{
23
52
  destination: z.ZodOptional<z.ZodString>;
24
53
  linkLabel: z.ZodOptional<z.ZodString>;
25
54
  campaignId: z.ZodOptional<z.ZodString>;
55
+ v: z.ZodLiteral<3>;
26
56
  }, z.core.$strip>;
27
57
  export type CallbackToken = z.output<typeof CallbackToken>;
58
+ /** The claims a verified token hands back, whichever format it arrived in. */
59
+ export type VerifiedCallbackToken = Omit<CallbackToken, "v"> & {
60
+ v: 2 | 3;
61
+ };
28
62
  /** The caller-supplied claims for a token — everything except the fields `mintToken` fills in. */
29
63
  export type TokenClaims = Omit<CallbackToken, "v" | "kid" | "exp" | "aud">;
30
64
  /**
@@ -37,9 +71,8 @@ export type TokenClaims = Omit<CallbackToken, "v" | "kid" | "exp" | "aud">;
37
71
  */
38
72
  export declare function tokenAudience(url: string): string;
39
73
  /**
40
- * Mint a signed token. The claims plus `kid`/`exp`/`v` are JSON-encoded and base64url-packed, then
41
- * HMAC-SHA-256 signed with `key`. The token is `<payload>.<signature>`; `kid` rides inside the signed
42
- * payload so the verifier knows which key to check without trusting an unsigned header.
74
+ * Mint a sealed token: the claims plus `v`/`kid`/`aud`/`exp`, JSON-encoded and sealed with AES-256-GCM under the key
75
+ * derived from `key`. Nothing in the result decodes to a claim.
43
76
  */
44
77
  export declare function mintToken(claims: TokenClaims, options: {
45
78
  key: string;
@@ -49,11 +82,10 @@ export declare function mintToken(claims: TokenClaims, options: {
49
82
  audience: string;
50
83
  }): Promise<string>;
51
84
  /**
52
- * Verify a token against the valid signing-key version set (`@pithy-sh/secrets`' `getVersions` shape)
53
- * and return its claims. Rejects — as `email/invalid_token` — a malformed token, an unknown/pruned
54
- * `kid`, a bad signature (constant-time via `crypto.subtle.verify`), a token minted for another origin,
55
- * or an expired token. The order is deliberate: structure, then signature, then audience, then expiry,
56
- * so a forged token never reaches a claim check.
85
+ * Verify a token against the valid key version set (`@pithy-sh/secrets`' `getVersions` shape) and return its claims.
86
+ * Rejects — as `email/invalid_token` — a malformed token, an unknown or pruned `kid`, a token whose seal or signature
87
+ * does not verify, a token minted for another origin, or an expired token. The order is deliberate: structure, then
88
+ * the cryptographic check, then audience, then expiry, so a forged token never reaches a claim check.
57
89
  *
58
90
  * `audience` is **required**, and is the URL the token arrived on — the request's own. A verifier that
59
91
  * could omit it would be a verifier that accepts every origin, which is the hole the claim closes.
@@ -65,5 +97,5 @@ export declare function mintToken(claims: TokenClaims, options: {
65
97
  */
66
98
  export declare function verifyToken(token: string, keys: {
67
99
  versions: Record<string, string>;
68
- }, now: Date, audience: string): Promise<CallbackToken>;
100
+ }, now: Date, audience: string): Promise<VerifiedCallbackToken>;
69
101
  //# sourceMappingURL=token.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"token.d.ts","sourceRoot":"","sources":["../../src/crypto/token.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAuBxB,eAAO,MAAM,SAAS;;;;EAE8F,CAAC;AACrH,MAAM,MAAM,SAAS,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,SAAS,CAAC,CAAC;AAEnD,4HAA4H;AAC5H,eAAO,MAAM,aAAa;;;;;;;;;;;;;;;iBA2BmE,CAAC;AAC9F,MAAM,MAAM,aAAa,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,aAAa,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,MAAM,MAAM,qBAAqB,GAAG,IAAI,CAAC,aAAa,EAAE,GAAG,CAAC,GAAG;IAAE,CAAC,EAAE,CAAC,GAAG,CAAC,CAAA;CAAE,CAAC;AAE5E,kGAAkG;AAClG,MAAM,MAAM,WAAW,GAAG,IAAI,CAAC,aAAa,EAAE,GAAG,GAAG,KAAK,GAAG,KAAK,GAAG,KAAK,CAAC,CAAC;AAE3E;;;;;;;GAOG;AACH,wBAAgB,aAAa,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAMjD;AA4DD;;;GAGG;AACH,wBAAsB,SAAS,CAC7B,MAAM,EAAE,WAAW,EACnB,OAAO,EAAE;IACP,GAAG,EAAE,MAAM,CAAC;IACZ,GAAG,EAAE,MAAM,CAAC;IACZ,SAAS,EAAE,IAAI,CAAC;IAChB,6GAA6G;IAC7G,QAAQ,EAAE,MAAM,CAAC;CAClB,GACA,OAAO,CAAC,MAAM,CAAC,CAwBjB;AA0ED;;;;;;;;;;;;;GAaG;AACH,wBAAsB,WAAW,CAC/B,KAAK,EAAE,MAAM,EACb,IAAI,EAAE;IAAE,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;CAAE,EAC1C,GAAG,EAAE,IAAI,EACT,QAAQ,EAAE,MAAM,GACf,OAAO,CAAC,qBAAqB,CAAC,CAuBhC"}
@@ -4,21 +4,43 @@ import { EmailInvalidTokenError } from "../error/errors.js";
4
4
  import { z } from "zod";
5
5
  //#region src/crypto/token.ts
6
6
  /**
7
- * HMAC-signed callback tokens. Click, open, and unsubscribe links carry one of these so a callback
8
- * is tamper-proof: the claims (which job, which recipient, where a click goes, which campaign) are
9
- * signed, and the signature is verified constant-time via `crypto.subtle.verify` before the callback
10
- * acts. The signing secret is a **rotatable** key from `@pithy-sh/secrets`; every token records the
11
- * key version (`kid`) it was signed with, so a link in a months-old email still verifies against the
12
- * retained version set after a rotation — and is rejected once that version is pruned.
7
+ * Sealed callback tokens. Click, open, and unsubscribe links carry one of these, and a link is written to every
8
+ * request log between a mail client and the Worker: Cloudflare's, Workers observability and tail, a mail scanner, a
9
+ * proxy. So a token says nothing to anyone who holds it. Its claims (which job, which recipient, where a click goes,
10
+ * which campaign) are sealed with AES-256-GCM, which both hides them and makes them tamper-proof: a changed byte
11
+ * fails the tag, and nothing is acted on before the tag verifies.
13
12
  *
14
- * **A token also names the origin it was minted for (`aud`), and only that origin may act on it (#596).**
15
- * A link points at the environment that minted it, so nothing about the product needs a staging token to
16
- * verify on production. The key is per environment, and that alone would keep them apart — for exactly as
17
- * long as nobody misconfigures one as shared. The claim is what makes that misconfiguration harmless rather
18
- * than a staging token that 302s through production's domain, records a staging job into production's
19
- * events, and writes a staging unsubscribe into the suppression list both environments bind, stamped as
20
- * production's. The key authorizes; the audience says where.
13
+ * Each token's sealing key is derived with HKDF-SHA256 from one version of the **rotatable** link-signing key in
14
+ * `@pithy-sh/secrets`, under the label {@link SEAL_LABEL} and a random salt the token carries. One secret, one
15
+ * 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
16
+ * (`kid`) it was sealed under, so a link in a months-old email still opens against the retained version set after a
17
+ * rotation, and is rejected once that version is pruned.
18
+ *
19
+ * A token also names the origin it was minted for (`aud`), and only that origin may act on it. A link points at the
20
+ * environment that minted it, and the key is per environment; the claim keeps a key misconfigured as shared from
21
+ * letting a staging token act on production's routes.
22
+ *
23
+ * ## Two formats on read, one on write
24
+ *
25
+ * - **`3.<kid>.<sealed>`**, minted by {@link mintToken}: `kid` base64url, `sealed` the 16-byte salt, the 12-byte
26
+ * IV, then the ciphertext and tag, base64url. The kid is bound as authenticated data, so a token moved to another
27
+ * version fails.
28
+ * - **`<payload>.<signature>`**, the signed format before it: base64url JSON with `v: 2` and an HMAC-SHA-256
29
+ * signature. Its payload decodes on sight, recipient included, so nothing mints it. It is still read, because
30
+ * mail already sent carries it, and it is accepted only until its own `exp`: `LINK_TTL_DAYS` from when it was
31
+ * sent, 90 days by default. The last one expires that long after the first deploy that stopped minting them,
32
+ * and the reader can be deleted then.
21
33
  */
34
+ /** The HKDF label a sealing key is derived under. Versioned, so a change to the format is a change of key. */
35
+ const SEAL_LABEL = "pithy/email/link-seal/3";
36
+ /** The first segment of a sealed token: its format version. */
37
+ const SEALED_PREFIX = "3";
38
+ /** The 16-byte HKDF salt, fresh for every token, so every token is sealed under its own key. */
39
+ const SALT_BYTES = 16;
40
+ /** The 12-byte AES-GCM initialization vector, fresh for every token. */
41
+ const IV_BYTES = 12;
42
+ /** The longest key version a token may name. A real one is a short stringified integer. */
43
+ const MAX_KID_LENGTH = 64;
22
44
  const encoder = new TextEncoder();
23
45
  const decoder = new TextDecoder();
24
46
  const TokenKind = z.enum([
@@ -26,10 +48,9 @@ const TokenKind = z.enum([
26
48
  "open",
27
49
  "unsubscribe"
28
50
  ]).describe("Which callback a token authorizes: a tracked link `click`, an open-pixel `open`, or an `unsubscribe`.");
29
- /** The signed claims a callback token carries. `kid`/`exp`/`v`/`aud` are set by `mintToken`; the rest are caller claims. */
30
- const CallbackToken = z.object({
31
- v: z.literal(2).describe("Token format version, so the scheme can evolve without ambiguity. `2` added `aud`; a `1` token names no audience and is refused."),
32
- kid: z.string().describe("The signing-key version this token was signed with; selects the key to verify against."),
51
+ /** The claims every token carries, sealed or signed. */
52
+ const claimFields = {
53
+ kid: z.string().describe("The link-signing key version this token was minted under; selects the key to open it with."),
33
54
  aud: z.string().describe("The origin this token was minted for — the scheme, host and port its links point at. It verifies at that origin and nowhere else."),
34
55
  kind: TokenKind.describe("Which callback this token authorizes."),
35
56
  jobId: z.string().describe("The `pithy_email_jobs.id` this token is bound to."),
@@ -38,7 +59,17 @@ const CallbackToken = z.object({
38
59
  destination: z.string().optional().describe("For a `click` token, the absolute URL to 302-redirect to after recording."),
39
60
  linkLabel: z.string().optional().describe("For a `click` token, the link's identity/label, recorded for attribution."),
40
61
  campaignId: z.string().optional().describe("The marketing campaign this token is attributed to, when applicable.")
41
- }).describe("The signed claims carried by an email callback token (click/open/unsubscribe).");
62
+ };
63
+ /** The claims a callback token carries. `kid`/`exp`/`v`/`aud` are set by `mintToken`; the rest are caller claims. */
64
+ const CallbackToken = z.object({
65
+ v: z.literal(3).describe("Token format version. `3` is sealed with AES-256-GCM; `2`, the signed format, is read and never minted."),
66
+ ...claimFields
67
+ }).describe("The sealed claims carried by an email callback token (click/open/unsubscribe).");
68
+ /** The claims of a token in the signed format, which is read until its links expire and never minted. */
69
+ const SignedCallbackToken = z.object({
70
+ v: z.literal(2).describe("The signed format. `1` named no audience and is refused."),
71
+ ...claimFields
72
+ }).describe("The signed, unsealed claims of a callback token minted before tokens were sealed.");
42
73
  /**
43
74
  * The audience a URL names: its origin, and nothing else.
44
75
  *
@@ -60,66 +91,116 @@ function base64UrlEncode(bytes) {
60
91
  return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
61
92
  }
62
93
  function base64UrlDecode(value) {
94
+ if (!/^[A-Za-z0-9_-]*$/.test(value)) throw new EmailInvalidTokenError({ detail: "token segment is not base64url" });
63
95
  const padded = value.replace(/-/g, "+").replace(/_/g, "/") + "=".repeat((4 - value.length % 4) % 4);
64
96
  const binary = atob(padded);
65
97
  const bytes = new Uint8Array(binary.length);
66
98
  for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i);
67
99
  return bytes;
68
100
  }
69
- async function importKey(secret) {
101
+ /** The authenticated data a sealed token binds: its format and its key version. */
102
+ function sealedContext(kid) {
103
+ return Uint8Array.from(encoder.encode(`${SEAL_LABEL}:${kid}`));
104
+ }
105
+ /** The AES-256-GCM key for one token: HKDF-SHA256 over a link-signing key version, its salt and {@link SEAL_LABEL}. */
106
+ async function sealingKey(secret, salt, usage) {
107
+ const material = await crypto.subtle.importKey("raw", Uint8Array.from(encoder.encode(secret)), "HKDF", false, ["deriveKey"]);
108
+ return crypto.subtle.deriveKey({
109
+ name: "HKDF",
110
+ hash: "SHA-256",
111
+ salt,
112
+ info: Uint8Array.from(encoder.encode(SEAL_LABEL))
113
+ }, material, {
114
+ name: "AES-GCM",
115
+ length: 256
116
+ }, false, [usage]);
117
+ }
118
+ async function hmacKey(secret) {
70
119
  return crypto.subtle.importKey("raw", encoder.encode(secret), {
71
120
  name: "HMAC",
72
121
  hash: "SHA-256"
73
- }, false, ["sign", "verify"]);
122
+ }, false, ["verify"]);
74
123
  }
75
124
  /**
76
- * Mint a signed token. The claims plus `kid`/`exp`/`v` are JSON-encoded and base64url-packed, then
77
- * HMAC-SHA-256 signed with `key`. The token is `<payload>.<signature>`; `kid` rides inside the signed
78
- * payload so the verifier knows which key to check without trusting an unsigned header.
125
+ * The secret for `kid`, or a refusal. An own property only: a bracket lookup with an attacker-controlled `kid` like
126
+ * `__proto__` or `constructor` would resolve up the prototype chain to a truthy non-string, which the key import would
127
+ * coerce to a fixed string an attacker knows.
128
+ */
129
+ function secretFor(keys, kid) {
130
+ const secret = Object.hasOwn(keys.versions, kid) ? keys.versions[kid] : void 0;
131
+ if (typeof secret !== "string") throw new EmailInvalidTokenError({ detail: `token kid '${kid.slice(0, 16).replace(/[^\x20-\x7e]/g, "?")}' is not in the valid key set` });
132
+ return secret;
133
+ }
134
+ /**
135
+ * Mint a sealed token: the claims plus `v`/`kid`/`aud`/`exp`, JSON-encoded and sealed with AES-256-GCM under the key
136
+ * derived from `key`. Nothing in the result decodes to a claim.
79
137
  */
80
138
  async function mintToken(claims, options) {
81
139
  const payload = {
82
140
  ...claims,
83
- v: 2,
141
+ v: 3,
84
142
  kid: options.kid,
85
143
  aud: tokenAudience(options.audience),
86
144
  exp: Math.floor(options.expiresAt.getTime() / 1e3)
87
145
  };
88
- const payloadB64 = base64UrlEncode(encoder.encode(JSON.stringify(payload)));
89
- const key = await importKey(options.key);
90
- return `${payloadB64}.${base64UrlEncode(new Uint8Array(await crypto.subtle.sign("HMAC", key, encoder.encode(payloadB64))))}`;
146
+ const salt = crypto.getRandomValues(new Uint8Array(SALT_BYTES));
147
+ const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES));
148
+ const key = await sealingKey(options.key, salt, "encrypt");
149
+ const ciphertext = new Uint8Array(await crypto.subtle.encrypt({
150
+ name: "AES-GCM",
151
+ iv,
152
+ additionalData: sealedContext(options.kid)
153
+ }, key, Uint8Array.from(encoder.encode(JSON.stringify(payload)))));
154
+ const sealed = new Uint8Array(28 + ciphertext.length);
155
+ sealed.set(salt, 0);
156
+ sealed.set(iv, SALT_BYTES);
157
+ sealed.set(ciphertext, 28);
158
+ return `${SEALED_PREFIX}.${base64UrlEncode(encoder.encode(options.kid))}.${base64UrlEncode(sealed)}`;
91
159
  }
92
- /**
93
- * Verify a token against the valid signing-key version set (`@pithy-sh/secrets`' `getVersions` shape)
94
- * and return its claims. Rejects — as `email/invalid_token` — a malformed token, an unknown/pruned
95
- * `kid`, a bad signature (constant-time via `crypto.subtle.verify`), a token minted for another origin,
96
- * or an expired token. The order is deliberate: structure, then signature, then audience, then expiry,
97
- * so a forged token never reaches a claim check.
98
- *
99
- * `audience` is **required**, and is the URL the token arrived on — the request's own. A verifier that
100
- * could omit it would be a verifier that accepts every origin, which is the hole the claim closes.
101
- *
102
- * **What the check cannot see:** where the caller got the URL. It compares against the string it is handed,
103
- * so a caller that passed a value read out of the token, or a header a client controls, would pass every
104
- * token. `http/callbacks.ts` hands it the request's own URL, and its route test plants a staging token on
105
- * each route to hold that; a new verifying caller needs the same.
106
- */
107
- async function verifyToken(token, keys, now, audience) {
108
- const parts = token.split(".");
109
- if (parts.length !== 2 || !parts[0] || !parts[1]) throw new EmailInvalidTokenError({ detail: "token is not in <payload>.<signature> form" });
110
- const [payloadB64, signatureB64] = parts;
160
+ /** Open a `3.<kid>.<sealed>` token, or refuse it. */
161
+ async function openSealed(kidB64, sealedB64, keys) {
162
+ let kid;
163
+ let sealed;
164
+ try {
165
+ kid = decoder.decode(base64UrlDecode(kidB64));
166
+ sealed = base64UrlDecode(sealedB64);
167
+ } catch (cause) {
168
+ throw new EmailInvalidTokenError({ detail: "token segments are not base64url" }, { cause });
169
+ }
170
+ if (kid.length === 0 || kid.length > MAX_KID_LENGTH) throw new EmailInvalidTokenError({ detail: "token kid is empty or too long" });
171
+ if (sealed.length <= 28) throw new EmailInvalidTokenError({ detail: "sealed token is too short" });
172
+ const key = await sealingKey(secretFor(keys, kid), sealed.slice(0, SALT_BYTES), "decrypt");
173
+ let plaintext;
174
+ try {
175
+ plaintext = await crypto.subtle.decrypt({
176
+ name: "AES-GCM",
177
+ iv: sealed.slice(SALT_BYTES, 28),
178
+ additionalData: sealedContext(kid)
179
+ }, key, sealed.slice(28));
180
+ } catch (cause) {
181
+ throw new EmailInvalidTokenError({ detail: "sealed token did not open" }, { cause });
182
+ }
183
+ let raw;
184
+ try {
185
+ raw = JSON.parse(decoder.decode(plaintext));
186
+ } catch (cause) {
187
+ throw new EmailInvalidTokenError({ detail: "sealed token payload is not JSON" }, { cause });
188
+ }
189
+ const parsed = CallbackToken.safeParse(raw);
190
+ if (!parsed.success || parsed.data.kid !== kid) throw new EmailInvalidTokenError({ detail: "token payload does not match the claim schema" });
191
+ return parsed.data;
192
+ }
193
+ /** Verify a `<payload>.<signature>` token in the signed format, or refuse it. */
194
+ async function openSigned(payloadB64, signatureB64, keys) {
111
195
  let raw;
112
196
  try {
113
197
  raw = JSON.parse(decoder.decode(base64UrlDecode(payloadB64)));
114
198
  } catch (cause) {
115
199
  throw new EmailInvalidTokenError({ detail: "token payload is not valid base64url JSON" }, { cause });
116
200
  }
117
- const parsed = CallbackToken.safeParse(raw);
201
+ const parsed = SignedCallbackToken.safeParse(raw);
118
202
  if (!parsed.success) throw new EmailInvalidTokenError({ detail: "token payload does not match the claim schema" });
119
- const versions = keys.versions;
120
- const secret = Object.hasOwn(versions, parsed.data.kid) ? versions[parsed.data.kid] : void 0;
121
- if (typeof secret !== "string") throw new EmailInvalidTokenError({ detail: `token kid '${parsed.data.kid}' is not in the valid key set` });
122
- const key = await importKey(secret);
203
+ const key = await hmacKey(secretFor(keys, parsed.data.kid));
123
204
  let valid;
124
205
  try {
125
206
  valid = await crypto.subtle.verify("HMAC", key, base64UrlDecode(signatureB64), encoder.encode(payloadB64));
@@ -127,10 +208,32 @@ async function verifyToken(token, keys, now, audience) {
127
208
  throw new EmailInvalidTokenError({ detail: "token signature could not be decoded" }, { cause });
128
209
  }
129
210
  if (!valid) throw new EmailInvalidTokenError({ detail: "token signature did not verify" });
130
- const expected = tokenAudience(audience);
131
- if (parsed.data.aud !== expected) throw new EmailInvalidTokenError({ detail: `token was minted for '${parsed.data.aud}' and presented at '${expected}'` });
132
- if (parsed.data.exp * 1e3 <= now.getTime()) throw new EmailInvalidTokenError({ detail: "token has expired" });
133
211
  return parsed.data;
134
212
  }
213
+ /**
214
+ * Verify a token against the valid key version set (`@pithy-sh/secrets`' `getVersions` shape) and return its claims.
215
+ * Rejects — as `email/invalid_token` — a malformed token, an unknown or pruned `kid`, a token whose seal or signature
216
+ * does not verify, a token minted for another origin, or an expired token. The order is deliberate: structure, then
217
+ * the cryptographic check, then audience, then expiry, so a forged token never reaches a claim check.
218
+ *
219
+ * `audience` is **required**, and is the URL the token arrived on — the request's own. A verifier that
220
+ * could omit it would be a verifier that accepts every origin, which is the hole the claim closes.
221
+ *
222
+ * **What the check cannot see:** where the caller got the URL. It compares against the string it is handed,
223
+ * so a caller that passed a value read out of the token, or a header a client controls, would pass every
224
+ * token. `http/callbacks.ts` hands it the request's own URL, and its route test plants a staging token on
225
+ * each route to hold that; a new verifying caller needs the same.
226
+ */
227
+ async function verifyToken(token, keys, now, audience) {
228
+ const parts = token.split(".");
229
+ let claims;
230
+ if (parts.length === 3 && parts[0] === SEALED_PREFIX && parts[1] && parts[2]) claims = await openSealed(parts[1], parts[2], keys);
231
+ else if (parts.length === 2 && parts[0] && parts[1]) claims = await openSigned(parts[0], parts[1], keys);
232
+ else throw new EmailInvalidTokenError({ detail: "token is not in a callback token form" });
233
+ const expected = tokenAudience(audience);
234
+ if (claims.aud !== expected) throw new EmailInvalidTokenError({ detail: `token was minted for '${claims.aud}' and presented at '${expected}'` });
235
+ if (claims.exp * 1e3 <= now.getTime()) throw new EmailInvalidTokenError({ detail: "token has expired" });
236
+ return claims;
237
+ }
135
238
  //#endregion
136
- export { CallbackToken, TokenKind, mintToken, tokenAudience, verifyToken };
239
+ export { CallbackToken, SEAL_LABEL, TokenKind, mintToken, tokenAudience, verifyToken };
@@ -21,14 +21,19 @@ export interface CallbackRequest {
21
21
  /** The URL the request arrived on. Only its origin is compared. */
22
22
  url: string;
23
23
  }
24
- /** Handle a click: record it, then 302-redirect to the signed http(s) destination. */
24
+ /** Handle a click: record it, then 302-redirect to the sealed http(s) destination. */
25
25
  export declare function handleClick(db: EmailDatabase, keys: SigningKeys, request: CallbackRequest, now: Date): Promise<Response>;
26
26
  /** Handle an open: record it, return the 1×1 pixel. */
27
27
  export declare function handleOpen(db: EmailDatabase, keys: SigningKeys, request: CallbackRequest, now: Date): Promise<Response>;
28
+ /**
29
+ * Render the unsubscribe page for a valid token, recording nothing. A forged, expired or misdirected token is refused
30
+ * here exactly as the POST would refuse it, so the page never offers a button that cannot work.
31
+ */
32
+ export declare function handleUnsubscribePage(keys: SigningKeys, request: CallbackRequest, now: Date): Promise<Response>;
28
33
  /**
29
34
  * Handle an unsubscribe: suppress the address (shared DB), record the opt-out event (app DB), confirm.
30
- * An optional `reason` — supplied by the app's own unsubscribe/preferences flow via the `?reason=` query
31
- * param — is stored on the suppression `detail` and the event, so a project can capture *why* someone
35
+ * An optional `reason` — supplied by the app's own unsubscribe/preferences flow in the POST's form body —
36
+ * is stored on the suppression `detail` and the event, so a project can capture *why* someone
32
37
  * opted out using its own logic. It is length-bounded so the link can't be used to stuff the column.
33
38
  */
34
39
  export declare function handleUnsubscribe(db: EmailDatabase, suppressionDb: EmailSuppressionDatabase, keys: SigningKeys, request: CallbackRequest, now: Date, reason?: string, environment?: string): Promise<Response>;
@@ -1 +1 @@
1
- {"version":3,"file":"callbacks.d.ts","sourceRoot":"","sources":["../../src/http/call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AAC,GAAG,EAAE,IAAI,CAAC,YAAY,CAAC,GAAG,IAAI,CAwF/D"}
@@ -7,7 +7,7 @@ import { resolveSigningKeys } from "../crypto/signingKey.js";
7
7
  import { EmailInvalidTokenError } from "../error/errors.js";
8
8
  import { verifyToken } from "../crypto/token.js";
9
9
  import { CALLBACK_BASE } from "../templates/engine.js";
10
- import { CallbackTokenParam, UnsubscribeQuery } from "./schemas.js";
10
+ import { CallbackTokenParam, UnsubscribeForm } from "./schemas.js";
11
11
  import { normalizeAddress } from "@pithy-sh/core/src/address/address";
12
12
  import { describeRoute } from "@pithy-sh/core/src/http/routeSpec";
13
13
  import { validate } from "@pithy-sh/core/src/http/validation";
@@ -20,7 +20,7 @@ async function verify(keys, request, expected, now) {
20
20
  if (claims.kind !== expected) throw new EmailInvalidTokenError({ detail: `token kind '${claims.kind}' does not match callback '${expected}'` });
21
21
  return claims;
22
22
  }
23
- /** Handle a click: record it, then 302-redirect to the signed http(s) destination. */
23
+ /** Handle a click: record it, then 302-redirect to the sealed http(s) destination. */
24
24
  async function handleClick(db, keys, request, now) {
25
25
  const claims = await verify(keys, request, "click", now);
26
26
  const destination = claims.destination ?? "";
@@ -58,10 +58,28 @@ async function handleOpen(db, keys, request, now) {
58
58
  }
59
59
  });
60
60
  }
61
+ /** The unsubscribe confirmation page. One button, posting back to this URL; nothing in it names the recipient. */
62
+ const UNSUBSCRIBE_PAGE = "<!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>";
63
+ /**
64
+ * Render the unsubscribe page for a valid token, recording nothing. A forged, expired or misdirected token is refused
65
+ * here exactly as the POST would refuse it, so the page never offers a button that cannot work.
66
+ */
67
+ async function handleUnsubscribePage(keys, request, now) {
68
+ await verify(keys, request, "unsubscribe", now);
69
+ return new Response(UNSUBSCRIBE_PAGE, {
70
+ status: 200,
71
+ headers: {
72
+ "content-type": "text/html; charset=utf-8",
73
+ "cache-control": "no-store, max-age=0",
74
+ "referrer-policy": "no-referrer",
75
+ "content-security-policy": "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; frame-ancestors 'none'"
76
+ }
77
+ });
78
+ }
61
79
  /**
62
80
  * Handle an unsubscribe: suppress the address (shared DB), record the opt-out event (app DB), confirm.
63
- * An optional `reason` — supplied by the app's own unsubscribe/preferences flow via the `?reason=` query
64
- * param — is stored on the suppression `detail` and the event, so a project can capture *why* someone
81
+ * An optional `reason` — supplied by the app's own unsubscribe/preferences flow in the POST's form body —
82
+ * is stored on the suppression `detail` and the event, so a project can capture *why* someone
65
83
  * opted out using its own logic. It is length-bounded so the link can't be used to stuff the column.
66
84
  */
67
85
  async function handleUnsubscribe(db, suppressionDb, keys, request, now, reason, environment) {
@@ -84,9 +102,31 @@ async function handleUnsubscribe(db, suppressionDb, keys, request, now, reason,
84
102
  }, now);
85
103
  return new Response("<p>You've been unsubscribed. Messages you ask for — a sign-in link, a security notice — still arrive. Nothing else will.</p>", {
86
104
  status: 200,
87
- headers: { "content-type": "text/html; charset=utf-8" }
105
+ headers: {
106
+ "content-type": "text/html; charset=utf-8",
107
+ "cache-control": "no-store, max-age=0",
108
+ "referrer-policy": "no-referrer",
109
+ "content-security-policy": "default-src 'none'; frame-ancestors 'none'"
110
+ }
88
111
  });
89
112
  }
113
+ /** The first value of a form field, or nothing. */
114
+ function firstValue(field) {
115
+ return Array.isArray(field) ? field[0] : field;
116
+ }
117
+ /**
118
+ * Read an unsubscribe POST's form body forgivingly: a body that will not parse reads as an empty form, so the
119
+ * validator after it sees `{}` and the opt-out still lands. Hono's form validator reads the parse this caches.
120
+ */
121
+ const forgivingForm = async (c, next) => {
122
+ const type = c.req.header("content-type") ?? "";
123
+ if (/^(multipart\/form-data|application\/x-www-form-urlencoded)/i.test(type)) try {
124
+ await c.req.formData();
125
+ } catch {
126
+ Object.assign(c.req.bodyCache, { formData: Promise.resolve(new FormData()) });
127
+ }
128
+ await next();
129
+ };
90
130
  /** Mount the click/open/unsubscribe callback routes under `${CALLBACK_BASE}` on the app's Hono router. */
91
131
  function registerCallbacks(app) {
92
132
  const setup = async (env) => {
@@ -99,7 +139,7 @@ function registerCallbacks(app) {
99
139
  };
100
140
  app.get(`${CALLBACK_BASE}/c/:token`, describeRoute({
101
141
  summary: "Record a click on a tracked link, then send the reader on to it.",
102
- description: "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.",
142
+ description: "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.",
103
143
  verification: "public",
104
144
  responses: { 302: { description: "A redirect to the link's destination, carried in `Location`." } }
105
145
  }), validate("param", CallbackTokenParam), async (c) => {
@@ -111,7 +151,7 @@ function registerCallbacks(app) {
111
151
  });
112
152
  app.get(`${CALLBACK_BASE}/o/:token`, describeRoute({
113
153
  summary: "Record that an email was opened.",
114
- description: "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.",
154
+ description: "Public: the token's seal is the only gate. The token may carry the `.png` suffix mail clients expect on an image URL.",
115
155
  verification: "public",
116
156
  responses: { 200: {
117
157
  description: "A 1×1 transparent PNG, never cached.",
@@ -124,22 +164,37 @@ function registerCallbacks(app) {
124
164
  url: c.req.url
125
165
  }, /* @__PURE__ */ new Date());
126
166
  });
127
- app.on(["GET", "POST"], `${CALLBACK_BASE}/u/:token`, describeRoute({
167
+ app.get(`${CALLBACK_BASE}/u/:token`, describeRoute({
168
+ summary: "Show the page that confirms an unsubscribe.",
169
+ description: "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.",
170
+ verification: "public",
171
+ responses: { 200: {
172
+ description: "A short HTML page with one button that unsubscribes.",
173
+ contentType: "text/html"
174
+ } }
175
+ }), validate("param", CallbackTokenParam), async (c) => {
176
+ const { keys } = await setup(c.env);
177
+ return handleUnsubscribePage(keys, {
178
+ token: c.req.valid("param").token,
179
+ url: c.req.url
180
+ }, /* @__PURE__ */ new Date());
181
+ });
182
+ app.post(`${CALLBACK_BASE}/u/:token`, describeRoute({
128
183
  summary: "Unsubscribe the recipient from everything but the mail they ask for.",
129
- description: "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.",
184
+ description: "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.",
130
185
  verification: "public",
131
186
  responses: { 200: {
132
187
  description: "A short HTML page confirming the opt-out.",
133
188
  contentType: "text/html"
134
189
  } }
135
- }), validate("param", CallbackTokenParam), validate("query", UnsubscribeQuery), async (c) => {
190
+ }), validate("param", CallbackTokenParam), forgivingForm, validate("form", UnsubscribeForm), async (c) => {
136
191
  const env = c.env;
137
192
  const { db, suppressionDb, keys } = await setup(env);
138
193
  return handleUnsubscribe(db, suppressionDb, keys, {
139
194
  token: c.req.valid("param").token,
140
195
  url: c.req.url
141
- }, /* @__PURE__ */ new Date(), c.req.valid("query").reason, env.ENVIRONMENT);
196
+ }, /* @__PURE__ */ new Date(), firstValue(c.req.valid("form").reason), env.ENVIRONMENT);
142
197
  });
143
198
  }
144
199
  //#endregion
145
- export { handleClick, handleOpen, handleUnsubscribe, registerCallbacks };
200
+ export { handleClick, handleOpen, handleUnsubscribe, handleUnsubscribePage, registerCallbacks };
@@ -1 +1 @@
1
- {"version":3,"file":"guards.d.ts","sourceRoot":"","sources":["../../src/http/guards.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,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MAAM,0BAA0B,EAAE,SAAS,iBAAiB,EAMlE,CAAC;AAEF;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,gBAAgB,CAAC,QAAQ,EAAE,MAAM,GAAG,qBAAqB,EAAE,CA4D1E"}
@@ -136,6 +136,15 @@ function emailAdminRoutes(basePath) {
136
136
  kind: "reads",
137
137
  summary: "Addresses this project will not send to, and why. Global — every environment shares it."
138
138
  },
139
+ {
140
+ method: "POST",
141
+ operation: "suppressions.lookup",
142
+ path: `${basePath}/suppressions/lookup`,
143
+ scope: EMAIL_SUPPRESSIONS_READ_SCOPE,
144
+ kind: "reads",
145
+ readInBody: true,
146
+ summary: "Whether one address is on the list, and why. The address travels in the body, never the URL."
147
+ },
139
148
  {
140
149
  method: "POST",
141
150
  operation: "suppressions.add",
@@ -11,6 +11,7 @@ import type { Hono } from "hono";
11
11
  * GET /email/jobs/:id → one job in full (control-plane: email:jobs:read) param
12
12
  * POST /email/jobs/:id/retry → queue it again (control-plane: email:jobs:retry) param
13
13
  * GET /email/suppressions → who we won't mail (control-plane: email:suppressions:read) query
14
+ * POST /email/suppressions/lookup → is this one blocked (control-plane: email:suppressions:read) json
14
15
  * POST /email/suppressions → block an address (control-plane: email:suppressions:write) json
15
16
  * POST /email/suppressions/remove → unblock one (control-plane: email:suppressions:delete) json
16
17
  *
@@ -31,10 +32,13 @@ import type { Hono } from "hono";
31
32
  * parsing every response would spend a validation pass on rows this Worker just read, and would turn a
32
33
  * shape mistake into a 500 in production rather than a red build.
33
34
  *
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.
35
+ * **An address never travels in a URL.** Removal is `POST /suppressions/remove`, not
36
+ * `DELETE /suppressions/:email`, and a lookup is `POST /suppressions/lookup`, not `?email=`. A path or a
37
+ * query string is in every access log, every proxy, every trace, and every referrer between the client
38
+ * and the Worker. The record is personal data whether or not it is a person's current address, so it
39
+ * travels in a body. Testers' `POST /remove` is the same call made for the same reason, and
40
+ * `addressedParameters` in `@pithy-sh/core/src/openapi/document` fails the kit's build on a route that
41
+ * declares one in its URL.
38
42
  */
39
43
  /** What every route this capability mounts declares: its path, its strategy, and the scope it checks. */
40
44
  export interface EmailRouteDeclaration {