@tokenoftrust/storefront-runner 7.7.4 → 7.8.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/dev-plugins/dev-auth-outbox.mjs +5 -3
- package/apps/storefront/src/components/catalog/storefront/ProductCard.astro +13 -9
- package/apps/storefront/src/components/catalog/storefront/islands/SearchTypeahead.tsx +2 -2
- package/apps/storefront/src/components/catalog/storefront/islands/VariantSelector.tsx +6 -4
- package/apps/storefront/src/components/catalog/storefront/plp/FacetSidebar.astro +4 -3
- package/apps/storefront/src/components/catalog/storefront/plp/SortSelect.astro +3 -2
- package/apps/storefront/src/components/compliance/storefront/islands/CheckoutComplianceGate.tsx +39 -45
- package/apps/storefront/src/components/publication/storefront/islands/CatalogQueryView.tsx +7 -4
- package/apps/storefront/src/layouts/Layout.astro +11 -7
- package/apps/storefront/src/lib/access/auth/agentSessionGate.ts +1 -0
- package/apps/storefront/src/lib/access/auth/loginGate.ts +14 -0
- package/apps/storefront/src/lib/access/shared/tenantRouting.ts +3 -1
- package/apps/storefront/src/lib/catalog/search/index.ts +3 -4
- package/apps/storefront/src/lib/catalog/shared/catalogIndex.ts +12 -7
- package/apps/storefront/src/lib/catalog/shared/catalogQueryView.ts +4 -2
- package/apps/storefront/src/lib/catalog/tot/query.ts +2 -1
- package/apps/storefront/src/lib/checkout/commerce/cartSession.ts +10 -11
- package/apps/storefront/src/lib/checkout/commerce/checkoutHandoffRoute.ts +81 -14
- package/apps/storefront/src/lib/compliance/browser/checkoutVerificationFlow.ts +35 -0
- package/apps/storefront/src/lib/content/seo/structuredData.ts +3 -2
- package/apps/storefront/src/lib/content/shared/jsonld.ts +3 -2
- package/apps/storefront/src/lib/customers/accounts/catalogAdmission.ts +75 -0
- package/apps/storefront/src/lib/customers/accounts/checkoutProof.ts +133 -0
- package/apps/storefront/src/lib/customers/accounts/orgKyb.ts +12 -0
- package/apps/storefront/src/lib/customers/accounts/pricing.ts +25 -0
- package/apps/storefront/src/lib/customers/accounts/purchaseAccess.ts +45 -0
- package/apps/storefront/src/lib/customers/accounts/scope.ts +55 -0
- package/apps/storefront/src/lib/customers/accounts/session.ts +173 -0
- package/apps/storefront/src/lib/customers/accounts/shopperPricingClient.ts +69 -0
- package/apps/storefront/src/lib/engagement/contact/submitToken.ts +2 -1
- package/apps/storefront/src/lib/inventory/allocations.ts +8 -5
- package/apps/storefront/src/lib/membership/eligibility.ts +2 -23
- package/apps/storefront/src/lib/publication/shared/cdnForward.ts +10 -3
- package/apps/storefront/src/lib/publication/shared/staticQuery.ts +10 -3
- package/apps/storefront/src/middleware/index.ts +80 -6
- package/apps/storefront/src/middleware/renderChain.ts +43 -26
- package/apps/storefront/src/middleware/routeBranch.ts +1 -0
- package/apps/storefront/src/middleware/staticBundle.ts +18 -3
- package/apps/storefront/src/pages/_sitemap.ts +14 -7
- package/apps/storefront/src/pages/api/cart-proposal/confirm.ts +2 -1
- package/apps/storefront/src/pages/api/cart-proposal/review.ts +5 -2
- package/apps/storefront/src/pages/api/commerce/cart-session.ts +3 -0
- package/apps/storefront/src/pages/api/commerce/checkout-sessions/[id].ts +2 -1
- package/apps/storefront/src/pages/api/commerce/checkout-sessions.ts +3 -1
- package/apps/storefront/src/pages/api/commerce/final-cart-authorization.ts +43 -10
- package/apps/storefront/src/pages/api/compliance/preflight.ts +34 -5
- package/apps/storefront/src/pages/cart.ts +3 -0
- package/apps/storefront/src/pages/catalog-index.json.ts +3 -2
- package/apps/storefront/src/pages/collections/[handle]/page/[n].astro +2 -1
- package/apps/storefront/src/pages/collections/[handle].astro +2 -1
- package/apps/storefront/src/pages/collections/_CollectionView.astro +8 -4
- package/apps/storefront/src/pages/index.astro +5 -3
- package/apps/storefront/src/pages/llms.txt.ts +2 -1
- package/apps/storefront/src/pages/products/[handle].astro +52 -8
- package/apps/storefront/src/pages/saved.astro +2 -1
- package/package.json +1 -1
- package/packages/cli/src/declared-config.mjs +46 -1
- package/packages/public-runtime/src/checkout-orders.ts +9 -1
- package/packages/public-runtime/src/checkout.ts +1 -1
- package/packages/public-runtime/src/declared-tenant-config.d.mts +11 -1
- package/packages/public-runtime/src/declared-tenant-config.mjs +111 -1
- package/packages/public-runtime/src/publication-space.ts +1 -0
- package/packages/public-runtime/src/static-bundle.ts +28 -3
- package/packages/public-runtime/src/tenant.ts +15 -0
|
@@ -15,7 +15,7 @@ export const CATALOG_INDEX_VERSION = 1;
|
|
|
15
15
|
const DESCRIPTION_CHARS = 280;
|
|
16
16
|
|
|
17
17
|
export interface CatalogIndexVariant {
|
|
18
|
-
price
|
|
18
|
+
price?: number;
|
|
19
19
|
compare_at_price?: number;
|
|
20
20
|
option_values: Record<string, string>;
|
|
21
21
|
inventory: { available: boolean };
|
|
@@ -32,7 +32,7 @@ export interface CatalogIndexProduct {
|
|
|
32
32
|
status: CatalogProduct["status"];
|
|
33
33
|
options: { name: string }[];
|
|
34
34
|
variants: CatalogIndexVariant[];
|
|
35
|
-
price_range
|
|
35
|
+
price_range?: CatalogProduct["price_range"];
|
|
36
36
|
collections: string[];
|
|
37
37
|
created_at: string;
|
|
38
38
|
image?: { url: string; alt?: string; rehosted?: boolean; id?: string };
|
|
@@ -47,9 +47,10 @@ export interface CatalogIndex {
|
|
|
47
47
|
version: number;
|
|
48
48
|
products: CatalogIndexProduct[];
|
|
49
49
|
collections: CatalogIndexCollection[];
|
|
50
|
+
pricesHidden?: true;
|
|
50
51
|
}
|
|
51
52
|
|
|
52
|
-
export function toCatalogIndexProduct(p: CatalogProduct): CatalogIndexProduct {
|
|
53
|
+
export function toCatalogIndexProduct(p: CatalogProduct, pricesHidden = false): CatalogIndexProduct {
|
|
53
54
|
const doc: CatalogIndexProduct = {
|
|
54
55
|
id: p.id,
|
|
55
56
|
handle: p.handle,
|
|
@@ -59,12 +60,14 @@ export function toCatalogIndexProduct(p: CatalogProduct): CatalogIndexProduct {
|
|
|
59
60
|
status: p.status,
|
|
60
61
|
options: p.options.map((o) => ({ name: o.name })),
|
|
61
62
|
variants: p.variants.map((v) => ({
|
|
62
|
-
|
|
63
|
-
|
|
63
|
+
...(!pricesHidden ? {
|
|
64
|
+
price: v.price,
|
|
65
|
+
...(v.compare_at_price != null ? { compare_at_price: v.compare_at_price } : {}),
|
|
66
|
+
} : {}),
|
|
64
67
|
option_values: v.option_values,
|
|
65
68
|
inventory: { available: v.inventory.available },
|
|
66
69
|
})),
|
|
67
|
-
price_range: p.price_range,
|
|
70
|
+
...(!pricesHidden ? { price_range: p.price_range } : {}),
|
|
68
71
|
collections: p.collections,
|
|
69
72
|
created_at: p.created_at,
|
|
70
73
|
};
|
|
@@ -84,11 +87,13 @@ export function toCatalogIndexProduct(p: CatalogProduct): CatalogIndexProduct {
|
|
|
84
87
|
export function buildCatalogIndex(
|
|
85
88
|
activeProducts: CatalogProduct[],
|
|
86
89
|
collections: CatalogCollection[],
|
|
90
|
+
pricesHidden = false,
|
|
87
91
|
): CatalogIndex {
|
|
88
92
|
return {
|
|
89
93
|
version: CATALOG_INDEX_VERSION,
|
|
90
|
-
products: activeProducts.map(toCatalogIndexProduct),
|
|
94
|
+
products: activeProducts.map(product => toCatalogIndexProduct(product, pricesHidden)),
|
|
91
95
|
collections: collections.map((c) => ({ handle: c.handle, product_handles: c.product_handles })),
|
|
96
|
+
...(pricesHidden ? { pricesHidden: true } : {}),
|
|
92
97
|
};
|
|
93
98
|
}
|
|
94
99
|
|
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
import type { ListProductsQuery, ListProductsResponse } from "@tot/public-runtime";
|
|
8
8
|
import { applyQuery, buildFacets, collectionProducts, paginate } from "../tot/query.js";
|
|
9
9
|
import { buildSearchIndex } from "../search/index.js";
|
|
10
|
+
import { withoutPrivatePriceQuery } from "../../publication/shared/staticQuery.js";
|
|
10
11
|
import {
|
|
11
12
|
asCatalogCollection,
|
|
12
13
|
asCatalogProduct,
|
|
@@ -29,8 +30,9 @@ export function collectionViewFromIndex(
|
|
|
29
30
|
const active = index.products.map(asCatalogProduct);
|
|
30
31
|
const collection = index.collections.find((c) => c.handle === handle);
|
|
31
32
|
const pool = collection ? collectionProducts(active, asCatalogCollection(collection)) : [];
|
|
32
|
-
const
|
|
33
|
-
const
|
|
33
|
+
const browse = withoutPrivatePriceQuery(query, index.pricesHidden === true);
|
|
34
|
+
const facets = buildFacets(pool, browse, !index.pricesHidden);
|
|
35
|
+
const { items, page, pageSize, total } = paginate(applyQuery(pool, browse, true), browse);
|
|
34
36
|
return { products: items, page, pageSize, total, facets };
|
|
35
37
|
}
|
|
36
38
|
|
|
@@ -53,6 +53,7 @@ export function isNew(p: CatalogProduct, days = 60): boolean {
|
|
|
53
53
|
export function buildFacets(
|
|
54
54
|
pool: CatalogProduct[],
|
|
55
55
|
query: ListProductsQuery = {},
|
|
56
|
+
includePrices = true,
|
|
56
57
|
): Facet[] {
|
|
57
58
|
const optionValues = new Map<string, Set<string>>();
|
|
58
59
|
const tagNames = new Set<string>();
|
|
@@ -76,7 +77,7 @@ export function buildFacets(
|
|
|
76
77
|
facets.push(buildTagFacet(tagNames, applyFilters(pool, query, "tags")));
|
|
77
78
|
}
|
|
78
79
|
facets.push(buildAvailabilityFacet(applyFilters(pool, query, "availability")));
|
|
79
|
-
facets.push(buildPriceFacet(applyFilters(pool, query, "price")));
|
|
80
|
+
if (includePrices) facets.push(buildPriceFacet(applyFilters(pool, query, "price")));
|
|
80
81
|
return facets;
|
|
81
82
|
}
|
|
82
83
|
|
|
@@ -147,12 +147,15 @@ async function readCart(
|
|
|
147
147
|
} catch (error) {
|
|
148
148
|
return { status: "unreadable", reason: error instanceof Error ? error.name : "Error" };
|
|
149
149
|
}
|
|
150
|
-
|
|
150
|
+
const protectedFields = fields.some(field => /^(?:\d+:)?shopper_checkout\|\|/.test(field.name));
|
|
151
|
+
const form = protectedFields ? new URLSearchParams() : url.searchParams;
|
|
152
|
+
for (const field of fields) form.append(field.name, field.value);
|
|
151
153
|
url.searchParams.set("output", "json");
|
|
152
154
|
if (fcsid) url.searchParams.set("fcsid", fcsid);
|
|
153
155
|
try {
|
|
154
156
|
const response = await fetchImpl(url.toString(), {
|
|
155
|
-
method: "GET",
|
|
157
|
+
method: protectedFields ? "POST" : "GET",
|
|
158
|
+
...(protectedFields ? { body: form } : {}),
|
|
156
159
|
redirect: "manual",
|
|
157
160
|
credentials: "omit",
|
|
158
161
|
headers: { accept: "application/json" },
|
|
@@ -377,17 +380,13 @@ export async function addLinesToTenantCart(input: {
|
|
|
377
380
|
}
|
|
378
381
|
const mergedCoupons = [...existingCoupons, ...newCoupons];
|
|
379
382
|
const addVerification = adds.flat().find((field) => field.name.split("||")[0] === "verification")?.value;
|
|
383
|
+
const checkoutProof = adds.flat().find((field) => field.name.split("||")[0] === "shopper_checkout")?.value;
|
|
380
384
|
const itemFields: CartLineField[] = [];
|
|
381
385
|
for (const [index, line] of carried.entries()) {
|
|
382
|
-
const
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
...line.fields.filter((f) => f.name !== "verification"),
|
|
387
|
-
{ name: "verification", value: addVerification },
|
|
388
|
-
],
|
|
389
|
-
}
|
|
390
|
-
: line;
|
|
386
|
+
const fields = line.fields.filter(field => !(addVerification && field.name === "verification") && field.name !== "shopper_checkout");
|
|
387
|
+
if (addVerification) fields.push({ name: "verification", value: addVerification });
|
|
388
|
+
if (checkoutProof) fields.push({ name: "shopper_checkout", value: checkoutProof });
|
|
389
|
+
const toSign = { ...line, fields };
|
|
391
390
|
for (const field of await input.sign(toSign)) itemFields.push({ name: `${index + 1}:${field.name}`, value: field.value });
|
|
392
391
|
}
|
|
393
392
|
const numbered = carried.length + adds.length > 1;
|
|
@@ -56,6 +56,8 @@ import { effectiveExcise } from "@/lib/checkout/commerce/checkoutExcise";
|
|
|
56
56
|
import { fromD1 } from "@/lib/catalog/d1/catalog";
|
|
57
57
|
import { readD1 } from "@/lib/publication/shared/env";
|
|
58
58
|
import { handoffStockFinding, MIRROR_LOCATION_UNSPECIFIED, readMirrorBalance } from "@/lib/inventory/mirrorStock";
|
|
59
|
+
import { shopperCatalogProduct, shopperVariantPrice } from "@/lib/customers/accounts/pricing";
|
|
60
|
+
import { requiresShopperPurchase, shopperJson } from "@/lib/customers/accounts/purchaseAccess";
|
|
59
61
|
|
|
60
62
|
export type SampleProductReader = (tenant: TenantConfig, handle: string, commerce: ResolvedManagedCheckout) => Promise<CatalogProduct | null>;
|
|
61
63
|
|
|
@@ -153,10 +155,9 @@ function takePromoCoupon(
|
|
|
153
155
|
}
|
|
154
156
|
|
|
155
157
|
/**
|
|
156
|
-
* Add the enforced line to this tenant's Foxy cart from the server
|
|
157
|
-
* the session that holds it. The location carries no cart fields, so following it adds nothing.
|
|
158
|
+
* Add the enforced line to this tenant's Foxy cart from the server.
|
|
158
159
|
*/
|
|
159
|
-
async function
|
|
160
|
+
async function addEnforcedLine(
|
|
160
161
|
context: APIContext,
|
|
161
162
|
commerce: ResolvedManagedCheckout,
|
|
162
163
|
tenant: TenantConfig,
|
|
@@ -164,7 +165,7 @@ async function sessionedCartLocation(
|
|
|
164
165
|
secret: string | undefined,
|
|
165
166
|
coupon: string | null = null,
|
|
166
167
|
): Promise<string | null> {
|
|
167
|
-
|
|
168
|
+
return addToBoundCart(
|
|
168
169
|
context,
|
|
169
170
|
commerce,
|
|
170
171
|
commerceTenantId(tenant),
|
|
@@ -173,7 +174,6 @@ async function sessionedCartLocation(
|
|
|
173
174
|
undefined,
|
|
174
175
|
coupon,
|
|
175
176
|
);
|
|
176
|
-
return fcsid ? withCartSession(commerce.cartUrl, fcsid) : null;
|
|
177
177
|
}
|
|
178
178
|
|
|
179
179
|
export function ledgerStage(env: string | undefined): "preview" | "publication" | null {
|
|
@@ -280,7 +280,32 @@ export async function completeCartFields(
|
|
|
280
280
|
}
|
|
281
281
|
|
|
282
282
|
/** Native cart POST. Browser preflight is not consulted. Payment is never authorized. */
|
|
283
|
-
|
|
283
|
+
export interface GatedHandoff {
|
|
284
|
+
tierId: string | null;
|
|
285
|
+
providerOrigin: string;
|
|
286
|
+
validateVerificationRef: (ref: string) => Promise<boolean>;
|
|
287
|
+
prepareProof: () => Promise<{ proof: string; buyerConfirmation: string; bind: (selector: string) => Promise<boolean> } | null>;
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
function buyerHandoff(providerOrigin: string, selector: string, proof: string, confirmation: string): Response {
|
|
291
|
+
const action = new URL("/api/commerce/shopper-checkout-handoff", providerOrigin);
|
|
292
|
+
const fields = { fcsid: selector, shopper_checkout: proof, buyer_confirmation: confirmation };
|
|
293
|
+
const inputs = Object.entries(fields).map(([name, value]) =>
|
|
294
|
+
`<input type="hidden" name="${name}" value="${escapeHtml(value)}">`).join("");
|
|
295
|
+
const html = '<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">' +
|
|
296
|
+
`<title>Continue to checkout</title><main><h1>Continue to checkout</h1><form method="post" action="${escapeHtml(action.href)}">` +
|
|
297
|
+
`${inputs}<button type="submit">Continue to checkout</button></form></main></html>`;
|
|
298
|
+
return new Response(html, { headers: {
|
|
299
|
+
"content-type": "text/html; charset=utf-8",
|
|
300
|
+
"cache-control": "private, no-store",
|
|
301
|
+
"content-security-policy": `default-src 'none'; frame-ancestors 'none'; base-uri 'none'; form-action ${action.origin}`,
|
|
302
|
+
"referrer-policy": "no-referrer",
|
|
303
|
+
"x-robots-tag": "noindex, nofollow",
|
|
304
|
+
"x-tot-payment-authorized": "false",
|
|
305
|
+
} });
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
async function cartFormPost(context: APIContext, shopper?: GatedHandoff): Promise<Response> {
|
|
284
309
|
const { tenant, commerce } = context.locals;
|
|
285
310
|
if (!commerce) {
|
|
286
311
|
return cartDenial(
|
|
@@ -297,12 +322,43 @@ async function cartFormPost(context: APIContext): Promise<Response> {
|
|
|
297
322
|
503,
|
|
298
323
|
);
|
|
299
324
|
}
|
|
300
|
-
|
|
325
|
+
let form: FormData;
|
|
326
|
+
try { form = await context.request.formData(); }
|
|
327
|
+
catch { return cartDenial("signature", "Invalid cart.", 422); }
|
|
301
328
|
const submitted: Array<[string, string]> = [];
|
|
302
329
|
for (const [name, value] of form.entries()) {
|
|
303
330
|
if (typeof value !== "string") return cartDenial("signature", "Invalid cart.", 422);
|
|
304
331
|
submitted.push([name, value]);
|
|
305
332
|
}
|
|
333
|
+
if (shopper) {
|
|
334
|
+
const { entries: purchase, ref } = takeVerificationRef(submitted);
|
|
335
|
+
const handle = form.get("productHandle");
|
|
336
|
+
const variantId = form.get("variantId");
|
|
337
|
+
const quantity = form.get("quantity");
|
|
338
|
+
if (purchase.length !== 3 || submitted.length !== 3 + Number(ref !== null) ||
|
|
339
|
+
typeof handle !== "string" || typeof variantId !== "string" ||
|
|
340
|
+
typeof quantity !== "string" || !/^[1-9]\d{0,2}$/.test(quantity) || Number(quantity) > MAX_CART_QUANTITY ||
|
|
341
|
+
handle.length < 1 || handle.length > 160 || variantId.length < 1 || variantId.length > 256) {
|
|
342
|
+
return cartDenial("signature", "Invalid cart.", 422);
|
|
343
|
+
}
|
|
344
|
+
if (ref && !await shopper.validateVerificationRef(ref)) return cartDenial("signature", "Verification is unavailable for this session.", 422);
|
|
345
|
+
const product = await context.locals.tot.getProductByHandle(handle);
|
|
346
|
+
if (!shopperCatalogProduct(tenant, product)) return cartDenial("signature", "This product is unavailable.", 422);
|
|
347
|
+
const variant = product.variants.find(item => item.id === variantId && item.inventory.available);
|
|
348
|
+
const price = variant && shopperVariantPrice(tenant, product, variant, shopper.tierId);
|
|
349
|
+
if (!price || !variant) return cartDenial("signature", "This product is unavailable.", 422);
|
|
350
|
+
const payload = await buildVariantCartPayload(product, variant, {
|
|
351
|
+
mode: commerce.mode, secret: signing.secret, signedPrice: price.price, tenantId: commerceTenantId(tenant),
|
|
352
|
+
currency: tenant.currency, publicOrigin: tenantPublicOrigin(tenant, {
|
|
353
|
+
requestOrigin: context.locals.requestOrigin,
|
|
354
|
+
basePath: context.locals.imageBasePath || context.locals.apiBasePath || context.locals.basePath,
|
|
355
|
+
}),
|
|
356
|
+
});
|
|
357
|
+
submitted.length = 0;
|
|
358
|
+
for (const field of payload.hidden) submitted.push([field.name, field.value]);
|
|
359
|
+
submitted.push([payload.quantityName, quantity]);
|
|
360
|
+
if (ref) submitted.push(["verification", ref]);
|
|
361
|
+
}
|
|
306
362
|
// The compliance gate adds the shopper's verification ref; it rides to the cart signed.
|
|
307
363
|
const { entries: withoutVerification, ref } = takeVerificationRef(submitted);
|
|
308
364
|
const { entries, coupon } = takePromoCoupon(withoutVerification, context.request.url);
|
|
@@ -323,8 +379,18 @@ async function cartFormPost(context: APIContext): Promise<Response> {
|
|
|
323
379
|
ref, returnUrl: submittedFromUrl(context.request, tenant),
|
|
324
380
|
});
|
|
325
381
|
if (!imaged) return cartDenial("shipping", SHIPPING_UNAVAILABLE_CART_MESSAGE, 409);
|
|
326
|
-
|
|
327
|
-
if (
|
|
382
|
+
let proof: Awaited<ReturnType<GatedHandoff["prepareProof"]>> = null;
|
|
383
|
+
if (shopper) {
|
|
384
|
+
if (commerce.mode !== "signed" || !signing.secret) return cartDenial("signing-unavailable", CART_UNAVAILABLE_MESSAGE, 503);
|
|
385
|
+
const code = submittedCode(imaged);
|
|
386
|
+
proof = code ? await shopper.prepareProof() : null;
|
|
387
|
+
if (!proof || !code) return cartDenial("signing-unavailable", CART_UNAVAILABLE_MESSAGE, 503);
|
|
388
|
+
imaged.push(...await signCartLine([{ name: "shopper_checkout", value: proof.proof }], { mode: commerce.mode, secret: signing.secret, code }));
|
|
389
|
+
}
|
|
390
|
+
const selector = await addEnforcedLine(context, commerce, tenant, imaged, signing.secret, coupon);
|
|
391
|
+
if (!selector || (proof && !await proof.bind(selector))) return cartDenial("signing-unavailable", CART_UNAVAILABLE_MESSAGE, 503);
|
|
392
|
+
if (proof && shopper) return buyerHandoff(shopper.providerOrigin, selector, proof.proof, proof.buyerConfirmation);
|
|
393
|
+
const location = withCartSession(commerce.cartUrl, selector);
|
|
328
394
|
// The page reads the cart that now holds the line (cartState.ts) and asks for its URL as data.
|
|
329
395
|
if ((context.request.headers.get("accept") ?? "").includes("application/json")) {
|
|
330
396
|
return new Response(JSON.stringify({ location }), {
|
|
@@ -348,8 +414,9 @@ async function cartFormPost(context: APIContext): Promise<Response> {
|
|
|
348
414
|
});
|
|
349
415
|
}
|
|
350
416
|
|
|
351
|
-
export async function checkoutHandoffPost(context: APIContext): Promise<Response> {
|
|
352
|
-
if (
|
|
417
|
+
export async function checkoutHandoffPost(context: APIContext, shopper?: GatedHandoff): Promise<Response> {
|
|
418
|
+
if (!shopper && requiresShopperPurchase(context.locals.tenant)) return shopperJson({ ok: false, error: "shopper_sign_in_required" }, 401);
|
|
419
|
+
if (isCartForm(context.request)) return cartFormPost(context, shopper);
|
|
353
420
|
const { tenant, browserEnvironment, commerce } = context.locals;
|
|
354
421
|
|
|
355
422
|
// No managed checkout on this tenant → nothing to attribute.
|
|
@@ -450,9 +517,9 @@ export async function sampleCartGet(
|
|
|
450
517
|
if (!result.ok) return invalid();
|
|
451
518
|
const shipped = await boundShippingPolicy(result.fields, tenant, "signed", signing.secret);
|
|
452
519
|
if (!shipped) return sampleResponse('{"error":"shipping_unavailable"}', 409);
|
|
453
|
-
const
|
|
454
|
-
if (!
|
|
455
|
-
return sampleResponse(null, 303,
|
|
520
|
+
const selector = await addEnforcedLine(context, commerce, tenant, shipped, signing.secret);
|
|
521
|
+
if (!selector) return sampleResponse('{"error":"cart_unavailable"}', 503);
|
|
522
|
+
return sampleResponse(null, 303, withCartSession(commerce.cartUrl, selector));
|
|
456
523
|
} catch { return sampleResponse('{"error":"sample_unavailable"}', 503); }
|
|
457
524
|
}
|
|
458
525
|
|
|
@@ -134,6 +134,41 @@ export function bypassesComplianceGate(res: PreflightResponse | null): boolean {
|
|
|
134
134
|
return res !== null && res.gate === "not-required" && res.decision.status === "clear";
|
|
135
135
|
}
|
|
136
136
|
|
|
137
|
+
export interface PendingLine {
|
|
138
|
+
form: HTMLFormElement;
|
|
139
|
+
shopperCart: boolean;
|
|
140
|
+
handle: string;
|
|
141
|
+
sku?: string;
|
|
142
|
+
variantId?: string;
|
|
143
|
+
quantity: number;
|
|
144
|
+
title: string;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
export function checkoutLineFromForm(form: HTMLFormElement): PendingLine | null {
|
|
148
|
+
const shopperCart = form.hasAttribute("data-shopper-cart");
|
|
149
|
+
if (!shopperCart && !form.hasAttribute("data-managed-cart")) return null;
|
|
150
|
+
const quantityInput = form.querySelector<HTMLInputElement>('input[name$="quantity" i]');
|
|
151
|
+
return {
|
|
152
|
+
form,
|
|
153
|
+
shopperCart,
|
|
154
|
+
handle: shopperCart ? form.querySelector<HTMLInputElement>('input[name="productHandle"]')?.value ?? "" : form.dataset.productHandle ?? "",
|
|
155
|
+
variantId: (shopperCart ? form.querySelector<HTMLSelectElement>('select[name="variantId"]')?.value : form.dataset.variantId) || undefined,
|
|
156
|
+
sku: shopperCart ? undefined : form.dataset.variantSku || undefined,
|
|
157
|
+
quantity: Math.max(1, parseInt(quantityInput?.value ?? "1", 10) || 1),
|
|
158
|
+
title: form.dataset.productTitle ?? "this item",
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
export function carryCheckoutVerification(form: HTMLFormElement, ref: string | null): void {
|
|
163
|
+
form.querySelectorAll('input[name="verification"]').forEach(input => input.remove());
|
|
164
|
+
if (!ref) return;
|
|
165
|
+
const input = form.ownerDocument.createElement("input");
|
|
166
|
+
input.type = "hidden";
|
|
167
|
+
input.name = "verification";
|
|
168
|
+
input.value = ref;
|
|
169
|
+
form.appendChild(input);
|
|
170
|
+
}
|
|
171
|
+
|
|
137
172
|
/** True when the decision carries the provider's real "did not pass" block. */
|
|
138
173
|
function hasVerificationFailure(decision: CartComplianceDecision): boolean {
|
|
139
174
|
return decision.blocks.some(
|
|
@@ -17,6 +17,7 @@ import type {
|
|
|
17
17
|
TenantConfig,
|
|
18
18
|
} from "@tot/public-runtime";
|
|
19
19
|
import { productLd } from "../shared/jsonld.js";
|
|
20
|
+
import { hidesPublicCatalogPrices } from "@tot/public-runtime/declared-tenant-config";
|
|
20
21
|
import { pageUrlForm } from "./urlForm.js";
|
|
21
22
|
|
|
22
23
|
type Node = Record<string, unknown>;
|
|
@@ -256,7 +257,7 @@ export function composeStructuredData(input: ComposeInput): Node | null {
|
|
|
256
257
|
name: nameOf("Product", p.title, "title"),
|
|
257
258
|
url: canonical,
|
|
258
259
|
...(pageToken ? { mainEntityOfPage: { "@id": pageId } } : {}),
|
|
259
|
-
...(single ? { offers: offer(single) } : {}),
|
|
260
|
+
...(single && !hidesPublicCatalogPrices(tenant) ? { offers: offer(single) } : {}),
|
|
260
261
|
...(profile.reviews ? page.reviews ?? {} : {}),
|
|
261
262
|
};
|
|
262
263
|
}
|
|
@@ -277,7 +278,7 @@ export function composeStructuredData(input: ComposeInput): Node | null {
|
|
|
277
278
|
"@type": "Product",
|
|
278
279
|
name: `${p.title} - ${v.title}`,
|
|
279
280
|
...(v.sku ? { sku: v.sku } : {}),
|
|
280
|
-
offers: offer(v),
|
|
281
|
+
...(!hidesPublicCatalogPrices(tenant) ? { offers: offer(v) } : {}),
|
|
281
282
|
})),
|
|
282
283
|
...(profile.reviews ? page.reviews ?? {} : {}),
|
|
283
284
|
};
|
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
* BreadcrumbList, Organization. Kept pure so pages compose them and pass to <Seo>.
|
|
4
4
|
*/
|
|
5
5
|
import type { CatalogProduct, Review, TenantConfig } from "@tot/public-runtime";
|
|
6
|
+
import { hidesPublicCatalogPrices } from "@tot/public-runtime/declared-tenant-config";
|
|
6
7
|
import { pageUrlForm } from "../seo/urlForm.js";
|
|
7
8
|
import { isAvailable } from "../../catalog/tot/query.js";
|
|
8
9
|
|
|
@@ -235,7 +236,7 @@ export function productLd(
|
|
|
235
236
|
...(images.length ? { image: images } : {}),
|
|
236
237
|
...(p.vendor ? { brand: { "@type": "Brand", name: p.vendor } } : {}),
|
|
237
238
|
...(p.product_type ? { category: p.product_type } : {}),
|
|
238
|
-
offers: {
|
|
239
|
+
...(!hidesPublicCatalogPrices(tenant) && { offers: {
|
|
239
240
|
"@type": "AggregateOffer",
|
|
240
241
|
priceCurrency: p.price_range.currency,
|
|
241
242
|
lowPrice: p.price_range.min.toFixed(2),
|
|
@@ -245,7 +246,7 @@ export function productLd(
|
|
|
245
246
|
? "https://schema.org/InStock"
|
|
246
247
|
: "https://schema.org/OutOfStock",
|
|
247
248
|
offers,
|
|
248
|
-
},
|
|
249
|
+
} }),
|
|
249
250
|
};
|
|
250
251
|
}
|
|
251
252
|
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import type { APIContext } from "astro";
|
|
2
|
+
import {
|
|
3
|
+
catalogAdmissionMessage,
|
|
4
|
+
catalogAdmissionWindow,
|
|
5
|
+
resolveShopperAccessPolicy,
|
|
6
|
+
} from "@tot/public-runtime/declared-tenant-config";
|
|
7
|
+
import { readEnv } from "@/lib/publication/shared/env";
|
|
8
|
+
import { getScopedShopper, isApprovedShopper, type ScopedShopper } from "./session";
|
|
9
|
+
import { resolveShopperScope, shopperCookiePath, type ShopperScope } from "./scope";
|
|
10
|
+
|
|
11
|
+
export const SHOPPER_CATALOG_COOKIE = "tot_shopper_catalog";
|
|
12
|
+
const ADMISSION_SECONDS = 120;
|
|
13
|
+
const encoder = new TextEncoder();
|
|
14
|
+
|
|
15
|
+
async function catalogKey(scope: ShopperScope): Promise<CryptoKey | null> {
|
|
16
|
+
const raw = await readEnv("SHOPPER_CATALOG_ADMISSION_KEYS");
|
|
17
|
+
if (!raw) return null;
|
|
18
|
+
let keys: unknown;
|
|
19
|
+
try {
|
|
20
|
+
keys = JSON.parse(raw);
|
|
21
|
+
} catch (error) {
|
|
22
|
+
if (error instanceof SyntaxError) return null;
|
|
23
|
+
throw error;
|
|
24
|
+
}
|
|
25
|
+
const name = `${scope.tenantId}:${scope.stage}`;
|
|
26
|
+
if (!keys || typeof keys !== "object" || !Object.hasOwn(keys, name)) return null;
|
|
27
|
+
const key = (keys as Record<string, unknown>)[name];
|
|
28
|
+
if (typeof key !== "string" || !/^[a-f0-9]{64}$/.test(key)) return null;
|
|
29
|
+
return crypto.subtle.importKey("raw", encoder.encode(key), { name: "HMAC", hash: "SHA-256" }, false, ["sign", "verify"]);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export async function hasShopperCatalogAdmissionKey(scope: ShopperScope): Promise<boolean> {
|
|
33
|
+
return (await catalogKey(scope)) !== null;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export async function verifyShopperCatalogAdmission(
|
|
37
|
+
token: string, scope: ShopperScope, host: string, now = Math.floor(Date.now() / 1000),
|
|
38
|
+
): Promise<boolean> {
|
|
39
|
+
const window = catalogAdmissionWindow(token, now);
|
|
40
|
+
if (!window?.mac) return false;
|
|
41
|
+
const key = await catalogKey(scope);
|
|
42
|
+
if (!key) return false;
|
|
43
|
+
const bytes = Uint8Array.from(window.mac.match(/../g) ?? [], octet => Number.parseInt(octet, 16));
|
|
44
|
+
const message = catalogAdmissionMessage(scope.tenantId, scope.stage, host, window.issued, window.expires);
|
|
45
|
+
return await crypto.subtle.verify("HMAC", key, bytes, encoder.encode(message));
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** The supplied shopper is the just-authenticated, freshly read result of session issuance. */
|
|
49
|
+
export async function setShopperCatalogAdmission(context: APIContext, shopper?: ScopedShopper): Promise<boolean> {
|
|
50
|
+
const scope = resolveShopperScope(context.locals);
|
|
51
|
+
if (!scope || !context.locals.requestOrigin || resolveShopperAccessPolicy(context.locals.tenant).mode !== "closed_store") return false;
|
|
52
|
+
const approved = shopper ?? await getScopedShopper(context);
|
|
53
|
+
if (!isApprovedShopper(approved) || approved.scope.tenantId !== scope.tenantId || approved.scope.stage !== scope.stage) return false;
|
|
54
|
+
const key = await catalogKey(scope);
|
|
55
|
+
if (!key) return false;
|
|
56
|
+
const issued = Math.floor(Date.now() / 1000);
|
|
57
|
+
const expires = Math.min(issued + ADMISSION_SECONDS, Math.floor(approved.expiresAt / 1000));
|
|
58
|
+
if (expires <= issued) return false;
|
|
59
|
+
const host = new URL(context.locals.requestOrigin).host;
|
|
60
|
+
const message = catalogAdmissionMessage(scope.tenantId, scope.stage, host, issued, expires);
|
|
61
|
+
const sig = await crypto.subtle.sign("HMAC", key, encoder.encode(message));
|
|
62
|
+
const hex = Array.from(new Uint8Array(sig), byte => byte.toString(16).padStart(2, "0")).join("");
|
|
63
|
+
context.cookies.set(SHOPPER_CATALOG_COOKIE, `v1.${issued}.${expires}.${hex}`, {
|
|
64
|
+
path: shopperCookiePath(context.locals),
|
|
65
|
+
httpOnly: true,
|
|
66
|
+
secure: true,
|
|
67
|
+
sameSite: "lax",
|
|
68
|
+
maxAge: expires - issued,
|
|
69
|
+
});
|
|
70
|
+
return true;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export function clearShopperCatalogAdmission(context: APIContext): void {
|
|
74
|
+
context.cookies.delete(SHOPPER_CATALOG_COOKIE, { path: shopperCookiePath(context.locals), secure: true, httpOnly: true, sameSite: "lax" });
|
|
75
|
+
}
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import { hmacSha256Hex, timingSafeEqual } from "@/lib/activity/ingestAuth";
|
|
2
|
+
import { sha256Hex } from "@tot/public-runtime";
|
|
3
|
+
import type { Queryable } from "@/lib/catalog/d1/catalog";
|
|
4
|
+
import { readEnv } from "@/lib/publication/shared/env";
|
|
5
|
+
import { isApprovedShopper, isShopperToken, randomShopperToken, readShopperBySessionRef, type ScopedShopper } from "./session";
|
|
6
|
+
import type { ShopperScope } from "./scope";
|
|
7
|
+
|
|
8
|
+
const HEX = /^[a-f0-9]{64}$/;
|
|
9
|
+
const PROOF = /^v2\.([a-f0-9-]{36})\.(\d{13})\.([a-f0-9]{64})$/;
|
|
10
|
+
const VERIFICATION_REF = /^(sandbox-cleared:)?(shp_[A-Za-z0-9_-]{22})\.([a-f0-9]{32})$/;
|
|
11
|
+
|
|
12
|
+
async function verificationMac(shopper: ScopedShopper, value: string): Promise<string | null> {
|
|
13
|
+
const secret = await readEnv("TOT_SECRET_KEY");
|
|
14
|
+
if (!secret) return null;
|
|
15
|
+
const signed = JSON.stringify(["shopper-verification/v1", shopper.scope.tenantId, shopper.scope.stage, shopper.shopperId, shopper.sessionId, value]);
|
|
16
|
+
return (await hmacSha256Hex(secret, signed)).slice(0, 32);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export async function newShopperVerificationRef(shopper: ScopedShopper, sandbox = false): Promise<string | null> {
|
|
20
|
+
const value = `${sandbox ? "sandbox-cleared:" : ""}shp_${randomShopperToken(16)}`;
|
|
21
|
+
const mac = await verificationMac(shopper, value);
|
|
22
|
+
return mac ? `${value}.${mac}` : null;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export async function shopperVerificationRefMatches(shopper: ScopedShopper, ref: string): Promise<boolean> {
|
|
26
|
+
const match = VERIFICATION_REF.exec(ref);
|
|
27
|
+
if (!match) return false;
|
|
28
|
+
const mac = await verificationMac(shopper, (match[1] ?? "") + match[2]);
|
|
29
|
+
return mac !== null && timingSafeEqual(mac, match[3]!);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface ShopperCheckoutWire {
|
|
33
|
+
version: 2;
|
|
34
|
+
proof: string;
|
|
35
|
+
providerCartSelectorDigest: string;
|
|
36
|
+
buyerConfirmation: string;
|
|
37
|
+
licensedDestinationDigest?: string;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function readShopperCheckoutWire(value: unknown): ShopperCheckoutWire | null {
|
|
41
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
|
|
42
|
+
const wire = value as Record<string, unknown>;
|
|
43
|
+
if (Object.keys(wire).some(key => !["version", "proof", "providerCartSelectorDigest", "buyerConfirmation", "licensedDestinationDigest"].includes(key)) ||
|
|
44
|
+
wire.version !== 2 || typeof wire.proof !== "string" || !PROOF.test(wire.proof) || !isShopperToken(wire.buyerConfirmation) ||
|
|
45
|
+
typeof wire.providerCartSelectorDigest !== "string" || !HEX.test(wire.providerCartSelectorDigest) ||
|
|
46
|
+
("licensedDestinationDigest" in wire && (typeof wire.licensedDestinationDigest !== "string" || !HEX.test(wire.licensedDestinationDigest)))) return null;
|
|
47
|
+
return wire as unknown as ShopperCheckoutWire;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export const shopperCheckoutContextDigest = (wire: ShopperCheckoutWire): Promise<string> => sha256Hex(JSON.stringify([
|
|
51
|
+
"shopper-checkout-context/v2", wire.version, wire.proof, wire.providerCartSelectorDigest, wire.buyerConfirmation, wire.licensedDestinationDigest ?? null,
|
|
52
|
+
]));
|
|
53
|
+
|
|
54
|
+
function signedMaterial(shopper: ScopedShopper, nonce: string, expiresAt: number): string {
|
|
55
|
+
return JSON.stringify(["shopper-checkout/v2", shopper.scope.tenantId, shopper.scope.stage, shopper.shopperId, shopper.sessionId, nonce, expiresAt]);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** The provider cart selector is shared by cart links and identifies the cart only. */
|
|
59
|
+
export const checkoutProviderCartSelectorDigest = (proof: string, selector: string): Promise<string> =>
|
|
60
|
+
hmacSha256Hex(proof, JSON.stringify(["shopper-provider-cart-selector/v2", selector]));
|
|
61
|
+
|
|
62
|
+
const LIVE_SHOPPER = `SELECT 1 FROM shopper_sessions s JOIN shopper_accounts a
|
|
63
|
+
ON a.tenant_id = s.tenant_id AND a.stage = s.stage AND a.id = s.shopper_id
|
|
64
|
+
LEFT JOIN buyer_orgs o ON o.tenant_id = a.tenant_id AND o.stage = a.stage AND o.id = a.org_id
|
|
65
|
+
WHERE s.tenant_id = ? AND s.stage = ? AND s.id = ? AND s.shopper_id = ? AND s.expires_at > ? AND s.revoked_at IS NULL
|
|
66
|
+
AND a.approval_status = 'approved' AND (a.org_id IS NULL OR o.approval_status = 'approved')`;
|
|
67
|
+
|
|
68
|
+
interface ProofRow {
|
|
69
|
+
shopper_id: string;
|
|
70
|
+
session_ref: string;
|
|
71
|
+
expires_at: number;
|
|
72
|
+
provider_cart_selector_digest: string;
|
|
73
|
+
buyer_confirmation_digest: string;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Only called after signature, caller, request body digest and scope are authenticated. */
|
|
77
|
+
export async function verifyCheckoutProof(db: Queryable, scope: ShopperScope, wire: ShopperCheckoutWire, now = Date.now()) {
|
|
78
|
+
const match = PROOF.exec(wire.proof);
|
|
79
|
+
const secret = await readEnv("TOT_SECRET_KEY");
|
|
80
|
+
if (!match || !secret) return null;
|
|
81
|
+
const nonce = match[1]!;
|
|
82
|
+
const deadline = match[2]!;
|
|
83
|
+
const presented = match[3]!;
|
|
84
|
+
const expiresAt = Number(deadline);
|
|
85
|
+
if (!Number.isSafeInteger(expiresAt) || expiresAt <= now) return null;
|
|
86
|
+
const [proofDigest, buyerConfirmationDigest] = await Promise.all([sha256Hex(wire.proof), sha256Hex(wire.buyerConfirmation)]);
|
|
87
|
+
const row = await db.first<ProofRow>(`SELECT shopper_id, session_ref, expires_at, provider_cart_selector_digest, buyer_confirmation_digest
|
|
88
|
+
FROM shopper_checkout_proofs WHERE tenant_id = ? AND stage = ? AND nonce = ? AND signed_token_digest = ?`,
|
|
89
|
+
scope.tenantId, scope.stage, nonce, proofDigest);
|
|
90
|
+
if (!row || row.expires_at !== expiresAt ||
|
|
91
|
+
!timingSafeEqual(row.provider_cart_selector_digest, wire.providerCartSelectorDigest) ||
|
|
92
|
+
!timingSafeEqual(row.buyer_confirmation_digest, buyerConfirmationDigest)) return null;
|
|
93
|
+
const shopper = await readShopperBySessionRef(scope, row.session_ref, now, db);
|
|
94
|
+
if (!isApprovedShopper(shopper) || shopper.shopperId !== row.shopper_id) return null;
|
|
95
|
+
const expected = await hmacSha256Hex(secret, signedMaterial(shopper, nonce, expiresAt));
|
|
96
|
+
if (!timingSafeEqual(presented, expected)) return null;
|
|
97
|
+
return { shopper, nonce, proofDigest, buyerConfirmationDigest, expiresAt };
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export async function bindCheckoutSnapshot(db: Queryable, proof: NonNullable<Awaited<ReturnType<typeof verifyCheckoutProof>>>, providerCartId: string, providerCartDigest: string, now = Date.now()): Promise<boolean> {
|
|
101
|
+
const { shopper, nonce, proofDigest, buyerConfirmationDigest } = proof;
|
|
102
|
+
const { tenantId, stage } = shopper.scope;
|
|
103
|
+
const rows = await db.all(`UPDATE shopper_checkout_proofs SET provider_cart_id = ?, provider_cart_digest = ?, bound_at = COALESCE(bound_at, ?)
|
|
104
|
+
WHERE tenant_id = ? AND stage = ? AND nonce = ? AND signed_token_digest = ? AND buyer_confirmation_digest = ? AND expires_at > ?
|
|
105
|
+
AND (bound_at IS NULL OR (provider_cart_id = ? AND provider_cart_digest = ?)) AND EXISTS (${LIVE_SHOPPER})
|
|
106
|
+
RETURNING nonce`, providerCartId, providerCartDigest, now, tenantId, stage, nonce, proofDigest, buyerConfirmationDigest, now, providerCartId, providerCartDigest,
|
|
107
|
+
tenantId, stage, shopper.sessionId, shopper.shopperId, now);
|
|
108
|
+
return rows.length === 1;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** Recheck purchase authority inside the same D1 transaction as authorization and stock holds. */
|
|
112
|
+
export function shopperCheckoutAuthorizationGuard(
|
|
113
|
+
proof: NonNullable<Awaited<ReturnType<typeof verifyCheckoutProof>>>, providerCartId: string,
|
|
114
|
+
providerCartDigest: string, orgKybUpdatedAt: number | undefined, now = Date.now(),
|
|
115
|
+
) {
|
|
116
|
+
const { shopper, nonce, proofDigest, buyerConfirmationDigest } = proof;
|
|
117
|
+
const { tenantId, stage } = shopper.scope;
|
|
118
|
+
return {
|
|
119
|
+
sql: `SELECT 1 FROM shopper_checkout_proofs p
|
|
120
|
+
JOIN shopper_sessions s ON s.tenant_id = p.tenant_id AND s.stage = p.stage AND s.id = p.session_ref
|
|
121
|
+
JOIN shopper_accounts a ON a.tenant_id = s.tenant_id AND a.stage = s.stage AND a.id = s.shopper_id
|
|
122
|
+
LEFT JOIN buyer_orgs o ON o.tenant_id = a.tenant_id AND o.stage = a.stage AND o.id = a.org_id
|
|
123
|
+
WHERE p.tenant_id = ? AND p.stage = ? AND p.nonce = ? AND p.signed_token_digest = ? AND p.buyer_confirmation_digest = ? AND p.expires_at > ?
|
|
124
|
+
AND p.provider_cart_id = ? AND p.provider_cart_digest = ? AND s.expires_at > ? AND s.revoked_at IS NULL
|
|
125
|
+
AND a.approval_status = 'approved' AND a.checkout_lock_mode = 'standard' AND a.org_id IS ?
|
|
126
|
+
AND (a.org_id IS NULL OR o.approval_status = 'approved') AND COALESCE(a.tier_id, o.tier_id) IS ?
|
|
127
|
+
${orgKybUpdatedAt === undefined ? "" : `AND o.kyb_status = 'verified' AND o.updated_at = ?
|
|
128
|
+
AND o.key_kid IS NOT NULL AND o.kyb_verification_ref IS NOT NULL AND o.licensed_addresses_ct IS NOT NULL
|
|
129
|
+
AND julianday(o.not_after) > julianday('now')`}`,
|
|
130
|
+
params: [tenantId, stage, nonce, proofDigest, buyerConfirmationDigest, now, providerCartId, providerCartDigest, now, shopper.orgId, shopper.tierId,
|
|
131
|
+
...(orgKybUpdatedAt === undefined ? [] : [orgKybUpdatedAt])],
|
|
132
|
+
};
|
|
133
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { Queryable } from "@/lib/catalog/d1/catalog";
|
|
2
|
+
import type { ScopedShopper } from "./session";
|
|
3
|
+
|
|
4
|
+
export async function hasShopperOrgKyb(_db: Queryable, _shopper: ScopedShopper, _now?: Date): Promise<boolean> {
|
|
5
|
+
return false;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export async function shopperOrgKyb(
|
|
9
|
+
_db: Queryable, _shopper: ScopedShopper, _destinationDigest: string | undefined, _totalMinor: number, _now?: Date,
|
|
10
|
+
): Promise<{ expiresAt: string; updatedAt: number } | null> {
|
|
11
|
+
return null;
|
|
12
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import {
|
|
2
|
+
isPublicCatalogProduct, normalizePurchaseOptions, priceForPurchaseOption, resolveMembershipRule,
|
|
3
|
+
type CatalogProduct, type CatalogVariant, type TenantConfig,
|
|
4
|
+
} from "@tot/public-runtime";
|
|
5
|
+
import { resolveMemberContext } from "@/lib/membership/eligibility";
|
|
6
|
+
|
|
7
|
+
export function shopperTierAvailable(tenant: TenantConfig, tierId: string): boolean {
|
|
8
|
+
return resolveMembershipRule(resolveMemberContext({ memberTierId: tierId }), tenant.commerce?.membership) !== undefined;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export function shopperCatalogProduct(tenant: TenantConfig, product: CatalogProduct | null): product is CatalogProduct {
|
|
12
|
+
return !!product && !!tenant.tot_data_scope && product.tenant_id === tenant.tot_data_scope && isPublicCatalogProduct(product);
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function shopperVariantPrice(tenant: TenantConfig, product: CatalogProduct, variant: CatalogVariant, tierId: string | null) {
|
|
16
|
+
if (tierId && !shopperTierAvailable(tenant, tierId)) return null;
|
|
17
|
+
const option = normalizePurchaseOptions(product).find(candidate => candidate.kind === "one_time");
|
|
18
|
+
if (!option || variant.product_id !== product.id || variant.tenant_id !== product.tenant_id) return null;
|
|
19
|
+
const priced = priceForPurchaseOption(variant.price, option, {
|
|
20
|
+
member: resolveMemberContext({ memberTierId: tierId }),
|
|
21
|
+
program: tenant.commerce?.membership,
|
|
22
|
+
});
|
|
23
|
+
if (!Number.isFinite(priced.price) || priced.price < 0) return null;
|
|
24
|
+
return { id: variant.id, title: variant.title, available: variant.inventory.available, price: priced.price, compareAtPrice: priced.compareAt ?? variant.compare_at_price ?? null, currency: variant.currency };
|
|
25
|
+
}
|