@tokenoftrust/storefront-runner 7.2.7 → 7.3.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/src/lib/checkout/commerce/cartSession.ts +184 -8
- package/apps/storefront/src/lib/checkout/commerce/checkoutHandoffRoute.ts +13 -10
- package/apps/storefront/src/lib/checkout/shared/cartState.ts +4 -3
- package/apps/storefront/src/lib/publication/shared/previewReload.ts +126 -1
- package/apps/storefront/src/middleware/renderChain.ts +2 -0
- package/package.json +1 -1
- package/packages/public-runtime/src/checkout.ts +14 -0
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { APIContext } from "astro";
|
|
2
|
+
import { INTERNAL_CART_FIELDS } from "@tot/public-runtime";
|
|
2
3
|
|
|
3
4
|
/**
|
|
4
5
|
* Per-tenant cart session on a shared Foxy store.
|
|
@@ -114,11 +115,31 @@ export function cartAcceptsTenant(body: unknown, tenantId: string): boolean {
|
|
|
114
115
|
|
|
115
116
|
type CartRead = { status: "cart"; body: unknown } | { status: "unreadable"; reason: string };
|
|
116
117
|
|
|
117
|
-
/** A cart
|
|
118
|
+
/** A cart field as Foxy receives it: `name` may carry `||hash[||open]`. */
|
|
119
|
+
export interface CartLineField {
|
|
120
|
+
name: string;
|
|
121
|
+
value: string;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** One cart line's fields before signing, for its product `code`. */
|
|
125
|
+
export interface CarriedCartLine {
|
|
126
|
+
code: string;
|
|
127
|
+
fields: Array<{ name: string; value: string; open?: boolean }>;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** Signs one carried line's fields for its product code. */
|
|
131
|
+
export type CartLineSigner = (line: CarriedCartLine) => Promise<CartLineField[]>;
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* A cart Foxy returned, or a read that failed. A failure is not an empty cart. `fields` are
|
|
135
|
+
* cart fields sent with the read, so a read without `fcsid` that carries them opens a new
|
|
136
|
+
* session holding those lines.
|
|
137
|
+
*/
|
|
118
138
|
async function readFoxyCart(
|
|
119
139
|
cartUrl: string,
|
|
120
140
|
fcsid: string | null,
|
|
121
141
|
fetchImpl: typeof fetch,
|
|
142
|
+
fields: readonly CartLineField[] = [],
|
|
122
143
|
): Promise<CartRead> {
|
|
123
144
|
let url: URL;
|
|
124
145
|
try {
|
|
@@ -126,6 +147,7 @@ async function readFoxyCart(
|
|
|
126
147
|
} catch (error) {
|
|
127
148
|
return { status: "unreadable", reason: error instanceof Error ? error.name : "Error" };
|
|
128
149
|
}
|
|
150
|
+
for (const field of fields) url.searchParams.append(field.name, field.value);
|
|
129
151
|
url.searchParams.set("output", "json");
|
|
130
152
|
if (fcsid) url.searchParams.set("fcsid", fcsid);
|
|
131
153
|
try {
|
|
@@ -176,6 +198,166 @@ export async function resolveTenantCartSession(input: {
|
|
|
176
198
|
return null;
|
|
177
199
|
}
|
|
178
200
|
|
|
201
|
+
function itemsOf(body: unknown): unknown[] {
|
|
202
|
+
const items = body && typeof body === "object" ? (body as { items?: unknown }).items : null;
|
|
203
|
+
return Array.isArray(items) ? items : [];
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
function cartErrors(body: unknown): number {
|
|
207
|
+
const messages = body && typeof body === "object" ? (body as { messages?: unknown }).messages : null;
|
|
208
|
+
const errors = messages && typeof messages === "object" ? (messages as { errors?: unknown }).errors : null;
|
|
209
|
+
return Array.isArray(errors) ? errors.length : 0;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
const COUPON_CODE = /^[A-Za-z0-9_-]{1,64}$/;
|
|
213
|
+
|
|
214
|
+
/** Coupon codes a cart holds, whether Foxy keys them by code or lists them. */
|
|
215
|
+
export function cartCouponCodes(body: unknown): string[] {
|
|
216
|
+
const coupons = body && typeof body === "object" ? (body as { coupons?: unknown }).coupons : null;
|
|
217
|
+
const codeOf = (coupon: unknown, key?: string): unknown =>
|
|
218
|
+
coupon && typeof coupon === "object" && typeof (coupon as { code?: unknown }).code === "string"
|
|
219
|
+
? (coupon as { code: string }).code
|
|
220
|
+
: key ?? coupon;
|
|
221
|
+
const codes = Array.isArray(coupons)
|
|
222
|
+
? coupons.map((coupon) => codeOf(coupon))
|
|
223
|
+
: coupons && typeof coupons === "object"
|
|
224
|
+
? Object.entries(coupons as Record<string, unknown>).map(([key, coupon]) => codeOf(coupon, key))
|
|
225
|
+
: [];
|
|
226
|
+
return [...new Set(codes.filter((code): code is string => typeof code === "string" && COUPON_CODE.test(code)))];
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
function wholeQuantity(value: unknown): number {
|
|
230
|
+
const n = typeof value === "number" ? value : Number(value);
|
|
231
|
+
return Number.isInteger(n) && n > 0 ? n : 0;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
function totalQuantity(body: unknown): number {
|
|
235
|
+
return itemsOf(body).reduce<number>((sum, item) => sum + wholeQuantity((item as { quantity?: unknown }).quantity), 0);
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
function text(value: unknown): string | null {
|
|
239
|
+
return typeof value === "string" && value.length > 0 ? value : null;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/**
|
|
243
|
+
* The fields that re-create one line Foxy echoed. An internal option is named by its `class`
|
|
244
|
+
* (FC.json spells `return_url` as "return url" for display); any other option keeps its echoed
|
|
245
|
+
* name. Measured 2026-11-17: the rebuilt fields of a signed add equal the submitted ones. A line
|
|
246
|
+
* this cannot rebuild (no code or name, a subscription) is null.
|
|
247
|
+
*/
|
|
248
|
+
export function carriedCartLine(item: unknown): CarriedCartLine | null {
|
|
249
|
+
if (!item || typeof item !== "object") return null;
|
|
250
|
+
const line = item as Record<string, unknown>;
|
|
251
|
+
const code = text(line.code);
|
|
252
|
+
const name = text(line.name);
|
|
253
|
+
const price = Number(line.base_price ?? line.price);
|
|
254
|
+
const quantity = wholeQuantity(line.quantity);
|
|
255
|
+
if (!code || !name || !Number.isFinite(price) || !quantity || text(line.sub_frequency)) return null;
|
|
256
|
+
const fields: CarriedCartLine["fields"] = [
|
|
257
|
+
{ name: "name", value: name },
|
|
258
|
+
{ name: "price", value: price.toFixed(2) },
|
|
259
|
+
{ name: "code", value: code },
|
|
260
|
+
{ name: "quantity", value: String(quantity), open: true },
|
|
261
|
+
];
|
|
262
|
+
const image = text(line.image);
|
|
263
|
+
if (image) fields.push({ name: "image", value: image });
|
|
264
|
+
const options = Array.isArray(line.options) ? line.options : [];
|
|
265
|
+
for (const option of options) {
|
|
266
|
+
if (!option || typeof option !== "object") return null;
|
|
267
|
+
const { name: shown, class: key, value } = option as { name?: unknown; class?: unknown; value?: unknown };
|
|
268
|
+
const internal = typeof key === "string" && (INTERNAL_CART_FIELDS as readonly string[]).includes(key) ? key : null;
|
|
269
|
+
const optionName = internal ?? text(shown);
|
|
270
|
+
if (!optionName || typeof value !== "string") return null;
|
|
271
|
+
fields.push({ name: optionName, value });
|
|
272
|
+
}
|
|
273
|
+
return { code, fields };
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/**
|
|
277
|
+
* Add one signed line to this tenant's cart and return the session that holds it.
|
|
278
|
+
*
|
|
279
|
+
* The add is sent with no `fcsid`, so Foxy opens a new session. This tenant's lines from the
|
|
280
|
+
* stored session ride along, re-signed from what Foxy echoes and numbered `1:`…`n:`, with the
|
|
281
|
+
* new line last, and so do its coupon codes. Each line keeps its internal options (tenant,
|
|
282
|
+
* verification, excise, shipping policy). Foxy
|
|
283
|
+
* does not add into an existing session (measured 2026-11-17 on the shared preview store: the
|
|
284
|
+
* add answers with no error and the count unchanged), so carrying is how a second add lands.
|
|
285
|
+
* The new session must answer with no error, a sane id, only this tenant's lines, and the
|
|
286
|
+
* quantity it held before plus the quantity added. Otherwise null, and no session is stored.
|
|
287
|
+
*/
|
|
288
|
+
export async function addToTenantCart(input: {
|
|
289
|
+
cartUrl: string;
|
|
290
|
+
tenantId: string;
|
|
291
|
+
existing: string | null;
|
|
292
|
+
add: readonly CartLineField[];
|
|
293
|
+
sign: CartLineSigner;
|
|
294
|
+
fetch?: typeof fetch;
|
|
295
|
+
}): Promise<string | null> {
|
|
296
|
+
if (!input.tenantId) return null;
|
|
297
|
+
const fetchImpl = input.fetch ?? fetch;
|
|
298
|
+
const add = input.add.filter((field) => !["fcsid", "output", "coupon"].includes(field.name.split("||")[0] ?? ""));
|
|
299
|
+
const addedQuantity = wholeQuantity(add.find((field) => field.name.split("||")[0] === "quantity")?.value ?? "1");
|
|
300
|
+
if (!addedQuantity) return null;
|
|
301
|
+
let carried: CarriedCartLine[] = [];
|
|
302
|
+
let coupons: string[] = [];
|
|
303
|
+
const existing = saneSessionId(input.existing) ? input.existing : null;
|
|
304
|
+
if (existing) {
|
|
305
|
+
const read = await readFoxyCart(input.cartUrl, existing, fetchImpl);
|
|
306
|
+
if (read.status === "unreadable") return null;
|
|
307
|
+
if (sessionIdOf(read.body) === existing && cartAcceptsTenant(read.body, input.tenantId)) {
|
|
308
|
+
const lines = itemsOf(read.body).map(carriedCartLine);
|
|
309
|
+
if (lines.some((line) => line === null)) return null;
|
|
310
|
+
carried = lines as CarriedCartLine[];
|
|
311
|
+
coupons = cartCouponCodes(read.body);
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
const fields: CartLineField[] = [];
|
|
315
|
+
for (const [index, line] of carried.entries()) {
|
|
316
|
+
for (const field of await input.sign(line)) fields.push({ name: `${index + 1}:${field.name}`, value: field.value });
|
|
317
|
+
}
|
|
318
|
+
const prefix = carried.length ? `${carried.length + 1}:` : "";
|
|
319
|
+
for (const field of add) fields.push({ name: `${prefix}${field.name}`, value: field.value });
|
|
320
|
+
for (const code of coupons) fields.push({ name: "coupon", value: code });
|
|
321
|
+
const before = carried.reduce((sum, line) => sum + wholeQuantity(line.fields.find((f) => f.name === "quantity")?.value), 0);
|
|
322
|
+
const opened = await readFoxyCart(input.cartUrl, null, fetchImpl, fields);
|
|
323
|
+
if (opened.status !== "cart" || cartErrors(opened.body) > 0) return null;
|
|
324
|
+
const id = sessionIdOf(opened.body);
|
|
325
|
+
if (!id || id === existing || !cartAcceptsTenant(opened.body, input.tenantId)) return null;
|
|
326
|
+
if (totalQuantity(opened.body) !== before + addedQuantity) return null;
|
|
327
|
+
return id;
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
function storeCartSession(context: CartSessionBinding, id: string): void {
|
|
331
|
+
context.cookies.set(CART_SESSION_COOKIE, id, {
|
|
332
|
+
httpOnly: true,
|
|
333
|
+
secure: true,
|
|
334
|
+
sameSite: "lax",
|
|
335
|
+
path: cartSessionCookiePath(context.locals.apiBasePath ?? context.locals.basePath ?? ""),
|
|
336
|
+
maxAge: CART_SESSION_MAX_AGE,
|
|
337
|
+
});
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
/** Add one signed line to the tenant's cart, and store the session that holds it. */
|
|
341
|
+
export async function addToBoundCart(
|
|
342
|
+
context: CartSessionBinding,
|
|
343
|
+
commerce: { cartUrl: string },
|
|
344
|
+
tenantId: string,
|
|
345
|
+
add: readonly CartLineField[],
|
|
346
|
+
sign: CartLineSigner,
|
|
347
|
+
fetchImpl?: typeof fetch,
|
|
348
|
+
): Promise<string | null> {
|
|
349
|
+
const id = await addToTenantCart({
|
|
350
|
+
cartUrl: commerce.cartUrl,
|
|
351
|
+
tenantId,
|
|
352
|
+
existing: context.cookies.get(CART_SESSION_COOKIE)?.value ?? null,
|
|
353
|
+
add,
|
|
354
|
+
sign,
|
|
355
|
+
fetch: fetchImpl,
|
|
356
|
+
});
|
|
357
|
+
if (id) storeCartSession(context, id);
|
|
358
|
+
return id;
|
|
359
|
+
}
|
|
360
|
+
|
|
179
361
|
/** Read the tenant cookie, resolve a Foxy session, and store the id when one is usable. */
|
|
180
362
|
export async function bindCartSession(
|
|
181
363
|
context: CartSessionBinding,
|
|
@@ -190,12 +372,6 @@ export async function bindCartSession(
|
|
|
190
372
|
fetch: fetchImpl,
|
|
191
373
|
});
|
|
192
374
|
if (!id) return null;
|
|
193
|
-
context
|
|
194
|
-
httpOnly: true,
|
|
195
|
-
secure: true,
|
|
196
|
-
sameSite: "lax",
|
|
197
|
-
path: cartSessionCookiePath(context.locals.apiBasePath ?? context.locals.basePath ?? ""),
|
|
198
|
-
maxAge: CART_SESSION_MAX_AGE,
|
|
199
|
-
});
|
|
375
|
+
storeCartSession(context, id);
|
|
200
376
|
return id;
|
|
201
377
|
}
|
|
@@ -20,7 +20,7 @@
|
|
|
20
20
|
import type { APIContext } from "astro";
|
|
21
21
|
import {
|
|
22
22
|
enforceCartSubmission,
|
|
23
|
-
|
|
23
|
+
signCartLine,
|
|
24
24
|
parseConsentSnapshot,
|
|
25
25
|
defaultConsentSnapshot,
|
|
26
26
|
buildVariantCartPayload,
|
|
@@ -45,7 +45,7 @@ import {
|
|
|
45
45
|
type ResolvedManagedCheckout,
|
|
46
46
|
} from "@tot/public-runtime";
|
|
47
47
|
import { resolveCheckoutHandoffCorrelation } from "@/lib/checkout/commerce/checkoutHandoffCorrelation";
|
|
48
|
-
import {
|
|
48
|
+
import { addToBoundCart, CART_UNAVAILABLE_MESSAGE, withCartSession } from "@/lib/checkout/commerce/cartSession";
|
|
49
49
|
import { resolveCartSigning, shopperCartDenialMessage } from "@/lib/checkout/shared/checkoutCommerce";
|
|
50
50
|
import { effectiveExcise } from "@/lib/checkout/commerce/checkoutExcise";
|
|
51
51
|
import { fromD1 } from "@/lib/catalog/d1/catalog";
|
|
@@ -119,17 +119,20 @@ async function boundShippingPolicy(
|
|
|
119
119
|
}
|
|
120
120
|
}
|
|
121
121
|
|
|
122
|
-
/**
|
|
122
|
+
/**
|
|
123
|
+
* Add the enforced line to this tenant's Foxy cart from the server, and return the cart view of
|
|
124
|
+
* the session that holds it. The location carries no cart fields, so following it adds nothing.
|
|
125
|
+
*/
|
|
123
126
|
async function sessionedCartLocation(
|
|
124
127
|
context: APIContext,
|
|
125
128
|
commerce: ResolvedManagedCheckout,
|
|
126
129
|
tenant: TenantConfig,
|
|
127
130
|
fields: readonly CartSubmissionField[],
|
|
131
|
+
secret: string | undefined,
|
|
128
132
|
): Promise<string | null> {
|
|
129
|
-
const fcsid = await
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
return foxyCartRedirectUrl(withCartSession(commerce.cartUrl, fcsid), kept);
|
|
133
|
+
const fcsid = await addToBoundCart(context, commerce, commerceTenantId(tenant), fields,
|
|
134
|
+
(line) => signCartLine(line.fields, { mode: commerce.mode, secret, code: line.code }));
|
|
135
|
+
return fcsid ? withCartSession(commerce.cartUrl, fcsid) : null;
|
|
133
136
|
}
|
|
134
137
|
|
|
135
138
|
function ledgerStage(env: string | undefined): "preview" | "publication" | null {
|
|
@@ -250,9 +253,9 @@ async function cartFormPost(context: APIContext): Promise<Response> {
|
|
|
250
253
|
basePath: context.locals.imageBasePath || context.locals.apiBasePath || context.locals.basePath,
|
|
251
254
|
}),
|
|
252
255
|
});
|
|
253
|
-
const location = await sessionedCartLocation(context, commerce, tenant, imaged);
|
|
256
|
+
const location = await sessionedCartLocation(context, commerce, tenant, imaged, signing.secret);
|
|
254
257
|
if (!location) return cartDenial("signing-unavailable", CART_UNAVAILABLE_MESSAGE, 503);
|
|
255
|
-
// The page
|
|
258
|
+
// The page reads the cart that now holds the line (cartState.ts) and asks for its URL as data.
|
|
256
259
|
if ((context.request.headers.get("accept") ?? "").includes("application/json")) {
|
|
257
260
|
return new Response(JSON.stringify({ location }), {
|
|
258
261
|
status: 200,
|
|
@@ -377,7 +380,7 @@ export async function sampleCartGet(
|
|
|
377
380
|
if (!result.ok) return invalid();
|
|
378
381
|
const shipped = await boundShippingPolicy(result.fields, tenant, "signed", signing.secret);
|
|
379
382
|
if (!shipped) return sampleResponse('{"error":"shipping_unavailable"}', 409);
|
|
380
|
-
const location = await sessionedCartLocation(context, commerce, tenant, shipped);
|
|
383
|
+
const location = await sessionedCartLocation(context, commerce, tenant, shipped, signing.secret);
|
|
381
384
|
if (!location) return sampleResponse('{"error":"cart_unavailable"}', 503);
|
|
382
385
|
return sampleResponse(null, 303, location);
|
|
383
386
|
} catch { return sampleResponse('{"error":"sample_unavailable"}', 503); }
|
|
@@ -16,8 +16,9 @@
|
|
|
16
16
|
* output; both reach the checkout origin and `/api/*` the same way.
|
|
17
17
|
*
|
|
18
18
|
* An add-to-cart submit that the compliance gate and the checkout loader have
|
|
19
|
-
* released is sent to the store's cart route as JSON, the
|
|
20
|
-
* it returns is loaded as a script (which
|
|
19
|
+
* released is sent to the store's cart route as JSON, which adds the line to this
|
|
20
|
+
* store's provider session; the cart URL it returns is loaded as a script (which
|
|
21
|
+
* returns the cart holding the line), and
|
|
21
22
|
* the shopper stays on the page with a confirmation. Any failure before the provider
|
|
22
23
|
* is asked hands the form back to the native submit, which opens the cart page. A
|
|
23
24
|
* failure after the provider is asked never resubmits: that could add the line twice.
|
|
@@ -408,7 +409,7 @@ export async function addFromForm(
|
|
|
408
409
|
const quantity = wholeNumber(submittedField(data, "quantity")) || 1;
|
|
409
410
|
try {
|
|
410
411
|
const cart = parseCart(await loadCartJsonp(location, cartOrigin, env));
|
|
411
|
-
if (!cart || cart.errors.length > 0) {
|
|
412
|
+
if (!cart || cart.errors.length > 0 || cart.count === 0) {
|
|
412
413
|
announce(env, { status: "error", cartHref: config.cartUrl });
|
|
413
414
|
return true;
|
|
414
415
|
}
|
|
@@ -269,6 +269,58 @@ export async function maybeInjectPreviewReload(
|
|
|
269
269
|
|
|
270
270
|
const SHARE_STATE_TTL_SECONDS = 24 * 3600;
|
|
271
271
|
|
|
272
|
+
export interface PreviewSharePrActivity {
|
|
273
|
+
lastOpenedAt?: string;
|
|
274
|
+
lastOpenedMobile?: boolean;
|
|
275
|
+
lastOpenedPath?: string | null;
|
|
276
|
+
lastSignal?: "approved" | "flagged" | null;
|
|
277
|
+
lastSignalAt?: string | null;
|
|
278
|
+
lastSignalPath?: string | null;
|
|
279
|
+
openCount?: number;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
export type PreviewShareTelemetryEvent =
|
|
283
|
+
| "qr_modal_open"
|
|
284
|
+
| "copy_link"
|
|
285
|
+
| "copy_invite"
|
|
286
|
+
| "download_qr"
|
|
287
|
+
| "revoke_links"
|
|
288
|
+
| "mobile_viewport_toggle"
|
|
289
|
+
| "in_preview_qr"
|
|
290
|
+
| "native_share"
|
|
291
|
+
| "mobile_open"
|
|
292
|
+
| "desktop_open"
|
|
293
|
+
| "approve_signal"
|
|
294
|
+
| "flag_signal";
|
|
295
|
+
|
|
296
|
+
export type PreviewShareTelemetryCounters = Partial<Record<PreviewShareTelemetryEvent, number>>;
|
|
297
|
+
|
|
298
|
+
const ALLOWED_SHARE_TELEMETRY_EVENTS: ReadonlySet<string> = new Set<PreviewShareTelemetryEvent>([
|
|
299
|
+
"qr_modal_open",
|
|
300
|
+
"copy_link",
|
|
301
|
+
"copy_invite",
|
|
302
|
+
"download_qr",
|
|
303
|
+
"revoke_links",
|
|
304
|
+
"mobile_viewport_toggle",
|
|
305
|
+
"in_preview_qr",
|
|
306
|
+
"native_share",
|
|
307
|
+
"mobile_open",
|
|
308
|
+
"desktop_open",
|
|
309
|
+
"approve_signal",
|
|
310
|
+
"flag_signal",
|
|
311
|
+
]);
|
|
312
|
+
|
|
313
|
+
export function isPreviewShareTelemetryEvent(v: unknown): v is PreviewShareTelemetryEvent {
|
|
314
|
+
return typeof v === "string" && ALLOWED_SHARE_TELEMETRY_EVENTS.has(v);
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
export function extractPreviewPrNumber(pathOrUrl: string | null | undefined): number | null {
|
|
318
|
+
const m = /\/preview\/pr\/(\d+)(?:\/|$|\?|#)/.exec(String(pathOrUrl || ""));
|
|
319
|
+
if (!m) return null;
|
|
320
|
+
const n = Number.parseInt(m[1]!, 10);
|
|
321
|
+
return Number.isInteger(n) && n > 0 ? n : null;
|
|
322
|
+
}
|
|
323
|
+
|
|
272
324
|
export interface PreviewShareLinkState {
|
|
273
325
|
revokedAtSeconds?: number;
|
|
274
326
|
revokedSigs?: string[];
|
|
@@ -276,10 +328,14 @@ export interface PreviewShareLinkState {
|
|
|
276
328
|
lastOpenedAt?: string;
|
|
277
329
|
lastOpenedMobile?: boolean;
|
|
278
330
|
lastOpenedPath?: string | null;
|
|
331
|
+
lastOpenedPr?: number | null;
|
|
279
332
|
lastSignal?: "approved" | "flagged" | null;
|
|
280
333
|
lastSignalAt?: string | null;
|
|
281
334
|
lastSignalPath?: string | null;
|
|
335
|
+
lastSignalPr?: number | null;
|
|
282
336
|
openCount?: number;
|
|
337
|
+
prActivity?: Record<string, PreviewSharePrActivity>;
|
|
338
|
+
telemetry?: PreviewShareTelemetryCounters;
|
|
283
339
|
}
|
|
284
340
|
|
|
285
341
|
export interface PreviewShareKvLike {
|
|
@@ -331,22 +387,46 @@ export async function recordPreviewShareOpen(
|
|
|
331
387
|
userAgent?: string | null,
|
|
332
388
|
nowIso: string = new Date().toISOString(),
|
|
333
389
|
openedPath?: string | null,
|
|
390
|
+
prNumber?: number | null,
|
|
334
391
|
): Promise<PreviewShareLinkState> {
|
|
335
392
|
const state = await readPreviewShareState((k) => kv.get(k), tenantId);
|
|
336
393
|
const sig = extractPreviewTokenSignature(token);
|
|
337
394
|
const seen = new Set(Array.isArray(state.seenSigs) ? state.seenSigs : []);
|
|
338
395
|
if (sig) seen.add(sig);
|
|
396
|
+
const isMobile = /Mobile|Android|iPhone|iPad|iPod/i.test(String(userAgent || ""));
|
|
339
397
|
const cleanPath =
|
|
340
398
|
typeof openedPath === "string" && openedPath.trim().startsWith("/")
|
|
341
399
|
? openedPath.trim().slice(0, 160)
|
|
342
400
|
: (state.lastOpenedPath ?? null);
|
|
401
|
+
const resolvedPr =
|
|
402
|
+
typeof prNumber === "number" && Number.isInteger(prNumber) && prNumber > 0
|
|
403
|
+
? prNumber
|
|
404
|
+
: extractPreviewPrNumber(openedPath);
|
|
405
|
+
const prActivity: Record<string, PreviewSharePrActivity> = { ...(state.prActivity ?? {}) };
|
|
406
|
+
if (resolvedPr !== null) {
|
|
407
|
+
const key = String(resolvedPr);
|
|
408
|
+
const prevPr = prActivity[key] ?? {};
|
|
409
|
+
prActivity[key] = {
|
|
410
|
+
...prevPr,
|
|
411
|
+
lastOpenedAt: nowIso,
|
|
412
|
+
lastOpenedMobile: isMobile,
|
|
413
|
+
lastOpenedPath: cleanPath ?? prevPr.lastOpenedPath ?? null,
|
|
414
|
+
openCount: (prevPr.openCount ?? 0) + 1,
|
|
415
|
+
};
|
|
416
|
+
}
|
|
417
|
+
const telemetry: PreviewShareTelemetryCounters = { ...(state.telemetry ?? {}) };
|
|
418
|
+
const openMetric: PreviewShareTelemetryEvent = isMobile ? "mobile_open" : "desktop_open";
|
|
419
|
+
telemetry[openMetric] = (telemetry[openMetric] ?? 0) + 1;
|
|
343
420
|
const next: PreviewShareLinkState = {
|
|
344
421
|
...state,
|
|
345
422
|
seenSigs: [...seen].slice(-64),
|
|
346
423
|
lastOpenedAt: nowIso,
|
|
347
|
-
lastOpenedMobile:
|
|
424
|
+
lastOpenedMobile: isMobile,
|
|
348
425
|
lastOpenedPath: cleanPath,
|
|
426
|
+
lastOpenedPr: resolvedPr ?? state.lastOpenedPr ?? null,
|
|
349
427
|
openCount: (state.openCount ?? 0) + 1,
|
|
428
|
+
prActivity,
|
|
429
|
+
telemetry,
|
|
350
430
|
};
|
|
351
431
|
await kv.put(previewShareStateKey(tenantId), JSON.stringify(next), {
|
|
352
432
|
expirationTtl: SHARE_STATE_TTL_SECONDS,
|
|
@@ -360,17 +440,58 @@ export async function recordPreviewShareSignal(
|
|
|
360
440
|
signal: "approved" | "flagged",
|
|
361
441
|
signalPath?: string | null,
|
|
362
442
|
nowIso: string = new Date().toISOString(),
|
|
443
|
+
prNumber?: number | null,
|
|
363
444
|
): Promise<PreviewShareLinkState> {
|
|
364
445
|
const state = await readPreviewShareState((k) => kv.get(k), tenantId);
|
|
365
446
|
const cleanPath =
|
|
366
447
|
typeof signalPath === "string" && signalPath.trim().startsWith("/")
|
|
367
448
|
? signalPath.trim().slice(0, 160)
|
|
368
449
|
: (state.lastOpenedPath ?? null);
|
|
450
|
+
const resolvedPr =
|
|
451
|
+
typeof prNumber === "number" && Number.isInteger(prNumber) && prNumber > 0
|
|
452
|
+
? prNumber
|
|
453
|
+
: (extractPreviewPrNumber(signalPath) ?? state.lastOpenedPr ?? null);
|
|
454
|
+
const prActivity: Record<string, PreviewSharePrActivity> = { ...(state.prActivity ?? {}) };
|
|
455
|
+
if (resolvedPr !== null) {
|
|
456
|
+
const key = String(resolvedPr);
|
|
457
|
+
const prevPr = prActivity[key] ?? {};
|
|
458
|
+
prActivity[key] = {
|
|
459
|
+
...prevPr,
|
|
460
|
+
lastSignal: signal,
|
|
461
|
+
lastSignalAt: nowIso,
|
|
462
|
+
lastSignalPath: cleanPath ?? prevPr.lastOpenedPath ?? null,
|
|
463
|
+
};
|
|
464
|
+
}
|
|
465
|
+
const telemetry: PreviewShareTelemetryCounters = { ...(state.telemetry ?? {}) };
|
|
466
|
+
const sigMetric: PreviewShareTelemetryEvent =
|
|
467
|
+
signal === "approved" ? "approve_signal" : "flag_signal";
|
|
468
|
+
telemetry[sigMetric] = (telemetry[sigMetric] ?? 0) + 1;
|
|
369
469
|
const next: PreviewShareLinkState = {
|
|
370
470
|
...state,
|
|
371
471
|
lastSignal: signal,
|
|
372
472
|
lastSignalAt: nowIso,
|
|
373
473
|
lastSignalPath: cleanPath,
|
|
474
|
+
lastSignalPr: resolvedPr,
|
|
475
|
+
prActivity,
|
|
476
|
+
telemetry,
|
|
477
|
+
};
|
|
478
|
+
await kv.put(previewShareStateKey(tenantId), JSON.stringify(next), {
|
|
479
|
+
expirationTtl: SHARE_STATE_TTL_SECONDS,
|
|
480
|
+
});
|
|
481
|
+
return next;
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
export async function recordPreviewShareTelemetry(
|
|
485
|
+
kv: PreviewShareKvLike,
|
|
486
|
+
tenantId: string,
|
|
487
|
+
event: PreviewShareTelemetryEvent,
|
|
488
|
+
): Promise<PreviewShareLinkState> {
|
|
489
|
+
const state = await readPreviewShareState((k) => kv.get(k), tenantId);
|
|
490
|
+
const telemetry: PreviewShareTelemetryCounters = { ...(state.telemetry ?? {}) };
|
|
491
|
+
telemetry[event] = (telemetry[event] ?? 0) + 1;
|
|
492
|
+
const next: PreviewShareLinkState = {
|
|
493
|
+
...state,
|
|
494
|
+
telemetry,
|
|
374
495
|
};
|
|
375
496
|
await kv.put(previewShareStateKey(tenantId), JSON.stringify(next), {
|
|
376
497
|
expirationTtl: SHARE_STATE_TTL_SECONDS,
|
|
@@ -393,11 +514,15 @@ export async function revokePreviewShareLinks(
|
|
|
393
514
|
const sig = extractPreviewTokenSignature(tok);
|
|
394
515
|
if (sig) revoked.add(sig);
|
|
395
516
|
}
|
|
517
|
+
const telemetry: PreviewShareTelemetryCounters = { ...(state.telemetry ?? {}) };
|
|
518
|
+
telemetry.revoke_links = (telemetry.revoke_links ?? 0) + 1;
|
|
396
519
|
const next: PreviewShareLinkState = {
|
|
397
520
|
revokedAtSeconds: nowSeconds,
|
|
398
521
|
revokedSigs: [...revoked].slice(-128),
|
|
399
522
|
seenSigs: [],
|
|
400
523
|
openCount: 0,
|
|
524
|
+
prActivity: {},
|
|
525
|
+
telemetry,
|
|
401
526
|
};
|
|
402
527
|
await kv.put(previewShareStateKey(tenantId), JSON.stringify(next), {
|
|
403
528
|
expirationTtl: SHARE_STATE_TTL_SECONDS,
|
|
@@ -30,6 +30,7 @@ import {
|
|
|
30
30
|
import { STATIC_SCRIPT_HASHES, STATIC_STYLE_HASHES } from "@/lib/access/shared/cspStaticHashes";
|
|
31
31
|
import { applySecurityHeaders } from "@/lib/access/shared/securityHeaders";
|
|
32
32
|
import {
|
|
33
|
+
extractPreviewPrNumber,
|
|
33
34
|
isPreviewOperatorSurfacePath,
|
|
34
35
|
isPreviewShareTokenRevoked,
|
|
35
36
|
maybeInjectPreviewReload,
|
|
@@ -258,6 +259,7 @@ export async function runRenderChain(input: RenderChainInput): Promise<Response>
|
|
|
258
259
|
request.headers.get("user-agent"),
|
|
259
260
|
new Date().toISOString(),
|
|
260
261
|
renderPath,
|
|
262
|
+
extractPreviewPrNumber(url.pathname),
|
|
261
263
|
);
|
|
262
264
|
}
|
|
263
265
|
// The cookie itself, when the context verified: the revision cookie below checks
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tokenoftrust/storefront-runner",
|
|
3
|
-
"version": "7.
|
|
3
|
+
"version": "7.3.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",
|
|
@@ -785,6 +785,20 @@ async function signField(
|
|
|
785
785
|
return { name, value: field.value };
|
|
786
786
|
}
|
|
787
787
|
|
|
788
|
+
/**
|
|
789
|
+
* One cart line's fields as the checkout receives them: signed for product `code` in `signed`
|
|
790
|
+
* mode, passed through under their `checkoutFieldName` otherwise.
|
|
791
|
+
*/
|
|
792
|
+
export async function signCartLine(
|
|
793
|
+
fields: readonly CartField[],
|
|
794
|
+
opts: { mode: ManagedCheckoutConfig["mode"]; secret?: string; code: string },
|
|
795
|
+
): Promise<RenderedCartField[]> {
|
|
796
|
+
if (opts.mode !== "signed") return fields.map(unsignedField);
|
|
797
|
+
const secret = opts.secret;
|
|
798
|
+
if (!secret) throw new CartSigningUnavailableError();
|
|
799
|
+
return Promise.all(fields.map((field) => signField(secret, opts.code, field)));
|
|
800
|
+
}
|
|
801
|
+
|
|
788
802
|
/**
|
|
789
803
|
* Build the render-ready add-to-cart payload for a variant. In `unsigned-demo`
|
|
790
804
|
* mode fields pass through verbatim (no secret touched); in `signed` mode every
|