@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.
- package/README.md +2 -0
- package/dist/bounce/handler.d.ts +22 -2
- package/dist/bounce/handler.d.ts.map +1 -1
- package/dist/bounce/handler.js +60 -17
- package/dist/capability.d.ts +12 -0
- package/dist/capability.d.ts.map +1 -1
- package/dist/capability.js +25 -15
- package/dist/crypto/signingKey.d.ts.map +1 -1
- package/dist/crypto/token.d.ts +43 -11
- package/dist/crypto/token.d.ts.map +1 -1
- package/dist/crypto/token.js +158 -55
- package/dist/http/callbacks.d.ts +8 -3
- package/dist/http/callbacks.d.ts.map +1 -1
- package/dist/http/callbacks.js +67 -12
- package/dist/http/guards.d.ts.map +1 -1
- package/dist/http/guards.js +9 -0
- package/dist/http/routes.d.ts +8 -4
- package/dist/http/routes.d.ts.map +1 -1
- package/dist/http/routes.js +67 -21
- package/dist/http/schemas.d.ts +41 -13
- package/dist/http/schemas.d.ts.map +1 -1
- package/dist/http/schemas.js +38 -15
- package/dist/jobs/read.d.ts +12 -9
- package/dist/jobs/read.d.ts.map +1 -1
- package/dist/jobs/read.js +6 -5
- package/dist/migrations/0002_job_filters.d.ts +15 -0
- package/dist/migrations/0002_job_filters.d.ts.map +1 -0
- package/dist/migrations/0002_job_filters.js +25 -0
- package/dist/send/enqueue.d.ts +26 -3
- package/dist/send/enqueue.d.ts.map +1 -1
- package/dist/send/enqueue.js +25 -2
- package/dist/send/errorMapping.d.ts +15 -20
- package/dist/send/errorMapping.d.ts.map +1 -1
- package/dist/send/errorMapping.js +33 -27
- package/dist/send/runSend.d.ts +2 -2
- package/dist/send/runSend.d.ts.map +1 -1
- package/dist/send/runSend.js +1 -1
- package/dist/send/suppression.d.ts +4 -0
- package/dist/send/suppression.d.ts.map +1 -1
- package/dist/send/suppression.js +4 -0
- package/dist/templates/engine.d.ts +1 -1
- package/dist/templates/engine.js +1 -1
- package/dist/version.generated.d.ts +1 -1
- package/dist/version.generated.d.ts.map +1 -1
- package/dist/version.generated.js +1 -1
- package/package.json +3 -3
- package/src/bounce/handler.ts +84 -32
- package/src/capability.ts +47 -27
- package/src/crypto/signingKey.ts +4 -2
- package/src/crypto/token.ts +225 -92
- package/src/http/callbacks.ts +100 -32
- package/src/http/guards.ts +9 -0
- package/src/http/routes.ts +96 -28
- package/src/http/schemas.ts +75 -24
- package/src/jobs/read.ts +14 -9
- package/src/migrations/0002_job_filters.ts +35 -0
- package/src/send/enqueue.ts +52 -5
- package/src/send/errorMapping.ts +45 -38
- package/src/send/runSend.ts +6 -7
- package/src/send/suppression.ts +13 -0
- package/src/templates/engine.ts +1 -1
- package/src/version.generated.ts +1 -1
package/dist/crypto/token.js
CHANGED
|
@@ -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
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
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
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
-
*
|
|
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
|
|
30
|
-
const
|
|
31
|
-
|
|
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
|
-
}
|
|
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
|
-
|
|
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, ["
|
|
122
|
+
}, false, ["verify"]);
|
|
74
123
|
}
|
|
75
124
|
/**
|
|
76
|
-
*
|
|
77
|
-
*
|
|
78
|
-
*
|
|
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:
|
|
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
|
|
89
|
-
const
|
|
90
|
-
|
|
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
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
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 =
|
|
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
|
|
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 };
|
package/dist/http/callbacks.d.ts
CHANGED
|
@@ -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
|
|
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
|
|
31
|
-
*
|
|
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/callbacks.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,0CAA0C,CAAC;AAI7E,OAAO,KAAK,EAAE,IAAI,
|
|
1
|
+
{"version":3,"file":"callbacks.d.ts","sourceRoot":"","sources":["../../src/http/callbacks.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,0CAA0C,CAAC;AAI7E,OAAO,KAAK,EAAE,IAAI,EAAqB,MAAM,MAAM,CAAC;AAGpD,OAAO,EACL,KAAK,aAAa,EAClB,KAAK,wBAAwB,EAG9B,MAAM,gBAAgB,CAAC;AA8CxB,8DAA8D;AAC9D,MAAM,WAAW,WAAW;IAC1B,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CAClC;AAQD;;;;;;;GAOG;AACH,MAAM,WAAW,eAAe;IAC9B,4CAA4C;IAC5C,KAAK,EAAE,MAAM,CAAC;IACd,mEAAmE;IACnE,GAAG,EAAE,MAAM,CAAC;CACb;AAgBD,sFAAsF;AACtF,wBAAsB,WAAW,CAC/B,EAAE,EAAE,aAAa,EACjB,IAAI,EAAE,WAAW,EACjB,OAAO,EAAE,eAAe,EACxB,GAAG,EAAE,IAAI,GACR,OAAO,CAAC,QAAQ,CAAC,CAmBnB;AAED,uDAAuD;AACvD,wBAAsB,UAAU,CAC9B,EAAE,EAAE,aAAa,EACjB,IAAI,EAAE,WAAW,EACjB,OAAO,EAAE,eAAe,EACxB,GAAG,EAAE,IAAI,GACR,OAAO,CAAC,QAAQ,CAAC,CAgBnB;AAMD;;;GAGG;AACH,wBAAsB,qBAAqB,CAAC,IAAI,EAAE,WAAW,EAAE,OAAO,EAAE,eAAe,EAAE,GAAG,EAAE,IAAI,GAAG,OAAO,CAAC,QAAQ,CAAC,CAYrH;AAED;;;;;GAKG;AACH,wBAAsB,iBAAiB,CACrC,EAAE,EAAE,aAAa,EACjB,aAAa,EAAE,wBAAwB,EACvC,IAAI,EAAE,WAAW,EACjB,OAAO,EAAE,eAAe,EACxB,GAAG,EAAE,IAAI,EACT,MAAM,CAAC,EAAE,MAAM,EACf,WAAW,CAAC,EAAE,MAAM,GACnB,OAAO,CAAC,QAAQ,CAAC,CA4BnB;AAuBD,0GAA0G;AAC1G,wBAAgB,iBAAiB,CAAC,GAAG,EAAE,IAAI,CAAC,YAAY,CAAC,GAAG,IAAI,CAwF/D"}
|
package/dist/http/callbacks.js
CHANGED
|
@@ -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,
|
|
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
|
|
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
|
|
64
|
-
*
|
|
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: {
|
|
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
|
|
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
|
|
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.
|
|
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
|
|
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("
|
|
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("
|
|
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,sDAAsD,CAAC;AAClG,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,6CAA6C,CAAC;AAErF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+CG;AAEH;;;;;;;GAOG;AACH,eAAO,MAAM,qBAAqB,EAAE,iBAAqC,CAAC;AAE1E;;;GAGG;AACH,eAAO,MAAM,sBAAsB,EAAE,iBAAsC,CAAC;AAE5E;;;GAGG;AACH,eAAO,MAAM,6BAA6B,EAAE,iBAA6C,CAAC;AAE1F,kGAAkG;AAClG,eAAO,MAAM,8BAA8B,EAAE,iBAA8C,CAAC;AAE5F;;;;GAIG;AACH,eAAO,MAAM,+BAA+B,EAAE,iBAA+C,CAAC;AAE9F;;;GAGG;AACH,eAAO,MAAM,0BAA0B,EAAE,SAAS,iBAAiB,EAMlE,CAAC;AAEF;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,gBAAgB,CAAC,QAAQ,EAAE,MAAM,GAAG,qBAAqB,EAAE,
|
|
1
|
+
{"version":3,"file":"guards.d.ts","sourceRoot":"","sources":["../../src/http/guards.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,sDAAsD,CAAC;AAClG,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,6CAA6C,CAAC;AAErF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+CG;AAEH;;;;;;;GAOG;AACH,eAAO,MAAM,qBAAqB,EAAE,iBAAqC,CAAC;AAE1E;;;GAGG;AACH,eAAO,MAAM,sBAAsB,EAAE,iBAAsC,CAAC;AAE5E;;;GAGG;AACH,eAAO,MAAM,6BAA6B,EAAE,iBAA6C,CAAC;AAE1F,kGAAkG;AAClG,eAAO,MAAM,8BAA8B,EAAE,iBAA8C,CAAC;AAE5F;;;;GAIG;AACH,eAAO,MAAM,+BAA+B,EAAE,iBAA+C,CAAC;AAE9F;;;GAGG;AACH,eAAO,MAAM,0BAA0B,EAAE,SAAS,iBAAiB,EAMlE,CAAC;AAEF;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,gBAAgB,CAAC,QAAQ,EAAE,MAAM,GAAG,qBAAqB,EAAE,CA4D1E"}
|
package/dist/http/guards.js
CHANGED
|
@@ -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",
|
package/dist/http/routes.d.ts
CHANGED
|
@@ -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
|
-
* **
|
|
35
|
-
*
|
|
36
|
-
*
|
|
37
|
-
*
|
|
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 {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"routes.d.ts","sourceRoot":"","sources":["../../src/http/routes.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,0CAA0C,CAAC;AAG7E,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,6CAA6C,CAAC;AAKrF,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,sCAAsC,CAAC;AAEjF,OAAO,KAAK,EAAW,IAAI,EAAE,MAAM,MAAM,CAAC;
|
|
1
|
+
{"version":3,"file":"routes.d.ts","sourceRoot":"","sources":["../../src/http/routes.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,0CAA0C,CAAC;AAG7E,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,6CAA6C,CAAC;AAKrF,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,sCAAsC,CAAC;AAEjF,OAAO,KAAK,EAAW,IAAI,EAAE,MAAM,MAAM,CAAC;AAsC1C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AAEH,yGAAyG;AACzG,MAAM,WAAW,qBAAqB;IACpC,QAAQ,CAAC,MAAM,EAAE,KAAK,GAAG,MAAM,CAAC;IAChC,oEAAoE;IACpE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,QAAQ,EAAE,oBAAoB,CAAC;IACxC,iDAAiD;IACjD,QAAQ,CAAC,KAAK,EAAE,iBAAiB,CAAC;CACnC;AAED;;;;;;;GAOG;AACH,eAAO,MAAM,kBAAkB,EAAE,SAAS,qBAAqB,EAkB9D,CAAC;AAaF,oDAAoD;AACpD,MAAM,WAAW,uBAAuB;IACtC;;;;;;;OAOG;IACH,QAAQ,EAAE,MAAM,CAAC;IACjB,4EAA4E;IAC5E,GAAG,CAAC,EAAE,MAAM,IAAI,CAAC;CAClB;AA4ED,yFAAyF;AACzF,wBAAgB,wBAAwB,CAAC,OAAO,EAAE,uBAAuB,GAAG,CAAC,GAAG,EAAE,IAAI,CAAC,YAAY,CAAC,KAAK,IAAI,CAuV5G"}
|