@pithy-sh/email 0.9.0 → 0.10.1
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/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 +61 -21
- package/dist/http/schemas.d.ts +32 -13
- package/dist/http/schemas.d.ts.map +1 -1
- package/dist/http/schemas.js +33 -13
- 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/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 +93 -28
- package/src/http/schemas.ts +54 -22
- package/src/templates/engine.ts +1 -1
- package/src/version.generated.ts +1 -1
package/src/crypto/token.ts
CHANGED
|
@@ -5,22 +5,49 @@ import { z } from "zod";
|
|
|
5
5
|
import { EmailInvalidTokenError } from "../error/errors";
|
|
6
6
|
|
|
7
7
|
/**
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
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
|
-
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
-
*
|
|
21
|
-
*
|
|
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
|
|
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(
|
|
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
|
-
"
|
|
90
|
+
"Token format version. `3` is sealed with AES-256-GCM; `2`, the signed format, is read and never minted.",
|
|
45
91
|
),
|
|
46
|
-
|
|
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
|
|
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
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
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
|
-
*
|
|
105
|
-
*
|
|
106
|
-
*
|
|
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:
|
|
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
|
|
127
|
-
const
|
|
128
|
-
const
|
|
129
|
-
|
|
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
|
-
|
|
134
|
-
|
|
135
|
-
|
|
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
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
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
|
-
|
|
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 (
|
|
327
|
+
if (claims.aud !== expected) {
|
|
195
328
|
throw new EmailInvalidTokenError({
|
|
196
|
-
detail: `token was minted for '${
|
|
329
|
+
detail: `token was minted for '${claims.aud}' and presented at '${expected}'`,
|
|
197
330
|
});
|
|
198
331
|
}
|
|
199
332
|
|
|
200
|
-
if (
|
|
333
|
+
if (claims.exp * 1000 <= now.getTime()) {
|
|
201
334
|
throw new EmailInvalidTokenError({ detail: "token has expired" });
|
|
202
335
|
}
|
|
203
336
|
|
|
204
|
-
return
|
|
337
|
+
return claims;
|
|
205
338
|
}
|
package/src/http/callbacks.ts
CHANGED
|
@@ -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
|
|
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,
|
|
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
|
-
*
|
|
28
|
-
* session, and the token's
|
|
29
|
-
* (`email/invalid_token` → 400) before anything is recorded. The click route
|
|
30
|
-
* an `http(s)` destination carried inside the
|
|
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 |
|
|
35
|
-
* | GET | /_pithy/email/o/:token |
|
|
36
|
-
* | GET | /_pithy/email/u/:token |
|
|
37
|
-
* | POST | /_pithy/email/u/:token |
|
|
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
|
|
40
|
-
*
|
|
41
|
-
*
|
|
42
|
-
*
|
|
43
|
-
*
|
|
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
|
-
*
|
|
46
|
-
*
|
|
47
|
-
*
|
|
48
|
-
*
|
|
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<
|
|
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
|
|
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
|
|
156
|
-
*
|
|
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: {
|
|
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
|
|
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
|
|
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.
|
|
238
|
-
|
|
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
|
|
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
|
-
|
|
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("
|
|
326
|
+
firstValue(c.req.valid("form").reason),
|
|
259
327
|
env.ENVIRONMENT,
|
|
260
328
|
);
|
|
261
329
|
},
|
package/src/http/guards.ts
CHANGED
|
@@ -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",
|