@tokenoftrust/storefront-runner 7.13.1 → 7.14.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.
@@ -38,6 +38,7 @@ export const RESERVED_PAGE_ROOTS = Object.freeze([
38
38
  "orders",
39
39
  "preview",
40
40
  "products",
41
+ "quick-order",
41
42
  "saved",
42
43
  "search",
43
44
  "shared",
@@ -32,6 +32,8 @@ import {
32
32
  withShippingPolicy,
33
33
  withReturnUrl,
34
34
  withExcise,
35
+ withAttribution,
36
+ attributionTokenFromCookieHeader,
35
37
  withServedCartImage,
36
38
  trustedCartReturnUrl,
37
39
  tenantPublicOrigin,
@@ -271,7 +273,8 @@ function logCartRefusal(context: APIContext, code: CartDenialCode, failedFields:
271
273
  /**
272
274
  * The server-owned steps one enforced cart line takes before it reaches the cart: the verification
273
275
  * ref the compliance gate produced (none for a proposal), the declared shipping policy, the
274
- * store's excise setting, the page it came from, and the served image. `null` when the declared
276
+ * store's excise setting, the page it came from, the first-party attribution the request's
277
+ * `__tot_attr` cookie carries, and the served image. `null` when the declared
275
278
  * shipping policy cannot be charged in the cart's currency.
276
279
  */
277
280
  export async function completeCartFields(
@@ -291,7 +294,12 @@ export async function completeCartFields(
291
294
  excise: await effectiveExcise(tenant, context.locals.capabilities, context.locals.customizationEnv ?? "test"),
292
295
  });
293
296
  const returned = await withReturnUrl(excised, { mode: commerce.mode, secret, returnUrl: opts.returnUrl });
294
- return withServedCartImage(returned, {
297
+ const attributed = await withAttribution(returned, {
298
+ mode: commerce.mode,
299
+ secret,
300
+ attribution: attributionTokenFromCookieHeader(context.request.headers.get("cookie")),
301
+ });
302
+ return withServedCartImage(attributed, {
295
303
  mode: commerce.mode,
296
304
  secret,
297
305
  canonicalDomain: tenant.canonicalDomain,
@@ -37,6 +37,7 @@ export const INTERNAL_CART_OPTIONS: readonly string[] = [
37
37
  "content_version",
38
38
  "excise",
39
39
  "shopper_checkout",
40
+ "attribution",
40
41
  ];
41
42
 
42
43
  const MANAGED_CART_FORM = "form[data-managed-cart], form[data-tot-cart-form]";
@@ -0,0 +1,65 @@
1
+ /**
2
+ * First-party click capture at the Worker edge.
3
+ *
4
+ * A GET whose query carries any allowlisted affiliate parameter (`ATTRIBUTION_PARAMS`: ref,
5
+ * aff_id, click_id, transaction_id, irclickid, rfsn, a_aid, sub1..sub5) gets an
6
+ * `__tot_attr` cookie on its HTML document response. The front door appends it after any
7
+ * edge-cache read or write, as it does the visitor region cookie, so cached bytes and cache keys
8
+ * stay visitor-invariant and the capture adds no I/O: no binding, no network call, no script.
9
+ *
10
+ * Only exact, lowercase parameter names are read. A parameter given more than once, or whose
11
+ * value fails `ATTRIBUTION_VALUE` (`^[A-Za-z0-9._:-]{1,128}$`, so no CR/LF, `;`, `,`, space or
12
+ * percent-escape survives), is ignored. A serialized token over `ATTRIBUTION_TOKEN_MAX_BYTES`
13
+ * writes nothing. Every other parameter is ignored.
14
+ *
15
+ * Last touch: a request with at least one valid parameter replaces the whole cookie with this
16
+ * click's parameters, never merged with an earlier click's. A request with none leaves the
17
+ * cookie as it is. The cookie lives `ATTRIBUTION_COOKIE_MAX_AGE` (30 days).
18
+ *
19
+ * The cookie is `HttpOnly; Secure; SameSite=Lax; Path=/` with no `Domain`, so it stays on the
20
+ * host that set it. The checkout handoff reads it back and re-validates it
21
+ * (`attributionTokenFromCookieHeader`) before signing it into the cart (`withAttribution`).
22
+ *
23
+ * No cookie is set on the GA4 sandbox frame document, which keeps its origin free of state.
24
+ */
25
+ import {
26
+ ATTRIBUTION_COOKIE,
27
+ ATTRIBUTION_COOKIE_ATTRIBUTES,
28
+ captureAttributionToken,
29
+ parseAttributionToken,
30
+ serializeAttribution,
31
+ } from "@tot/public-runtime";
32
+ import { NATIVE_GA4_SANDBOX_ASSET_URL } from "@tot/public-runtime/integration/native-ga4-sandbox-asset";
33
+
34
+ /** The `Set-Cookie` value for a token, or `null` when `token` is not a valid token. */
35
+ export function attributionSetCookie(token: string): string | null {
36
+ const context = parseAttributionToken(token);
37
+ const canonical = context ? serializeAttribution(context) : null;
38
+ if (!canonical) return null;
39
+ return `${ATTRIBUTION_COOKIE}=${canonical}; ${ATTRIBUTION_COOKIE_ATTRIBUTES}`;
40
+ }
41
+
42
+ /** The token this request captures, or `null` to set none. */
43
+ export function attributionCaptureFor(request: Request): string | null {
44
+ if (request.method !== "GET") return null;
45
+ const url = new URL(request.url);
46
+ if (url.pathname.endsWith(NATIVE_GA4_SANDBOX_ASSET_URL)) return null;
47
+ return captureAttributionToken((key) => url.searchParams.getAll(key));
48
+ }
49
+
50
+ /** Append the attribution cookie to an HTML document response; any other response is returned as is. */
51
+ export function withAttributionCookie(response: Response, token: string | null): Response {
52
+ if (!token) return response;
53
+ if (!(response.headers.get("content-type") ?? "").toLowerCase().includes("text/html")) return response;
54
+ const cookie = attributionSetCookie(token);
55
+ if (!cookie) return response;
56
+ try {
57
+ response.headers.append("set-cookie", cookie);
58
+ return response;
59
+ } catch {
60
+ // Immutable headers (a fetched or platform response): copy, then append.
61
+ const copy = new Response(response.body, response);
62
+ copy.headers.append("set-cookie", cookie);
63
+ return copy;
64
+ }
65
+ }
@@ -33,6 +33,7 @@ import type { RenditionRegistryBucket } from "@/lib/assets/registeredRenditions"
33
33
  import { DEV_DRAFT_COOKIE } from "@/lib/developer-experience/dev/devDraft";
34
34
  import { applySecurityHeaders } from "@/lib/access/shared/securityHeaders";
35
35
  import { visitorRegionFor, withVisitorRegionCookie } from "@/lib/compliance/shared/visitorRegionCookie";
36
+ import { attributionCaptureFor, withAttributionCookie } from "./edgeAttribution.js";
36
37
  import { tryServeStaticBundle } from "./staticBundle.js";
37
38
  import { resolveCandidateContentPin } from "./candidatePin.js";
38
39
  import { resolveRequestPreviewContext } from "./previewContext.js";
@@ -87,8 +88,9 @@ function routeTierIndexFor(tenant: TenantConfig): RouteTierIndexV1 {
87
88
  }
88
89
 
89
90
  /**
90
- * Every HTML document leaves with the visitor's region class (lib/compliance/shared/visitorRegionCookie),
91
- * appended after the branch has read or written any edge cache.
91
+ * Every HTML document leaves with the visitor's region class (lib/compliance/shared/visitorRegionCookie)
92
+ * and, when its query carries an allowlisted affiliate parameter, the first-party attribution
93
+ * cookie (./edgeAttribution), both appended after the branch has read or written any edge cache.
92
94
  */
93
95
  export const onRequest = defineMiddleware(async (context, next) => {
94
96
  // An in-process rewrite re-enters this middleware with the same locals; the outer pass owns
@@ -110,10 +112,11 @@ export const onRequest = defineMiddleware(async (context, next) => {
110
112
  : served;
111
113
  const { scopePreviewPinnedImageUrls } = await import("@/lib/assets/preview-pinned-image-urls");
112
114
  const scoped = await scopePreviewPinnedImageUrls(response, context.locals.apiBasePath ?? seen.assetBasePath ?? "");
113
- const finished = withVisitorRegionCookie(
115
+ const regioned = withVisitorRegionCookie(
114
116
  scoped,
115
117
  visitorRegionFor(context.request, { cdnForwarded: seen.cdnForwarded, dev: import.meta.env.DEV }),
116
118
  );
119
+ const finished = outer ? withAttributionCookie(regioned, attributionCaptureFor(context.request)) : regioned;
117
120
  if (seen.privateCatalog) {
118
121
  finished.headers.set("cache-control", "private, no-store");
119
122
  finished.headers.set("x-robots-tag", "noindex, nofollow");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tokenoftrust/storefront-runner",
3
- "version": "7.13.1",
3
+ "version": "7.14.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",
@@ -25,6 +25,15 @@ import type {
25
25
  SubscriptionPurchaseOption,
26
26
  } from "./product.js";
27
27
  import { resolveStoreCurrency } from "./declared-tenant-config.mjs";
28
+ import {
29
+ ATTRIBUTION_COOKIE,
30
+ ATTRIBUTION_COOKIE_ATTRIBUTES,
31
+ ATTRIBUTION_COOKIE_MAX_AGE,
32
+ ATTRIBUTION_PARAMS,
33
+ ATTRIBUTION_TOKEN_MAX_BYTES,
34
+ ATTRIBUTION_VALUE,
35
+ captureAttributionToken,
36
+ } from "./integration/attribution-capture.mjs";
28
37
  import { DEFAULT_ONE_TIME_PURCHASE_OPTION } from "./product.js";
29
38
  import type { ShippingPolicy, TenantConfig } from "./tenant.js";
30
39
  import { isContentVersionId } from "./checkout-orders.js";
@@ -332,9 +341,10 @@ export class CartSigningUnavailableError extends Error {
332
341
  * store's declared shipping charge (`withShippingPolicy`). `return_url` carries the page the
333
342
  * shopper submitted from (`withReturnUrl`). `content_version` carries the candidate
334
343
  * content pin the page rendered, and only then. `excise` carries the store's excise setting
335
- * (`withExcise`), `on` or `off`.
344
+ * (`withExcise`), `on` or `off`. `attribution` carries the shopper's first-party click
345
+ * attribution token (`withAttribution`) when the request presented a valid one.
336
346
  */
337
- export const INTERNAL_CART_FIELDS = ["currency", "tenant", "verification", "shipping_policy", "return_url", "content_version", "excise", "shopper_checkout"] as const;
347
+ export const INTERNAL_CART_FIELDS = ["currency", "tenant", "verification", "shipping_policy", "return_url", "content_version", "excise", "shopper_checkout", "attribution"] as const;
338
348
 
339
349
  /** Signed cart option naming the content version the preview page rendered. */
340
350
  export const CONTENT_VERSION_CART_FIELD = "content_version";
@@ -1222,6 +1232,135 @@ export async function withReturnUrl(
1222
1232
  return [...kept, await signField(opts.secret, code, field)];
1223
1233
  }
1224
1234
 
1235
+ /**
1236
+ * First-party click attribution.
1237
+ *
1238
+ * The edge captures a fixed allowlist of affiliate query parameters into the HttpOnly
1239
+ * {@link ATTRIBUTION_COOKIE}; the checkout handoff reads that cookie back, re-validates it, and
1240
+ * signs it into the cart as the one internal {@link ATTRIBUTION_CART_FIELD} option. Every key
1241
+ * lives inside that option's value, so no attribution key can stand in for a native or internal
1242
+ * cart field. A token is `key=value` pairs joined by `&`, keys in {@link ATTRIBUTION_PARAMS}
1243
+ * order, each value an opaque id matching {@link ATTRIBUTION_VALUE}, the whole at most
1244
+ * {@link ATTRIBUTION_TOKEN_MAX_BYTES}. Anything else is not a token: no partial token is kept.
1245
+ */
1246
+ export const ATTRIBUTION_CART_FIELD = "attribution";
1247
+
1248
+ export {
1249
+ ATTRIBUTION_COOKIE,
1250
+ ATTRIBUTION_COOKIE_ATTRIBUTES,
1251
+ ATTRIBUTION_COOKIE_MAX_AGE,
1252
+ ATTRIBUTION_PARAMS,
1253
+ ATTRIBUTION_TOKEN_MAX_BYTES,
1254
+ ATTRIBUTION_VALUE,
1255
+ captureAttributionToken,
1256
+ };
1257
+ export type AttributionParam = (typeof ATTRIBUTION_PARAMS)[number];
1258
+
1259
+ export type AttributionContext = Partial<Record<AttributionParam, string>>;
1260
+
1261
+ /**
1262
+ * Names a signed cart reserves: native item parameters, internal options, cart-level selectors,
1263
+ * and everything an assistant proposal may never carry (price, tax, excise, identity, …).
1264
+ */
1265
+ const RESERVED_CART_KEYS: ReadonlySet<string> = new Set(
1266
+ [
1267
+ ...NATIVE_CART_FIELDS, ...INTERNAL_CART_FIELDS, ...CART_PROPOSAL_FORBIDDEN_FIELDS, ...CART_LEVEL_PARAMS,
1268
+ "coupon", "tax", "excise", "jurisdiction", "warning", "identity", "quantity", "code",
1269
+ ].map((name) => name.toLowerCase()),
1270
+ );
1271
+
1272
+ /**
1273
+ * True when `key` names, or would be read as, a reserved signed-cart field: a native or internal
1274
+ * field, a protected commerce name, an unsigned `h:`/`x:`/`__`/`utm_` prefix, or a `||` suffix.
1275
+ */
1276
+ export function reservedCartKey(key: string): boolean {
1277
+ const lower = key.trim().toLowerCase();
1278
+ return RESERVED_CART_KEYS.has(lower) || lower.includes("||") ||
1279
+ UNSIGNED_PREFIXES.some((prefix) => lower.startsWith(prefix));
1280
+ }
1281
+
1282
+ function isAttributionParam(key: string): key is AttributionParam {
1283
+ return (ATTRIBUTION_PARAMS as readonly string[]).includes(key) && !reservedCartKey(key);
1284
+ }
1285
+
1286
+ function utf8Length(value: string): number {
1287
+ return new TextEncoder().encode(value).length;
1288
+ }
1289
+
1290
+ /** The canonical token for `context`, or `null` when it is empty, invalid or over the byte cap. */
1291
+ export function serializeAttribution(context: AttributionContext): string | null {
1292
+ const parts: string[] = [];
1293
+ for (const key of ATTRIBUTION_PARAMS) {
1294
+ if (!Object.hasOwn(context, key)) continue;
1295
+ const value = context[key];
1296
+ if (typeof value !== "string" || !ATTRIBUTION_VALUE.test(value) || !isAttributionParam(key)) return null;
1297
+ parts.push(`${key}=${value}`);
1298
+ }
1299
+ if (parts.length === 0) return null;
1300
+ const token = parts.join("&");
1301
+ return utf8Length(token) <= ATTRIBUTION_TOKEN_MAX_BYTES ? token : null;
1302
+ }
1303
+
1304
+ /**
1305
+ * A token parsed strictly, or `null`. An unknown or reserved key, a repeated key, a malformed pair
1306
+ * or value, or a token over the byte cap discards the whole token.
1307
+ */
1308
+ export function parseAttributionToken(raw: string | null | undefined): AttributionContext | null {
1309
+ if (typeof raw !== "string" || raw.length === 0 || utf8Length(raw) > ATTRIBUTION_TOKEN_MAX_BYTES) return null;
1310
+ const context: AttributionContext = {};
1311
+ for (const pair of raw.split("&")) {
1312
+ const eq = pair.indexOf("=");
1313
+ if (eq <= 0) return null;
1314
+ const key = pair.slice(0, eq);
1315
+ const value = pair.slice(eq + 1);
1316
+ if (!isAttributionParam(key) || Object.hasOwn(context, key) || !ATTRIBUTION_VALUE.test(value)) return null;
1317
+ context[key] = value;
1318
+ }
1319
+ return context;
1320
+ }
1321
+
1322
+ /**
1323
+ * The canonical attribution token a request's `Cookie` header carries, or `null`. Exactly one
1324
+ * {@link ATTRIBUTION_COOKIE} must be present: two (one tossed from a sibling host, say) are
1325
+ * ambiguous and both are discarded, as is any value that does not parse as a token.
1326
+ */
1327
+ export function attributionTokenFromCookieHeader(header: string | null | undefined): string | null {
1328
+ if (!header) return null;
1329
+ const values: string[] = [];
1330
+ for (const pair of header.split(";")) {
1331
+ const eq = pair.indexOf("=");
1332
+ if (eq === -1 || pair.slice(0, eq).trim() !== ATTRIBUTION_COOKIE) continue;
1333
+ values.push(pair.slice(eq + 1).trim());
1334
+ }
1335
+ if (values.length !== 1) return null;
1336
+ const context = parseAttributionToken(values[0]);
1337
+ return context ? serializeAttribution(context) : null;
1338
+ }
1339
+
1340
+ /**
1341
+ * Bind the shopper's attribution token into an enforced cart as the internal `attribution` option,
1342
+ * signed against the cart's product code. Any `attribution` the shopper submitted is dropped first,
1343
+ * so only the server-read cookie reaches the cart. The token is re-validated here; an invalid one,
1344
+ * or a cart with no product code, leaves the cart exactly as it was without one.
1345
+ */
1346
+ export async function withAttribution(
1347
+ fields: readonly CartSubmissionField[],
1348
+ opts: { mode: ManagedCheckoutConfig["mode"]; secret?: string; attribution: string | null },
1349
+ ): Promise<CartSubmissionField[]> {
1350
+ const kept = fields.filter(
1351
+ (field) => (field.name.split("||")[0] ?? "").trim().toLowerCase() !== ATTRIBUTION_CART_FIELD,
1352
+ );
1353
+ const context = parseAttributionToken(opts.attribution);
1354
+ const token = context ? serializeAttribution(context) : null;
1355
+ if (!token) return kept;
1356
+ const code = kept.find((field) => field.name.split("||")[0] === "code")?.value;
1357
+ if (!code) return kept;
1358
+ const field: CartField = { name: ATTRIBUTION_CART_FIELD, value: token };
1359
+ if (opts.mode !== "signed") return [...kept, unsignedField(field)];
1360
+ if (!opts.secret) throw new CartSigningUnavailableError();
1361
+ return [...kept, await signField(opts.secret, code, field)];
1362
+ }
1363
+
1225
1364
  const CAPTURED_CART_ASSET_PATH = /^\/_a\/[0-9a-f]{64}(?:\.[A-Za-z0-9]+)?$/;
1226
1365
 
1227
1366
  /**
@@ -0,0 +1,10 @@
1
+ export const ATTRIBUTION_COOKIE: "__tot_attr";
2
+ export const ATTRIBUTION_COOKIE_MAX_AGE: 2592000;
3
+ export const ATTRIBUTION_COOKIE_ATTRIBUTES: string;
4
+ export const ATTRIBUTION_PARAMS: readonly [
5
+ "ref", "aff_id", "click_id", "transaction_id", "irclickid", "rfsn", "a_aid",
6
+ "sub1", "sub2", "sub3", "sub4", "sub5",
7
+ ];
8
+ export const ATTRIBUTION_VALUE: RegExp;
9
+ export const ATTRIBUTION_TOKEN_MAX_BYTES: 512;
10
+ export function captureAttributionToken(valuesOf: (key: string) => readonly string[]): string | null;
@@ -0,0 +1,54 @@
1
+ // @ts-check
2
+ /**
3
+ * The edge capture of first-party click attribution: the wire constants and the one pure capture
4
+ * rule both CDNs run. The Worker front door calls it with `URLSearchParams.getAll`; the CloudFront
5
+ * viewer-response function (`scripts/publish/cloudfront/csp-meta-emit.mjs`) serializes it with
6
+ * `Function.toString()` and calls it over the viewer request's query string, so the rule proven by
7
+ * tests is byte-identically the rule at each edge. Written for CloudFront Functions' runtime: no
8
+ * imports inside the function body, no `TextEncoder`, no regex flags it lacks.
9
+ *
10
+ * A request carrying any allowlisted parameter, given exactly once with a value matching
11
+ * {@link ATTRIBUTION_VALUE}, captures every such parameter as one token: `key=value` pairs joined by
12
+ * `&` in {@link ATTRIBUTION_PARAMS} order. Values are ASCII by construction, so the token's length is
13
+ * its UTF-8 byte length; a token over {@link ATTRIBUTION_TOKEN_MAX_BYTES} captures nothing.
14
+ */
15
+
16
+ /** First-party, per-host cookie holding the last captured attribution token. */
17
+ export const ATTRIBUTION_COOKIE = "__tot_attr";
18
+
19
+ /** Seconds a captured attribution lives in the browser: 30 days. */
20
+ export const ATTRIBUTION_COOKIE_MAX_AGE = 2592000;
21
+
22
+ /** The cookie's attributes on both CDNs: host-only, script-unreadable, first-party navigations only. */
23
+ export const ATTRIBUTION_COOKIE_ATTRIBUTES = "Path=/; Max-Age=" + ATTRIBUTION_COOKIE_MAX_AGE + "; HttpOnly; Secure; SameSite=Lax";
24
+
25
+ /** The only query parameters attribution reads, in token order. */
26
+ export const ATTRIBUTION_PARAMS = /** @type {const} */ ([
27
+ "ref", "aff_id", "click_id", "transaction_id", "irclickid", "rfsn", "a_aid",
28
+ "sub1", "sub2", "sub3", "sub4", "sub5",
29
+ ]);
30
+
31
+ /** An attribution value: an opaque id, never free text. */
32
+ export const ATTRIBUTION_VALUE = /^[A-Za-z0-9._:-]{1,128}$/;
33
+
34
+ /** Upper bound, in UTF-8 bytes, of a serialized attribution token. */
35
+ export const ATTRIBUTION_TOKEN_MAX_BYTES = 512;
36
+
37
+ /**
38
+ * The token a request captures, or `null`. `valuesOf(key)` returns every decoded value the request's
39
+ * query gives `key` (an empty array when absent). Keys are exact and lowercase.
40
+ * @param {(key: string) => readonly string[]} valuesOf
41
+ * @returns {string | null}
42
+ */
43
+ export function captureAttributionToken(valuesOf) {
44
+ var parts = [];
45
+ for (var i = 0; i < ATTRIBUTION_PARAMS.length; i++) {
46
+ var key = ATTRIBUTION_PARAMS[i];
47
+ var values = valuesOf(key);
48
+ if (!values || values.length !== 1 || typeof values[0] !== "string" || !ATTRIBUTION_VALUE.test(values[0])) continue;
49
+ parts.push(key + "=" + values[0]);
50
+ }
51
+ if (parts.length === 0) return null;
52
+ var token = parts.join("&");
53
+ return token.length <= ATTRIBUTION_TOKEN_MAX_BYTES ? token : null;
54
+ }