@tokenoftrust/storefront-runner 7.15.0 → 8.0.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/apps/storefront/env.d.ts +4 -0
- package/apps/storefront/src/config/compliance/rulesets.ts +475 -50
- package/apps/storefront/src/lib/checkout/commerce/finalCartAuthorization.ts +6 -0
- package/apps/storefront/src/lib/compliance/enforcement.ts +29 -0
- package/apps/storefront/src/lib/engagement/newsletter/consent.ts +115 -6
- package/apps/storefront/src/lib/engagement/newsletter/subscribers.ts +155 -23
- package/apps/storefront/src/pages/api/commerce/final-cart-authorization.ts +6 -0
- package/apps/storefront/src/pages/api/newsletter/[collection]/subscribe.ts +57 -23
- package/package.json +1 -1
- package/packages/public-runtime/src/compliance/evaluate.ts +600 -126
- package/packages/public-runtime/src/compliance/evidence-signals.ts +3 -1
- package/packages/public-runtime/src/compliance/profile.ts +184 -166
- package/packages/public-runtime/src/compliance/ruleset.ts +743 -78
- package/packages/public-runtime/src/compliance/state-directory.ts +116 -4
- package/packages/public-runtime/src/tenant.ts +1 -1
- package/packages/public-runtime/tests/fixtures/compliance-decisions.golden.json +100 -38
- package/apps/storefront/src/pages/api/newsletter/confirm.ts +0 -75
- package/apps/storefront/src/pages/api/newsletter/unsubscribe.ts +0 -89
|
@@ -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
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
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`
|
|
84
|
-
* is a no-op success
|
|
85
|
-
* `unsubscribed`/`bounced` (the confirm link is no longer valid) — is
|
|
86
|
-
*
|
|
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:
|
|
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
|
-
|
|
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
|
-
|
|
98
|
-
|
|
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
|
-
|
|
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<
|
|
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
|
-
|
|
151
|
-
|
|
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
|
|
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
|
}
|
|
@@ -210,9 +210,15 @@ async function evaluateSeam(context: APIContext, snapshot: CommerceProviderCartS
|
|
|
210
210
|
const flavors = [...new Set(blocks.flatMap(block => block.code === "flavored_prohibited" ? block.flavors ?? [] : []))];
|
|
211
211
|
const hasRuleBlock = blocks.some(
|
|
212
212
|
block =>
|
|
213
|
+
block.code === "invalid_ruleset" ||
|
|
214
|
+
block.code === "postal_code_required" ||
|
|
213
215
|
block.code === "flavored_prohibited" ||
|
|
214
216
|
block.code === "cooling_agent_prohibited" ||
|
|
215
217
|
block.code === "region_prohibited" ||
|
|
218
|
+
block.code === "registry_prohibited" ||
|
|
219
|
+
block.code === "fact_prohibited" ||
|
|
220
|
+
block.code === "pact_requirement_failed" ||
|
|
221
|
+
block.code === "sku_limit_exceeded" ||
|
|
216
222
|
block.code === "purchase_limit_exceeded",
|
|
217
223
|
);
|
|
218
224
|
const titleOf = (sku: string) => products.find(p => p.variants.some(v => v.sku === sku))?.title;
|
|
@@ -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` =
|
|
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
|
|
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 {
|
|
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
|
-
/**
|
|
67
|
-
|
|
68
|
-
|
|
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
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
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
|
|
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
|
|
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
|
|
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": "
|
|
3
|
+
"version": "8.0.0",
|
|
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",
|