@tokenoftrust/storefront-runner 7.14.3 → 7.15.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.
@@ -64,6 +64,10 @@ interface CloudflareEnv {
64
64
  TOT_ACCESS_TOKEN?: string;
65
65
  /** HMAC secret for signing/verifying customization preview tokens. */
66
66
  CUSTOMIZATION_PREVIEW_SECRET?: string;
67
+ /** Dedicated HMAC secret for the `checkout.abandoned` resume link (`checkoutResume.ts`). */
68
+ CHECKOUT_RESUME_SIGNING_SECRET?: string;
69
+ /** Newsletter consent salt: the consent IP hash and the confirm-link key (`newsletter/consent.ts`). */
70
+ NEWSLETTER_CONSENT_SALT?: string;
67
71
  /**
68
72
  * Managed checkout (Track A). `FOXY_STORE_SUBDOMAIN` overrides the tenant's default
69
73
  * demo store subdomain (swap the demo store with zero code change).
@@ -1,11 +1,17 @@
1
1
  /**
2
- * Consent-record primitives for the newsletter double-opt-in flow.
2
+ * Consent-record primitives for the newsletter double-opt-in flow. Web Crypto only (no `node:*`),
3
+ * so they run identically in the Worker and in tests.
3
4
  *
4
- * `randomToken` mints the opaque per-subscriber secret that both the confirm and
5
- * unsubscribe links carry — Web Crypto only (no `node:*`) so it runs
6
- * identically in the Worker and in tests. `hashConsentIp` is the GDPR-safe IP
7
- * record: we store `sha256(ip + ":" + salt)`, NEVER the raw IP (repo convention:
8
- * opaque hashes only, cf. `apps/orders/customerHash.ts`).
5
+ * - `randomToken` mints the opaque per-subscriber row secret. It is the unsubscribe capability and
6
+ * the row the confirm link addresses.
7
+ * - `hashConsentIp` is the GDPR-safe IP record: `sha256(ip + ":" + salt)`, never the raw IP.
8
+ * - `resolveConsentSalt` is the one source of the `NEWSLETTER_CONSENT_SALT` value. Outside a local
9
+ * dev build a missing salt is `null` and the caller refuses; there is no fallback salt.
10
+ * - `signConfirmToken` / `verifyConfirmToken` produce and check the emailed confirm link token:
11
+ * `v1.<base64url(JSON claims)>.<base64url(HMAC-SHA256)>` over the claims
12
+ * `{ t: tenantId, s: stage, c: collection, r: rowToken, e: expiry (epoch seconds) }`. The MAC key
13
+ * is `HMAC-SHA256(salt, "newsletter-confirm:v1")`, so the salt's other uses never share a key with
14
+ * the confirm link. A token lives at most {@link CONFIRM_TOKEN_TTL_SECONDS}.
9
15
  */
10
16
  import { sha256Hex } from "@tot/public-runtime";
11
17
 
@@ -21,3 +27,106 @@ export function randomToken(): string {
21
27
  export function hashConsentIp(ip: string, salt: string): Promise<string> {
22
28
  return sha256Hex(`${ip}:${salt}`);
23
29
  }
30
+
31
+ /** The salt a local dev build (`astro dev`) uses when none is configured. Never used by a deployed Worker. */
32
+ const LOCAL_DEV_CONSENT_SALT = "newsletter-consent-local-dev-salt";
33
+
34
+ /**
35
+ * The configured consent salt, or the local-dev salt in a local dev build. `null` means refuse:
36
+ * a deployed Worker without `NEWSLETTER_CONSENT_SALT` writes nothing and verifies nothing.
37
+ */
38
+ export function resolveConsentSalt(configured: string | undefined, localDev: boolean): string | null {
39
+ const salt = configured?.trim();
40
+ if (salt) return salt;
41
+ return localDev ? LOCAL_DEV_CONSENT_SALT : null;
42
+ }
43
+
44
+ export type ConfirmStage = "preview" | "publication";
45
+
46
+ export interface ConfirmClaims {
47
+ tenantId: string;
48
+ stage: ConfirmStage;
49
+ collection: string;
50
+ /** The subscriber row's `token`. */
51
+ rowToken: string;
52
+ /** Expiry, epoch seconds. */
53
+ exp: number;
54
+ }
55
+
56
+ /** A confirm link is valid for 72 hours after it is sent. */
57
+ export const CONFIRM_TOKEN_TTL_SECONDS = 72 * 3600;
58
+
59
+ const CONFIRM_VERSION = "v1";
60
+ const CONFIRM_KEY_LABEL = "newsletter-confirm:v1";
61
+ const encoder = new TextEncoder();
62
+
63
+ function base64url(bytes: Uint8Array): string {
64
+ let bin = "";
65
+ for (const b of bytes) bin += String.fromCharCode(b);
66
+ return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
67
+ }
68
+
69
+ function fromBase64url(text: string): Uint8Array<ArrayBuffer> | undefined {
70
+ if (!/^[A-Za-z0-9_-]+$/.test(text) || text.length % 4 === 1) return undefined;
71
+ const bin = atob(text.replace(/-/g, "+").replace(/_/g, "/"));
72
+ const out = new Uint8Array(bin.length);
73
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
74
+ return out;
75
+ }
76
+
77
+ async function confirmKey(salt: string, usage: "sign" | "verify"): Promise<CryptoKey> {
78
+ const root = await crypto.subtle.importKey("raw", encoder.encode(salt), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
79
+ const derived = await crypto.subtle.sign("HMAC", root, encoder.encode(CONFIRM_KEY_LABEL));
80
+ return crypto.subtle.importKey("raw", derived, { name: "HMAC", hash: "SHA-256" }, false, [usage]);
81
+ }
82
+
83
+ function signedBytes(payload: string): Uint8Array<ArrayBuffer> {
84
+ return new Uint8Array(encoder.encode(`${CONFIRM_VERSION}.${payload}`));
85
+ }
86
+
87
+ /** Sign a confirm token for one subscriber row, expiring {@link CONFIRM_TOKEN_TTL_SECONDS} after `nowMs`. */
88
+ export async function signConfirmToken(
89
+ salt: string,
90
+ claims: Omit<ConfirmClaims, "exp">,
91
+ nowMs: number = Date.now(),
92
+ ): Promise<string> {
93
+ const exp = Math.floor(nowMs / 1000) + CONFIRM_TOKEN_TTL_SECONDS;
94
+ const payload = base64url(encoder.encode(JSON.stringify({
95
+ t: claims.tenantId, s: claims.stage, c: claims.collection, r: claims.rowToken, e: exp,
96
+ })));
97
+ const mac = await crypto.subtle.sign("HMAC", await confirmKey(salt, "sign"), signedBytes(payload));
98
+ return `${CONFIRM_VERSION}.${payload}.${base64url(new Uint8Array(mac))}`;
99
+ }
100
+
101
+ /**
102
+ * The claims of an authentic, unexpired confirm token, or `null`. The signature is checked with
103
+ * `crypto.subtle.verify` (constant time) before any claim is read. The caller still matches the
104
+ * tenant, stage and collection against the request.
105
+ */
106
+ export async function verifyConfirmToken(
107
+ salt: string,
108
+ token: string,
109
+ nowMs: number = Date.now(),
110
+ ): Promise<ConfirmClaims | null> {
111
+ const parts = token.split(".");
112
+ if (parts.length !== 3 || parts[0] !== CONFIRM_VERSION) return null;
113
+ const [, payload, sig] = parts as [string, string, string];
114
+ const sigBytes = fromBase64url(sig);
115
+ const payloadBytes = fromBase64url(payload);
116
+ if (!sigBytes || !payloadBytes) return null;
117
+ if (!(await crypto.subtle.verify("HMAC", await confirmKey(salt, "verify"), sigBytes, signedBytes(payload)))) return null;
118
+
119
+ let raw: Record<string, unknown>;
120
+ try {
121
+ raw = JSON.parse(new TextDecoder().decode(payloadBytes)) as Record<string, unknown>;
122
+ } catch {
123
+ return null;
124
+ }
125
+ const { t, s, c, r, e } = raw;
126
+ if (typeof t !== "string" || !t || typeof c !== "string" || !c || typeof r !== "string" || !r) return null;
127
+ if (s !== "preview" && s !== "publication") return null;
128
+ if (typeof e !== "number" || !Number.isInteger(e)) return null;
129
+ const now = Math.floor(nowMs / 1000);
130
+ if (e <= now || e - now > CONFIRM_TOKEN_TTL_SECONDS) return null;
131
+ return { tenantId: t, stage: s, collection: c, rowToken: r, exp: e };
132
+ }
@@ -33,6 +33,29 @@ export interface SubscribeResult {
33
33
 
34
34
  export type ConfirmResult = "confirmed" | "already" | "not_found";
35
35
 
36
+ /** The marketing consent a confirmation grants: the shopper scope and shopper id it is recorded under. */
37
+ export interface MarketingConsentGrant {
38
+ /** The commerce tenant id of the shopper scope. */
39
+ tenantId: string;
40
+ stage: "preview" | "publication";
41
+ /** The shopper id. Never an email. */
42
+ customerRef: string;
43
+ }
44
+
45
+ export interface ConfirmInput {
46
+ tenantId: string;
47
+ collection: string;
48
+ token: string;
49
+ /** Resolves the consent the confirmed address grants; `null` grants none. Called only for a pending row. */
50
+ grantFor?: (email: string) => Promise<MarketingConsentGrant | null>;
51
+ }
52
+
53
+ export interface ConfirmOutcome {
54
+ result: ConfirmResult;
55
+ /** Set when this confirmation inserted a `customer_marketing_consents` row. */
56
+ granted?: { customerRef: string; grantedAt: string };
57
+ }
58
+
36
59
  interface SubscriberRow {
37
60
  status: string;
38
61
  token: string;
@@ -80,29 +103,81 @@ export class NewsletterSubscribersStore {
80
103
 
81
104
  /**
82
105
  * Flip a `pending` subscriber to `confirmed` by its opaque token, scoped to
83
- * the caller's tenant. Idempotent: re-confirming an already-`confirmed` token
84
- * is a no-op success, not an error. An unknown token — or one whose row is
85
- * `unsubscribed`/`bounced` (the confirm link is no longer valid) — is
86
- * `not_found`.
106
+ * the caller's tenant and collection. Idempotent: re-confirming an already-`confirmed`
107
+ * token is a no-op success that writes nothing. An unknown token — or one whose row is
108
+ * `unsubscribed`/`bounced` (the confirm link is no longer valid) — is `not_found`.
109
+ *
110
+ * When `grantFor` resolves a grant, one batch flips the row while recording a fresh consent id
111
+ * on it, inserts the email `customer_marketing_consents` row (source `storefront-form`) under that
112
+ * id, and clears the id if no row was inserted. The insert applies only when that batch's own
113
+ * flip moved the row from `pending` to `confirmed`: an unsubscribe or another confirmation that
114
+ * lands while the grant is resolved leaves no consent from this call. The insert is
115
+ * `ON CONFLICT DO NOTHING`: an existing row for that shopper and channel, granted or revoked, is
116
+ * left as it is and not linked, and `granted` is set only when a row was inserted.
87
117
  */
88
- async confirmByToken(input: { tenantId: string; token: string }): Promise<ConfirmResult> {
118
+ async confirmByToken(input: ConfirmInput): Promise<ConfirmOutcome> {
119
+ const scope = [input.tenantId, input.collection, input.token] as const;
89
120
  const row = await this.db.first<SubscriberRow>(
90
- `SELECT status FROM newsletter_subscribers WHERE tenant_id = ? AND token = ?`,
91
- input.tenantId,
92
- input.token,
121
+ `SELECT status, email FROM newsletter_subscribers WHERE tenant_id = ? AND collection = ? AND token = ?`,
122
+ ...scope,
93
123
  );
94
- if (!row) return "not_found";
95
- if (row.status === "confirmed") return "already";
96
- if (row.status !== "pending") return "not_found";
97
- await this.db.run(
98
- `UPDATE newsletter_subscribers
124
+ if (!row) return { result: "not_found" };
125
+ if (row.status === "confirmed") return { result: "already" };
126
+ if (row.status !== "pending") return { result: "not_found" };
127
+
128
+ const grant = input.grantFor && row.email ? await input.grantFor(row.email) : null;
129
+ const now = this.now();
130
+ const confirm = {
131
+ sql: `UPDATE newsletter_subscribers
99
132
  SET status = 'confirmed', confirmed_at = ?
100
- WHERE tenant_id = ? AND token = ? AND status = 'pending'`,
101
- this.now(),
133
+ WHERE tenant_id = ? AND collection = ? AND token = ? AND status = 'pending'
134
+ RETURNING token`,
135
+ params: [now, ...scope],
136
+ };
137
+ if (!grant) {
138
+ const flipped = await this.db.all(confirm.sql, ...confirm.params);
139
+ return flipped.length > 0 ? { result: "confirmed" } : this.lostTransition(input);
140
+ }
141
+ if (!this.db.batchResults) throw new Error("newsletter-confirm-batch-unavailable");
142
+ // This attempt's own id is written by the flip itself, so only the batch whose flip moved the
143
+ // row out of `pending` finds it there: the insert is gated on it, never on a timestamp.
144
+ const consentId = crypto.randomUUID();
145
+ const [flipped, inserted] = await this.db.batchResults([{
146
+ sql: `UPDATE newsletter_subscribers
147
+ SET status = 'confirmed', confirmed_at = ?, marketing_consent_id = ?
148
+ WHERE tenant_id = ? AND collection = ? AND token = ? AND status = 'pending'
149
+ RETURNING token`,
150
+ params: [now, consentId, ...scope],
151
+ }, {
152
+ sql: `INSERT INTO customer_marketing_consents
153
+ (consent_id, tenant_id, stage, customer_ref, channel, purpose, source, granted_at)
154
+ SELECT ?, ?, ?, ?, 'email', 'marketing-communications', 'storefront-form', ?
155
+ WHERE EXISTS (SELECT 1 FROM newsletter_subscribers
156
+ WHERE tenant_id = ? AND collection = ? AND token = ? AND marketing_consent_id = ?)
157
+ ON CONFLICT (tenant_id, stage, customer_ref, channel) DO NOTHING
158
+ RETURNING consent_id`,
159
+ params: [consentId, grant.tenantId, grant.stage, grant.customerRef, now, ...scope, consentId],
160
+ }, {
161
+ sql: `UPDATE newsletter_subscribers SET marketing_consent_id = NULL
162
+ WHERE tenant_id = ? AND collection = ? AND token = ? AND marketing_consent_id = ?
163
+ AND NOT EXISTS (SELECT 1 FROM customer_marketing_consents WHERE consent_id = ?)`,
164
+ params: [...scope, consentId, consentId],
165
+ }]);
166
+ if ((flipped?.results.length ?? 0) === 0) return this.lostTransition(input);
167
+ return (inserted?.results.length ?? 0) > 0
168
+ ? { result: "confirmed", granted: { customerRef: grant.customerRef, grantedAt: now } }
169
+ : { result: "confirmed" };
170
+ }
171
+
172
+ /** The row left `pending` between the read and the flip: another confirm won, or it was unsubscribed. */
173
+ private async lostTransition(input: ConfirmInput): Promise<ConfirmOutcome> {
174
+ const row = await this.db.first<SubscriberRow>(
175
+ `SELECT status FROM newsletter_subscribers WHERE tenant_id = ? AND collection = ? AND token = ?`,
102
176
  input.tenantId,
177
+ input.collection,
103
178
  input.token,
104
179
  );
105
- return "confirmed";
180
+ return { result: row?.status === "confirmed" ? "already" : "not_found" };
106
181
  }
107
182
  }
108
183
 
@@ -114,10 +189,33 @@ export class NewsletterSubscribersStore {
114
189
  */
115
190
  export type UnsubscribeOutcome = "unsubscribed" | "already-unsubscribed" | "unknown-token";
116
191
 
192
+ /** The marketing consent an unsubscribe revoked: the one this subscriber's confirmation granted. */
193
+ export interface RevokedMarketingConsent {
194
+ tenantId: string;
195
+ stage: "preview" | "publication";
196
+ /** The shopper id. Never an email. */
197
+ customerRef: string;
198
+ revokedAt: string;
199
+ /** Whether that shopper still holds an unrevoked marketing consent on another channel. */
200
+ stillConsented: boolean;
201
+ }
202
+
203
+ export interface UnsubscribeResult {
204
+ outcome: UnsubscribeOutcome;
205
+ /** Set when this call revoked the consent the subscriber's confirmation granted. */
206
+ revoked?: RevokedMarketingConsent;
207
+ }
208
+
117
209
  interface StatusRow {
118
210
  status: string;
119
211
  }
120
212
 
213
+ interface RevokedRow {
214
+ tenant_id: string;
215
+ stage: string;
216
+ customer_ref: string;
217
+ }
218
+
121
219
  /**
122
220
  * Flip the subscriber addressed by `token` to `unsubscribed`, stamping `unsubscribed_at`
123
221
  * on the FIRST transition only. Idempotent: re-unsubscribing an already-unsubscribed
@@ -130,27 +228,61 @@ interface StatusRow {
130
228
  * exactly one row without ever putting the email in the URL (which would leak PII into
131
229
  * access logs). Lookup is by token alone — no tenant/collection needed — and every
132
230
  * write is scoped to that single token, so it can only ever touch the one row it names.
231
+ *
232
+ * It then revokes the email marketing consent that subscriber's confirmation granted
233
+ * (`marketing_consent_id`), and no other consent. The flip runs first, so a confirmation
234
+ * resolving its grant at the same moment can no longer insert one; a confirmation that already
235
+ * committed has linked its consent, which this revokes. A repeat unsubscribe revokes a linked
236
+ * consent a failed earlier attempt left active.
133
237
  */
134
238
  export async function unsubscribeByToken(
135
239
  db: Queryable,
136
240
  token: string,
137
241
  now: string,
138
- ): Promise<UnsubscribeOutcome> {
139
- if (!token) return "unknown-token";
242
+ ): Promise<UnsubscribeResult> {
243
+ if (!token) return { outcome: "unknown-token" };
140
244
 
141
245
  const row = await db.first<StatusRow>(
142
246
  "SELECT status FROM newsletter_subscribers WHERE token = ?",
143
247
  token,
144
248
  );
145
- if (!row) return "unknown-token";
146
- if (row.status === "unsubscribed") return "already-unsubscribed";
249
+ if (!row) return { outcome: "unknown-token" };
147
250
 
148
251
  // Guard the UPDATE on the current status too, so a concurrent double-submit can't
149
252
  // overwrite the first `unsubscribed_at`.
150
- await db.run(
151
- "UPDATE newsletter_subscribers SET status = 'unsubscribed', unsubscribed_at = ? WHERE token = ? AND status != 'unsubscribed'",
253
+ if (row.status !== "unsubscribed") {
254
+ await db.run(
255
+ "UPDATE newsletter_subscribers SET status = 'unsubscribed', unsubscribed_at = ? WHERE token = ? AND status != 'unsubscribed'",
256
+ now,
257
+ token,
258
+ );
259
+ }
260
+ const outcome: UnsubscribeOutcome = row.status === "unsubscribed" ? "already-unsubscribed" : "unsubscribed";
261
+
262
+ const [revoked] = await db.all<RevokedRow>(
263
+ `UPDATE customer_marketing_consents SET revoked_at = ?
264
+ WHERE consent_id = (SELECT marketing_consent_id FROM newsletter_subscribers WHERE token = ?)
265
+ AND revoked_at IS NULL
266
+ RETURNING tenant_id, stage, customer_ref`,
152
267
  now,
153
268
  token,
154
269
  );
155
- return "unsubscribed";
270
+ if (!revoked) return { outcome };
271
+ const other = await db.first(
272
+ `SELECT 1 AS held FROM customer_marketing_consents
273
+ WHERE tenant_id = ? AND stage = ? AND customer_ref = ? AND revoked_at IS NULL`,
274
+ revoked.tenant_id,
275
+ revoked.stage,
276
+ revoked.customer_ref,
277
+ );
278
+ return {
279
+ outcome,
280
+ revoked: {
281
+ tenantId: revoked.tenant_id,
282
+ stage: revoked.stage as RevokedMarketingConsent["stage"],
283
+ customerRef: revoked.customer_ref,
284
+ revokedAt: now,
285
+ stillConsented: other !== null,
286
+ },
287
+ };
156
288
  }
@@ -5,24 +5,38 @@
5
5
  * Discipline (mirrors the other public POSTs, `blog/.../react.ts` / `newsletter.ts`):
6
6
  * - `tenant_id` is resolved from `locals.tenant`, `collection` from the ROUTE —
7
7
  * NEVER the request body (tenant is the isolation boundary).
8
+ * - The routed stage (`preview` / `publication`) and `NEWSLETTER_CONSENT_SALT` are required:
9
+ * an unknown stage refuses (409) and a missing salt outside a local dev build refuses (503),
10
+ * both before any write.
8
11
  * - A per-visitor KV rate limit (`kvWindow`, keyed on the hashed client IP,
9
12
  * fail-closed) stops scripted signups; a missing or failing KV refuses (503).
10
13
  * - `INSERT OR IGNORE` a `pending` row with a fresh opaque token + consent
11
- * record (`consent_source` = referrer, `consent_ip_hash` = sha256(ip+salt) —
12
- * NEVER a raw IP). A repeat subscribe is idempotent.
14
+ * record (`consent_source` = the same-origin referring path, `consent_ip_hash` =
15
+ * sha256(ip+salt) — NEVER a raw IP). A repeat subscribe is idempotent.
16
+ * - The emailed confirm link carries a signed token bound to (tenant, stage, collection,
17
+ * row) that expires after `CONFIRM_TOKEN_TTL_SECONDS` (`consent.ts`).
13
18
  * - A confirmation email that cannot be sent, a missing apps DB and a failed
14
19
  * write are errors (502/503 JSON), never a success: the visitor is not told to
15
20
  * check an inbox that will stay empty. A retry re-sends while the row is pending.
21
+ * - A Referer that is present but malformed or from another origin refuses (403) before the
22
+ * rate limit, any write or any mail. An absent Referer is accepted with no consent source.
16
23
  * - Never 500. A `fetch`/JSON caller gets a clean JSON body; a plain form POST
17
- * that succeeded is redirected back to the referrer so the page can show its own thanks.
24
+ * that succeeded is redirected back to a same-origin referrer so the page can show its own
25
+ * thanks.
18
26
  */
19
27
  import type { APIRoute } from "astro";
20
28
  import { readD1, readKv, readEnv } from "@/lib/publication/shared/env";
21
29
  import { fromD1 } from "@/lib/catalog/d1/catalog";
22
30
  import { checkRateLimit } from "@/lib/access/rate/kvWindow";
23
31
  import { requestClientIp } from "@/lib/publication/shared/cdnForward";
32
+ import { resolveShopperScope } from "@/lib/customers/accounts/scope";
24
33
  import { NewsletterSubscribersStore } from "@/lib/engagement/newsletter/subscribers";
25
- import { randomToken, hashConsentIp } from "@/lib/engagement/newsletter/consent";
34
+ import {
35
+ hashConsentIp,
36
+ randomToken,
37
+ resolveConsentSalt,
38
+ signConfirmToken,
39
+ } from "@/lib/engagement/newsletter/consent";
26
40
  import { sendConfirmationEmail } from "@/lib/engagement/newsletter/confirmationEmail";
27
41
 
28
42
  export const prerender = false;
@@ -31,8 +45,6 @@ const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
31
45
  const COLLECTION_RE = /^[a-z0-9][a-z0-9._-]*$/;
32
46
  const RATE_WINDOW_SECONDS = 3600;
33
47
  const RATE_MAX_PER_WINDOW = 5;
34
- /** Dev fallback only — production sets NEWSLETTER_CONSENT_SALT as a secret. */
35
- const DEV_CONSENT_SALT = "newsletter-consent-dev-salt";
36
48
 
37
49
  function json(body: unknown, status = 200): Response {
38
50
  return new Response(JSON.stringify(body), {
@@ -63,18 +75,27 @@ function wantsJson(request: Request): boolean {
63
75
  return (request.headers.get("accept") ?? "").includes("application/json");
64
76
  }
65
77
 
66
- /** Success response: JSON for fetch, else redirect back to the referrer with a flag. */
67
- function ok(request: Request): Response {
68
- if (wantsJson(request)) return json({ ok: true, status: "pending" });
78
+ /**
79
+ * The Referer: `null` when absent, the URL when it parses and shares the viewer's origin,
80
+ * `"refused"` when it is present but malformed or from another origin.
81
+ */
82
+ function readReferer(request: Request, viewerOrigin: string): URL | null | "refused" {
69
83
  const referer = request.headers.get("referer");
70
- if (referer) {
71
- try {
72
- const back = new URL(referer);
73
- back.searchParams.set("subscribed", "1");
74
- return Response.redirect(back.toString(), 303);
75
- } catch {
76
- /* fall through */
77
- }
84
+ if (!referer) return null;
85
+ try {
86
+ const url = new URL(referer);
87
+ return url.origin === viewerOrigin ? url : "refused";
88
+ } catch {
89
+ return "refused";
90
+ }
91
+ }
92
+
93
+ /** Success response: JSON for fetch, else redirect back to a same-origin referrer with a flag. */
94
+ function ok(request: Request, back: URL | null): Response {
95
+ if (wantsJson(request)) return json({ ok: true, status: "pending" });
96
+ if (back) {
97
+ back.searchParams.set("subscribed", "1");
98
+ return Response.redirect(back.toString(), 303);
78
99
  }
79
100
  return json({ ok: true, status: "pending" });
80
101
  }
@@ -85,6 +106,12 @@ export const POST: APIRoute = async (context) => {
85
106
  if (!tenantId || !collection || !COLLECTION_RE.test(collection)) {
86
107
  return json({ ok: false, error: "not_found" }, 404);
87
108
  }
109
+ // The origin the viewer addressed: on a CloudFront forward, the tenant's host, never this Worker's.
110
+ const viewerOrigin = context.locals?.requestOrigin ?? new URL(context.request.url).origin;
111
+ const referer = readReferer(context.request, viewerOrigin);
112
+ if (referer === "refused") {
113
+ return json({ ok: false, error: "referer_refused" }, 403);
114
+ }
88
115
 
89
116
  try {
90
117
  const email = (await readEmail(context.request))?.trim().toLowerCase() ?? "";
@@ -92,7 +119,15 @@ export const POST: APIRoute = async (context) => {
92
119
  return json({ ok: false, error: "invalid_email" }, 400);
93
120
  }
94
121
 
95
- const salt = (await readEnv("NEWSLETTER_CONSENT_SALT")) ?? DEV_CONSENT_SALT;
122
+ const stage = resolveShopperScope(context.locals)?.stage;
123
+ if (!stage) {
124
+ return json({ ok: false, error: "stage_unknown" }, 409);
125
+ }
126
+ const salt = resolveConsentSalt(await readEnv("NEWSLETTER_CONSENT_SALT"), import.meta.env.DEV === true);
127
+ if (!salt) {
128
+ console.error(`[newsletter] subscribe refused: NEWSLETTER_CONSENT_SALT unset tenant=${tenantId} collection=${collection}`);
129
+ return json({ ok: false, error: "unavailable" }, 503);
130
+ }
96
131
  const ip = await requestClientIp(context.request.headers, await readEnv("CDN_ORIGIN_SECRET"));
97
132
  const consentIpHash = await hashConsentIp(ip, salt);
98
133
  const rateKey = await hashConsentIp(ip, `newsletter-rate:${salt}`);
@@ -115,8 +150,7 @@ export const POST: APIRoute = async (context) => {
115
150
  return json({ ok: false, error: "unavailable" }, 503);
116
151
  }
117
152
 
118
- const referer = context.request.headers.get("referer");
119
- const consentSource = referer ? new URL(referer).pathname : null;
153
+ const consentSource = referer?.pathname ?? null;
120
154
 
121
155
  const store = new NewsletterSubscribersStore(fromD1(d1));
122
156
  const result = await store.subscribe({
@@ -132,10 +166,10 @@ export const POST: APIRoute = async (context) => {
132
166
  // or unsubscribed address. A failed send is an error: the row stays pending, so
133
167
  // the visitor's retry re-sends.
134
168
  if (result.status === "pending") {
135
- const origin = new URL(context.request.url).origin;
136
169
  // The tenant's real routed prefix: a pinned preview's basePath has no API mirror.
137
170
  const apiBasePath = context.locals?.apiBasePath ?? context.locals?.basePath ?? "";
138
- const confirmUrl = `${origin}${apiBasePath}/api/newsletter/confirm?token=${result.token}`;
171
+ const confirmToken = await signConfirmToken(salt, { tenantId, stage, collection, rowToken: result.token });
172
+ const confirmUrl = `${viewerOrigin}${apiBasePath}/api/newsletter/confirm?token=${encodeURIComponent(confirmToken)}`;
139
173
  try {
140
174
  await sendConfirmationEmail({ email, collection, confirmUrl });
141
175
  } catch (err) {
@@ -146,7 +180,7 @@ export const POST: APIRoute = async (context) => {
146
180
  }
147
181
  }
148
182
 
149
- return ok(context.request);
183
+ return ok(context.request, referer);
150
184
  } catch (err) {
151
185
  // Never 500 on a signup, and never report a success that did not happen.
152
186
  console.error(
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tokenoftrust/storefront-runner",
3
- "version": "7.14.3",
3
+ "version": "7.15.1",
4
4
  "license": "SEE LICENSE IN LICENSE",
5
5
  "description": "World-shareable storefront runner: multi-tenant renderer on Astro/Cloudflare. No control plane.",
6
6
  "packageManager": "pnpm@11.9.0",
@@ -1,75 +0,0 @@
1
- /**
2
- * N2 — newsletter double-opt-in confirm. `GET /api/newsletter/confirm?token=…`
3
- * (the link in the confirmation email). Flips the addressed `pending` subscriber
4
- * to `confirmed`; that timestamp + the stored consent source/ip-hash IS the GDPR
5
- * consent record.
6
- *
7
- * The token is opaque + per-subscriber, so it identifies the exact row without
8
- * an email in the URL; the lookup is still scoped to `locals.tenant`. Idempotent:
9
- * re-clicking an already-confirmed link is a success, not an error. An unknown/
10
- * stale token renders a clean "invalid link" page — never a 500.
11
- */
12
- import type { APIRoute } from "astro";
13
- import { readD1 } from "@/lib/publication/shared/env";
14
- import { fromD1 } from "@/lib/catalog/d1/catalog";
15
- import { NewsletterSubscribersStore } from "@/lib/engagement/newsletter/subscribers";
16
-
17
- export const prerender = false;
18
-
19
- function page(title: string, message: string, status = 200): Response {
20
- const esc = (s: string) => s.replace(/[&<>]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;" })[c]!);
21
- const html = `<!doctype html>
22
- <html lang="en">
23
- <head>
24
- <meta charset="utf-8" />
25
- <meta name="viewport" content="width=device-width, initial-scale=1" />
26
- <meta name="robots" content="noindex" />
27
- <title>${esc(title)}</title>
28
- <style>
29
- :root { color-scheme: light dark; }
30
- body { font-family: ui-serif, Georgia, serif; margin: 0; min-height: 100vh;
31
- display: grid; place-items: center; padding: 2rem; text-align: center;
32
- background: #f4f1ea; color: #2f3a34; }
33
- .card { max-width: 30rem; }
34
- h1 { font-size: clamp(1.6rem, 4vw, 2.2rem); margin: 0 0 0.75rem; }
35
- p { color: #5a655e; line-height: 1.6; }
36
- a { color: #2f3a34; font-weight: 600; }
37
- </style>
38
- </head>
39
- <body>
40
- <div class="card">
41
- <h1>${esc(title)}</h1>
42
- <p>${esc(message)}</p>
43
- <p><a href="/">Back to the shop →</a></p>
44
- </div>
45
- </body>
46
- </html>`;
47
- return new Response(html, {
48
- status,
49
- headers: { "content-type": "text/html; charset=utf-8" },
50
- });
51
- }
52
-
53
- export const GET: APIRoute = async (context) => {
54
- const tenantId = context.locals?.tenant?.tenant_id;
55
- const token = context.url.searchParams.get("token")?.trim();
56
- if (!tenantId || !token) {
57
- return page("Invalid link", "That confirmation link isn't valid. Try subscribing again.", 400);
58
- }
59
-
60
- try {
61
- const d1 = await readD1("STOREFRONT_APPS_DB");
62
- if (!d1) {
63
- return page("Try again shortly", "We couldn't confirm your subscription just now. Please try again in a moment.", 503);
64
- }
65
- const store = new NewsletterSubscribersStore(fromD1(d1));
66
- const result = await store.confirmByToken({ tenantId, token });
67
- if (result === "not_found") {
68
- return page("Invalid link", "That confirmation link is expired or already used. Try subscribing again.", 400);
69
- }
70
- // "confirmed" and "already" are both success — idempotent.
71
- return page("You're confirmed.", "Thanks for confirming — you'll hear from us when something worth knowing lands.");
72
- } catch {
73
- return page("Try again shortly", "We couldn't confirm your subscription just now. Please try again in a moment.", 503);
74
- }
75
- };
@@ -1,89 +0,0 @@
1
- /**
2
- * Newsletter one-click unsubscribe (newsletter-send epic, N3) — the endpoint the
3
- * unsubscribe footer link and the RFC 8058 `List-Unsubscribe` header both point at.
4
- * (N4 composes those headers/links; this unit is only the target they hit.)
5
- *
6
- * - GET /api/newsletter/unsubscribe?token=… — a clicked email-footer link. Flips
7
- * the subscriber to `unsubscribed` and renders a plain confirmation page.
8
- * - POST /api/newsletter/unsubscribe?token=… — the RFC 8058 `List-Unsubscribe-Post:
9
- * List-Unsubscribe=One-Click` request a mailbox provider (Gmail/Yahoo) fires. Same
10
- * effect, 200 with no interstitial and no confirmation step.
11
- *
12
- * The `token` (query string only — never the email in the URL) is an opaque per-
13
- * subscriber capability, so this succeeds WITHOUT login in one click. It is idempotent
14
- * (re-unsubscribing is a no-op success) and NON-LEAKING: an unknown token gets the exact
15
- * same response as a real one, so an observer can't probe which tokens exist.
16
- *
17
- * The front door's cross-site form check admits this route's POST (lib/publication/shared/cdnForward.ts
18
- * `MACHINE_POST_ROUTES`), so the mailbox provider's origin-less form POST reaches this handler.
19
- */
20
- import type { APIContext } from "astro";
21
- import { readD1 } from "@/lib/publication/shared/env";
22
- import { fromD1 } from "@/lib/catalog/d1/catalog";
23
- import { unsubscribeByToken } from "@/lib/engagement/newsletter/subscribers";
24
-
25
- export const prerender = false;
26
-
27
- /** Confirmation page for the clicked-link (GET) path. `noindex`; house serif style. */
28
- function confirmationPage(): Response {
29
- const html = `<!doctype html>
30
- <html lang="en">
31
- <head>
32
- <meta charset="utf-8" />
33
- <meta name="viewport" content="width=device-width, initial-scale=1" />
34
- <meta name="robots" content="noindex" />
35
- <title>Unsubscribed</title>
36
- <style>
37
- :root { color-scheme: light dark; }
38
- body { font-family: ui-serif, Georgia, serif; margin: 0; min-height: 100vh;
39
- display: grid; place-items: center; padding: 2rem; text-align: center;
40
- background: #f4f1ea; color: #2f3a34; }
41
- .card { max-width: 30rem; }
42
- h1 { font-size: clamp(1.6rem, 4vw, 2.2rem); margin: 0 0 0.75rem; }
43
- p { color: #5a655e; line-height: 1.6; }
44
- a { color: #2f3a34; font-weight: 600; }
45
- </style>
46
- </head>
47
- <body>
48
- <div class="card">
49
- <h1>You're unsubscribed.</h1>
50
- <p>You won't receive any more of these emails. Changed your mind? You can always sign up again.</p>
51
- <p><a href="/">Back to the shop →</a></p>
52
- </div>
53
- </body>
54
- </html>`;
55
- return new Response(html, {
56
- status: 200,
57
- headers: { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" },
58
- });
59
- }
60
-
61
- /** Apply the unsubscribe for the token in the query string. Best-effort: never throws,
62
- * and returns the same value regardless of whether the token was real (non-leaking).
63
- * When no D1 binding is present (local/dev) it's a silent no-op — the response shape
64
- * is identical either way. */
65
- async function applyUnsubscribe(context: APIContext): Promise<void> {
66
- try {
67
- const token = new URL(context.request.url).searchParams.get("token") ?? "";
68
- const d1 = await readD1("STOREFRONT_APPS_DB");
69
- if (!d1) return;
70
- await unsubscribeByToken(fromD1(d1), token, new Date().toISOString());
71
- } catch {
72
- // Unsubscribe must never error out at the reader — degrade to the same success
73
- // response. (A failed write is preferable to showing a subscriber an error.)
74
- }
75
- }
76
-
77
- export async function GET(context: APIContext): Promise<Response> {
78
- await applyUnsubscribe(context);
79
- return confirmationPage();
80
- }
81
-
82
- export async function POST(context: APIContext): Promise<Response> {
83
- await applyUnsubscribe(context);
84
- // RFC 8058 one-click: a bare 200, no body of consequence, no confirmation step.
85
- return new Response("Unsubscribed", {
86
- status: 200,
87
- headers: { "content-type": "text/plain; charset=utf-8", "cache-control": "no-store" },
88
- });
89
- }