@tokenoftrust/storefront-runner 7.2.8 → 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.
@@ -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 Foxy returned, or a read that failed. A failure is not an empty 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.cookies.set(CART_SESSION_COOKIE, id, {
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
- foxyCartRedirectUrl,
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 { bindCartSession, CART_UNAVAILABLE_MESSAGE, withCartSession } from "@/lib/checkout/commerce/cartSession";
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
- /** Redirect onto this tenant's Foxy session. A shopper-supplied fcsid is dropped. */
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 bindCartSession(context, commerce, commerceTenantId(tenant));
130
- if (!fcsid) return null;
131
- const kept = fields.filter((field) => field.name.split("||")[0] !== "fcsid");
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 adds the line itself (cartState.ts) and asks for the signed cart URL as data.
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 signed provider cart URL
20
- * it returns is loaded as a script (which adds the line and returns the cart), and
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
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tokenoftrust/storefront-runner",
3
- "version": "7.2.8",
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