@tokenoftrust/storefront-runner 7.7.3 → 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/assets/captured-original-serve.ts +61 -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 +43 -13
- 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 -15
- 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
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import type { APIContext } from "astro";
|
|
2
|
+
import type { TenantConfig } from "@tot/public-runtime";
|
|
3
|
+
import { resolveShopperAccessPolicy } from "@tot/public-runtime/declared-tenant-config";
|
|
4
|
+
import { getScopedShopper } from "./session";
|
|
5
|
+
import { isShopperOrigin } from "./scope";
|
|
6
|
+
|
|
7
|
+
export function requiresShopperPurchase(tenant: TenantConfig): boolean {
|
|
8
|
+
const policy = resolveShopperAccessPolicy(tenant);
|
|
9
|
+
return policy.mode !== "open" || policy.hidePricesForGuests || policy.b2bKybOrgVerification;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export function shopperJson(body: unknown, status = 200): Response {
|
|
13
|
+
return Response.json(body, { status, headers: {
|
|
14
|
+
"cache-control": "private, no-store",
|
|
15
|
+
"x-robots-tag": "noindex, nofollow",
|
|
16
|
+
} });
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export type ShopperPurchaseAccess =
|
|
20
|
+
| { ok: true; shopper: Awaited<ReturnType<typeof getScopedShopper>> }
|
|
21
|
+
| { ok: false; response: Response };
|
|
22
|
+
|
|
23
|
+
export async function shopperPurchaseAccess(
|
|
24
|
+
context: APIContext, declaration?: "shopper-session" | "shopper-approved",
|
|
25
|
+
): Promise<ShopperPurchaseAccess> {
|
|
26
|
+
const deny = (error: string, status: number): ShopperPurchaseAccess => ({
|
|
27
|
+
ok: false, response: shopperJson({ ok: false, error }, status),
|
|
28
|
+
});
|
|
29
|
+
try {
|
|
30
|
+
if (!context.locals.tenant) return deny("store_unavailable", 503);
|
|
31
|
+
if (!declaration && !requiresShopperPurchase(context.locals.tenant)) return { ok: true, shopper: null };
|
|
32
|
+
if (context.request.method === "POST" && !isShopperOrigin(context)) return deny("origin_denied", 403);
|
|
33
|
+
const shopper = await getScopedShopper(context);
|
|
34
|
+
if (!shopper) return deny("shopper_sign_in_required", 401);
|
|
35
|
+
if (declaration !== "shopper-session" && shopper.approvalStatus !== "approved") return deny("shopper_approval_required", 403);
|
|
36
|
+
return { ok: true, shopper };
|
|
37
|
+
} catch {
|
|
38
|
+
return deny("shopper_authority_unavailable", 503);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export async function withShopperPurchase(context: APIContext, run: () => Promise<Response>): Promise<Response> {
|
|
43
|
+
const access = await shopperPurchaseAccess(context);
|
|
44
|
+
return access.ok ? run() : access.response;
|
|
45
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import type { APIContext } from "astro";
|
|
2
|
+
import { commerceTenantId } from "@tot/public-runtime";
|
|
3
|
+
import { safeNext } from "@/lib/access/auth/safeNext";
|
|
4
|
+
|
|
5
|
+
/** Shopper routes use tenant-stage and shopper or interactive-owner authority. */
|
|
6
|
+
export const SHOPPER_ADMISSION_CLASSES = [
|
|
7
|
+
"shopper-public", "shopper-origin", "shopper-session", "shopper-approved",
|
|
8
|
+
"shopper-owner-read", "shopper-owner-mutation",
|
|
9
|
+
] as const;
|
|
10
|
+
export type ShopperAdmissionClass = (typeof SHOPPER_ADMISSION_CLASSES)[number];
|
|
11
|
+
export type ShopperRouteAdmission = {
|
|
12
|
+
GET?: Exclude<ShopperAdmissionClass, "shopper-origin" | "shopper-owner-mutation">;
|
|
13
|
+
POST?: Extract<ShopperAdmissionClass, "shopper-origin" | "shopper-owner-mutation">;
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
export interface ShopperScope {
|
|
17
|
+
tenantId: string;
|
|
18
|
+
stage: "preview" | "publication";
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function resolveShopperScope(
|
|
22
|
+
locals: Pick<App.Locals, "tenant" | "customizationEnv">,
|
|
23
|
+
): ShopperScope | null {
|
|
24
|
+
const tenantId = locals.tenant ? commerceTenantId(locals.tenant) : "";
|
|
25
|
+
const stage = locals.customizationEnv === "test"
|
|
26
|
+
? "preview"
|
|
27
|
+
: locals.customizationEnv === "live" ? "publication" : null;
|
|
28
|
+
return tenantId && stage ? { tenantId, stage } : null;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function isShopperOrigin(context: Pick<APIContext, "request" | "locals">): boolean {
|
|
32
|
+
const origin = context.locals.requestOrigin;
|
|
33
|
+
return !!origin && origin === context.request.headers.get("origin");
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function admitShopperScope(
|
|
37
|
+
context: Pick<APIContext, "request" | "locals">,
|
|
38
|
+
declaration: "shopper-public" | "shopper-origin",
|
|
39
|
+
): ShopperScope | null {
|
|
40
|
+
if (declaration === "shopper-public" && context.request.method === "GET") return resolveShopperScope(context.locals);
|
|
41
|
+
if (declaration === "shopper-origin" && context.request.method === "POST" && isShopperOrigin(context)) {
|
|
42
|
+
return resolveShopperScope(context.locals);
|
|
43
|
+
}
|
|
44
|
+
return null;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function shopperCookiePath(locals: Pick<App.Locals, "apiBasePath">): string {
|
|
48
|
+
return locals.apiBasePath || "/";
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function shopperReturnPath(value: string | null, base: string): string {
|
|
52
|
+
const normalized = new URL(safeNext(value), "https://shopper.invalid");
|
|
53
|
+
const path = safeNext(normalized.pathname + normalized.search);
|
|
54
|
+
return !base || path === base || path.startsWith(`${base}/`) || path.startsWith(`${base}?`) ? path : base + path;
|
|
55
|
+
}
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
import type { APIContext } from "astro";
|
|
2
|
+
import { sha256Hex } from "@tot/public-runtime";
|
|
3
|
+
import { fromD1, type Queryable } from "@/lib/catalog/d1/catalog";
|
|
4
|
+
import { CART_SESSION_COOKIE, PROPOSAL_MARKER_COOKIE, cartSessionCookiePath } from "@/lib/checkout/commerce/cartSession";
|
|
5
|
+
import { readD1, readKv } from "@/lib/publication/shared/env";
|
|
6
|
+
import { resolveShopperScope, shopperCookiePath, type ShopperScope } from "./scope";
|
|
7
|
+
|
|
8
|
+
export const SHOPPER_SESSION_COOKIE = "tot_shopper_session";
|
|
9
|
+
const SESSION_PREFIX = "shopper_sess:";
|
|
10
|
+
export const SHOPPER_SESSION_TTL_SECONDS = 7 * 24 * 3600;
|
|
11
|
+
export type ShopperApproval = "pending" | "approved" | "rejected" | "suspended";
|
|
12
|
+
|
|
13
|
+
export interface ScopedShopper {
|
|
14
|
+
scope: ShopperScope;
|
|
15
|
+
sessionId: string;
|
|
16
|
+
shopperId: string;
|
|
17
|
+
expiresAt: number;
|
|
18
|
+
approvalStatus: ShopperApproval;
|
|
19
|
+
orgId: string | null;
|
|
20
|
+
orgRole: "owner" | "buyer" | null;
|
|
21
|
+
orgApprovalStatus: ShopperApproval | null;
|
|
22
|
+
tierId: string | null;
|
|
23
|
+
checkoutLockMode: "standard" | "require_step_up";
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
interface SessionHint extends ShopperScope {
|
|
27
|
+
expiresAt: number;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
type SessionContext = Pick<APIContext, "locals" | "cookies">;
|
|
31
|
+
|
|
32
|
+
export function randomShopperToken(bytes = 32): string {
|
|
33
|
+
const octets = crypto.getRandomValues(new Uint8Array(bytes));
|
|
34
|
+
return btoa(String.fromCharCode(...octets)).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function isShopperToken(value: unknown): value is string {
|
|
38
|
+
return typeof value === "string" && /^[\w-]{43}$/.test(value);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export async function shopperDb(): Promise<Queryable | null> {
|
|
42
|
+
const db = await readD1("STOREFRONT_APPS_DB");
|
|
43
|
+
return db ? fromD1(db) : null;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function isApprovedShopper(shopper: ScopedShopper | null): shopper is ScopedShopper & { approvalStatus: "approved" } {
|
|
47
|
+
return shopper?.approvalStatus === "approved" && (!shopper.orgId || shopper.orgApprovalStatus === "approved");
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function refuseSessionRead(reason: "database-unavailable" | "hint-unavailable" | "hint-invalid"): null {
|
|
51
|
+
console.warn("shopper-session-read-refused", { reason });
|
|
52
|
+
return null;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function parseSessionHint(raw: string): SessionHint | null {
|
|
56
|
+
try {
|
|
57
|
+
const hint = JSON.parse(raw) as SessionHint | null;
|
|
58
|
+
if (!hint || typeof hint.tenantId !== "string" || (hint.stage !== "preview" && hint.stage !== "publication") ||
|
|
59
|
+
!Number.isSafeInteger(hint.expiresAt)) return refuseSessionRead("hint-invalid");
|
|
60
|
+
return hint;
|
|
61
|
+
} catch (error) {
|
|
62
|
+
if (error instanceof SyntaxError) return refuseSessionRead("hint-invalid");
|
|
63
|
+
throw error;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** For a provider call only after its signature and shopper proof have been verified. */
|
|
68
|
+
export async function readShopperBySessionRef(
|
|
69
|
+
scope: ShopperScope, sessionId: string, now = Date.now(), database?: Queryable,
|
|
70
|
+
): Promise<ScopedShopper | null> {
|
|
71
|
+
if (!/^[a-f0-9]{64}$/.test(sessionId) || !Number.isFinite(now)) return null;
|
|
72
|
+
try {
|
|
73
|
+
const db = database ?? await shopperDb();
|
|
74
|
+
if (!db) return refuseSessionRead("database-unavailable");
|
|
75
|
+
const row = await db.first<Omit<ScopedShopper, "scope" | "sessionId">>(
|
|
76
|
+
`SELECT a.id AS shopperId, s.expires_at AS expiresAt,
|
|
77
|
+
CASE WHEN a.approval_status = 'approved' AND a.org_id IS NOT NULL
|
|
78
|
+
THEN COALESCE(o.approval_status, 'suspended') ELSE a.approval_status END AS approvalStatus,
|
|
79
|
+
a.org_id AS orgId, a.org_role AS orgRole, o.approval_status AS orgApprovalStatus,
|
|
80
|
+
COALESCE(a.tier_id, o.tier_id) AS tierId, a.checkout_lock_mode AS checkoutLockMode
|
|
81
|
+
FROM shopper_sessions s
|
|
82
|
+
JOIN shopper_accounts a ON a.tenant_id = s.tenant_id AND a.stage = s.stage AND a.id = s.shopper_id
|
|
83
|
+
LEFT JOIN buyer_orgs o ON o.tenant_id = a.tenant_id AND o.stage = a.stage AND o.id = a.org_id
|
|
84
|
+
WHERE s.tenant_id = ? AND s.stage = ? AND s.id = ? AND s.revoked_at IS NULL AND s.expires_at > ?`,
|
|
85
|
+
scope.tenantId, scope.stage, sessionId, now,
|
|
86
|
+
);
|
|
87
|
+
return row ? { ...row, scope, sessionId } : null;
|
|
88
|
+
} catch {
|
|
89
|
+
return refuseSessionRead("database-unavailable");
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export async function readScopedShopper(
|
|
94
|
+
scope: ShopperScope, token: string, now = Date.now(),
|
|
95
|
+
deps: { db?: Queryable; kv?: KVNamespace } = {},
|
|
96
|
+
): Promise<ScopedShopper | null> {
|
|
97
|
+
if (!isShopperToken(token) || !Number.isFinite(now)) return null;
|
|
98
|
+
try {
|
|
99
|
+
const kv = deps.kv ?? await readKv("SESSION");
|
|
100
|
+
if (!kv) return refuseSessionRead("hint-unavailable");
|
|
101
|
+
const raw = await kv.get(SESSION_PREFIX + token);
|
|
102
|
+
if (!raw) return null;
|
|
103
|
+
const hint = parseSessionHint(raw);
|
|
104
|
+
if (!hint || hint.tenantId !== scope.tenantId || hint.stage !== scope.stage || hint.expiresAt <= now) return null;
|
|
105
|
+
return readShopperBySessionRef(scope, await sha256Hex(token), now, deps.db);
|
|
106
|
+
} catch {
|
|
107
|
+
return refuseSessionRead("hint-unavailable");
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export async function getScopedShopper(context: SessionContext): Promise<ScopedShopper | null> {
|
|
112
|
+
const scope = resolveShopperScope(context.locals);
|
|
113
|
+
const id = context.cookies.get(SHOPPER_SESSION_COOKIE)?.value;
|
|
114
|
+
return scope && id ? readScopedShopper(scope, id) : null;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export async function newShopperSession(scope: ShopperScope, now: number) {
|
|
118
|
+
const token = randomShopperToken();
|
|
119
|
+
return { scope, token, id: await sha256Hex(token), expiresAt: now + SHOPPER_SESSION_TTL_SECONDS * 1000 };
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
type NewShopperSession = Awaited<ReturnType<typeof newShopperSession>>;
|
|
123
|
+
|
|
124
|
+
/** The hint alone grants nothing. The D1 session is created in the same batch as proof consumption. */
|
|
125
|
+
export async function writeShopperSessionHint(session: NewShopperSession, kv: KVNamespace): Promise<void> {
|
|
126
|
+
await kv.put(SESSION_PREFIX + session.token, JSON.stringify({ ...session.scope, expiresAt: session.expiresAt }), {
|
|
127
|
+
expirationTtl: SHOPPER_SESSION_TTL_SECONDS,
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export function setShopperSessionCookie(context: SessionContext, id: string): void {
|
|
132
|
+
clearShopperCheckoutCookies(context);
|
|
133
|
+
context.cookies.set(SHOPPER_SESSION_COOKIE, id, {
|
|
134
|
+
path: shopperCookiePath(context.locals), httpOnly: true, secure: true, sameSite: "lax",
|
|
135
|
+
maxAge: SHOPPER_SESSION_TTL_SECONDS,
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function clearShopperCheckoutCookies(context: SessionContext): void {
|
|
140
|
+
const path = cartSessionCookiePath(context.locals.apiBasePath ?? context.locals.basePath ?? "");
|
|
141
|
+
const options = { path, httpOnly: true, secure: true, sameSite: "lax" as const };
|
|
142
|
+
context.cookies.delete(CART_SESSION_COOKIE, options);
|
|
143
|
+
context.cookies.delete(PROPOSAL_MARKER_COOKIE, options);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
export async function revokeScopedShopper(context: SessionContext, now = Date.now()): Promise<boolean> {
|
|
147
|
+
const scope = resolveShopperScope(context.locals);
|
|
148
|
+
const id = context.cookies.get(SHOPPER_SESSION_COOKIE)?.value;
|
|
149
|
+
context.cookies.delete(SHOPPER_SESSION_COOKIE, { path: shopperCookiePath(context.locals) });
|
|
150
|
+
clearShopperCheckoutCookies(context);
|
|
151
|
+
if (!isShopperToken(id)) return true;
|
|
152
|
+
if (!scope) return false;
|
|
153
|
+
try {
|
|
154
|
+
const db = await shopperDb();
|
|
155
|
+
if (!db) return false;
|
|
156
|
+
const revoked = await db.first(
|
|
157
|
+
`UPDATE shopper_sessions SET revoked_at = ?
|
|
158
|
+
WHERE tenant_id = ? AND stage = ? AND id = ? AND revoked_at IS NULL RETURNING id`,
|
|
159
|
+
now, scope.tenantId, scope.stage, await sha256Hex(id),
|
|
160
|
+
);
|
|
161
|
+
if (revoked) {
|
|
162
|
+
try {
|
|
163
|
+
const kv = await readKv("SESSION");
|
|
164
|
+
await kv?.delete(SESSION_PREFIX + id);
|
|
165
|
+
} catch {
|
|
166
|
+
// The durable revocation remains authoritative.
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
return true;
|
|
170
|
+
} catch {
|
|
171
|
+
return false;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import type { shopperVariantPrice } from "./pricing.js";
|
|
2
|
+
|
|
3
|
+
type PricedVariant = NonNullable<ReturnType<typeof shopperVariantPrice>>;
|
|
4
|
+
|
|
5
|
+
function isPricedVariant(input: unknown): input is PricedVariant {
|
|
6
|
+
if (typeof input !== "object" || input === null) return false;
|
|
7
|
+
return "id" in input && typeof input.id === "string" &&
|
|
8
|
+
"title" in input && typeof input.title === "string" &&
|
|
9
|
+
"available" in input && typeof input.available === "boolean" &&
|
|
10
|
+
"currency" in input && typeof input.currency === "string" &&
|
|
11
|
+
"price" in input && typeof input.price === "number" && Number.isFinite(input.price) &&
|
|
12
|
+
"compareAtPrice" in input &&
|
|
13
|
+
(input.compareAtPrice === null || (typeof input.compareAtPrice === "number" && Number.isFinite(input.compareAtPrice)));
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
async function readPricing(url: URL): Promise<PricedVariant[]> {
|
|
17
|
+
const response = await fetch(url, { credentials: "same-origin", headers: { Accept: "application/json" } });
|
|
18
|
+
if (!response.ok) return [];
|
|
19
|
+
const reply: unknown = await response.json();
|
|
20
|
+
if (typeof reply !== "object" || reply === null || !("ok" in reply) || reply.ok !== true ||
|
|
21
|
+
!("variants" in reply) || !Array.isArray(reply.variants) || !reply.variants.every(isPricedVariant)) return [];
|
|
22
|
+
return reply.variants;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export async function mountShopperPricing(region: HTMLElement): Promise<void> {
|
|
26
|
+
const { pricingUrl, purchaseUrl, shopperProduct, locale } = region.dataset;
|
|
27
|
+
const cta = region.querySelector("[data-shopper-pricing-cta]");
|
|
28
|
+
const template = region.querySelector<HTMLTemplateElement>("template");
|
|
29
|
+
const form = template?.content.querySelector("form")?.cloneNode(true) as HTMLFormElement | undefined;
|
|
30
|
+
const select = form?.querySelector<HTMLSelectElement>("select[name=variantId]");
|
|
31
|
+
const buy = form?.querySelector<HTMLButtonElement>("button[type=submit]");
|
|
32
|
+
const product = form?.querySelector<HTMLInputElement>("input[name=productHandle]");
|
|
33
|
+
const priceText = form?.querySelector<HTMLElement>("[data-shopper-price]");
|
|
34
|
+
if (!pricingUrl || !purchaseUrl || !shopperProduct || !cta || !form || !select || !buy || !product || !priceText) return;
|
|
35
|
+
|
|
36
|
+
try {
|
|
37
|
+
const url = new URL(pricingUrl, location.origin);
|
|
38
|
+
url.searchParams.set("handle", shopperProduct);
|
|
39
|
+
const variants = await readPricing(url);
|
|
40
|
+
if (variants.length === 0) return;
|
|
41
|
+
form.setAttribute("action", purchaseUrl);
|
|
42
|
+
product.value = shopperProduct;
|
|
43
|
+
if (form.dataset.shopperCompliance === "required") {
|
|
44
|
+
form.addEventListener("submit", event => {
|
|
45
|
+
if (form.dataset.complianceCleared === "1") return;
|
|
46
|
+
event.preventDefault();
|
|
47
|
+
const status = form.querySelector("[data-shopper-preflight-status]");
|
|
48
|
+
if (status) status.textContent = "Checkout verification is loading. Try again in a moment.";
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
for (const variant of variants) select.add(new Option(variant.title, variant.id));
|
|
52
|
+
const showSelection = () => {
|
|
53
|
+
const item = variants[select.selectedIndex];
|
|
54
|
+
if (!item) return;
|
|
55
|
+
const formatter = new Intl.NumberFormat(locale, { style: "currency", currency: item.currency });
|
|
56
|
+
const price = formatter.format(item.price);
|
|
57
|
+
const original = item.compareAtPrice !== null && item.compareAtPrice > item.price
|
|
58
|
+
? `${formatter.format(item.compareAtPrice)} · ` : "";
|
|
59
|
+
priceText.textContent = `${original}${price}`;
|
|
60
|
+
buy.disabled = !item.available;
|
|
61
|
+
};
|
|
62
|
+
showSelection();
|
|
63
|
+
select.addEventListener("change", showSelection);
|
|
64
|
+
cta.replaceWith(form);
|
|
65
|
+
region.parentElement?.querySelector("[data-guest-variant-selector]")?.setAttribute("hidden", "");
|
|
66
|
+
} catch {
|
|
67
|
+
// The sign-in action stays available when live pricing cannot be loaded.
|
|
68
|
+
}
|
|
69
|
+
}
|
|
@@ -16,11 +16,12 @@ const VERSION = "v1";
|
|
|
16
16
|
const encoder = new TextEncoder();
|
|
17
17
|
|
|
18
18
|
/** The public forms a submit token can be issued for. */
|
|
19
|
-
export type ContactFormKind = "contact" | "bulk-quote";
|
|
19
|
+
export type ContactFormKind = "contact" | "bulk-quote" | "wholesale-application";
|
|
20
20
|
|
|
21
21
|
const MAC_PREFIX: Record<ContactFormKind, string> = {
|
|
22
22
|
contact: "contact-form",
|
|
23
23
|
"bulk-quote": "bulk-quote-form",
|
|
24
|
+
"wholesale-application": "wholesale-application-form",
|
|
24
25
|
};
|
|
25
26
|
|
|
26
27
|
export function isContactFormKind(value: unknown): value is ContactFormKind {
|
|
@@ -86,6 +86,8 @@ export interface ReserveInput {
|
|
|
86
86
|
holds: readonly ReserveHold[];
|
|
87
87
|
/** Trusted server snapshot committed in the same transaction as the stock holds. */
|
|
88
88
|
admissionStatement?: SqlStatement;
|
|
89
|
+
/** Scoped server-side authority that must still hold when the reservation begins. */
|
|
90
|
+
authorizationGuard?: SqlStatement;
|
|
89
91
|
/** Immutable provider identity, claimed atomically with its receipt and holds. */
|
|
90
92
|
providerCart?: { provider: "foxycart"; id: string; digest: string; expectedAuthorizationId?: string };
|
|
91
93
|
/**
|
|
@@ -97,7 +99,7 @@ export interface ReserveInput {
|
|
|
97
99
|
|
|
98
100
|
export type ReserveResult =
|
|
99
101
|
| { ok: true; authorizationId: string; repeated: boolean; expiresAt: string }
|
|
100
|
-
| { ok: false; finding: "caller-replay" | "stock-unavailable" | "malformed-request" | "provider-cart-conflict" | "admission-consumed" | "admission-expired" };
|
|
102
|
+
| { ok: false; finding: "caller-replay" | "stock-unavailable" | "malformed-request" | "provider-cart-conflict" | "admission-consumed" | "admission-expired" | "shopper-checkout-proof-unavailable" };
|
|
101
103
|
|
|
102
104
|
export interface PolicyResult {
|
|
103
105
|
released: number;
|
|
@@ -347,20 +349,21 @@ export async function reserveAllocation(runner: StatementRunner, input: ReserveI
|
|
|
347
349
|
const seenAt = `${input.now}|${crypto.randomUUID()}`;
|
|
348
350
|
const holds = [...input.holds].sort((left, right) => left.sku.localeCompare(right.sku) || left.locationId.localeCompare(right.locationId));
|
|
349
351
|
const sync = allocationSync({ tenantId: input.tenantId, stage: input.stage, now: input.now, scope: itemScope(holds) });
|
|
352
|
+
const guard = input.authorizationGuard;
|
|
350
353
|
const statements: SqlStatement[] = [
|
|
351
354
|
{
|
|
352
355
|
sql: `INSERT INTO scrappy_caller_replay (tenant_id, stage, issuer, jti, seen_at)
|
|
353
|
-
|
|
356
|
+
SELECT ?, ?, ?, ?, ? WHERE ${guard ? `EXISTS (${guard.sql})` : "1"}
|
|
354
357
|
ON CONFLICT DO NOTHING
|
|
355
358
|
RETURNING jti`,
|
|
356
|
-
params: [input.tenantId, input.stage, input.issuer, input.jti, seenAt],
|
|
359
|
+
params: [input.tenantId, input.stage, input.issuer, input.jti, seenAt, ...(guard?.params ?? [])],
|
|
357
360
|
},
|
|
358
361
|
{
|
|
359
362
|
sql: `INSERT INTO scrappy_commerce_orders (
|
|
360
363
|
tenant_id, stage, order_id, source, source_order_id, currency, placed_at,
|
|
361
364
|
payment_state, compliance_state, stock_state, fulfillment_state, label_state,
|
|
362
365
|
amount_minor, event_version
|
|
363
|
-
)
|
|
366
|
+
) SELECT ?, ?, ?, 'scrappy', ?, ?, ?, 'pending', 'UNKNOWN', 'unallocated', 'held', 'none', ?, 1 WHERE ${guard ? "changes() = 1" : "1"}
|
|
364
367
|
ON CONFLICT DO NOTHING
|
|
365
368
|
RETURNING order_id`,
|
|
366
369
|
params: [input.tenantId, input.stage, input.orderId, input.orderId, input.currency, input.now, input.amountMinor],
|
|
@@ -472,7 +475,7 @@ export async function reserveAllocation(runner: StatementRunner, input: ReserveI
|
|
|
472
475
|
if (authRows.length > 0) {
|
|
473
476
|
return { ok: true, authorizationId: input.orderId, repeated: false, expiresAt: input.expiresAt };
|
|
474
477
|
}
|
|
475
|
-
if (replayRows.length === 0) return { ok: false, finding: "caller-replay" };
|
|
478
|
+
if (replayRows.length === 0) return { ok: false, finding: guard ? "shopper-checkout-proof-unavailable" : "caller-replay" };
|
|
476
479
|
const existing = selected[0];
|
|
477
480
|
if (existing) {
|
|
478
481
|
return {
|
|
@@ -1,34 +1,13 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Shopper membership eligibility — the request-scoped seam that resolves whether
|
|
3
|
-
* the current shopper is a member, and which tier.
|
|
4
|
-
*
|
|
5
|
-
* Phase 1 storefronts have NO shopper-login/account source (member accounts are
|
|
6
|
-
* a Phase-2 managed-checkout capability), so this resolves anonymous
|
|
7
|
-
* (`{ isMember: false }`) by default. The pricing engine in
|
|
8
|
-
* `@tot/public-runtime` is real and unit-tested regardless; member pricing only
|
|
9
|
-
* RENDERS once a real eligibility signal flows through here.
|
|
10
|
-
*
|
|
11
|
-
* Production wires the signal from the resolved account claim (e.g. a
|
|
12
|
-
* member-tier cookie/JWT set by the Phase-2 login), so the whole storefront gets
|
|
13
|
-
* member pricing by threading one function — no per-page auth logic.
|
|
14
|
-
*/
|
|
1
|
+
/** Resolve membership pricing from a server-verified shopper tier. */
|
|
15
2
|
import type { MemberContext } from "@tot/public-runtime";
|
|
16
3
|
import { ANONYMOUS_MEMBER } from "@tot/public-runtime";
|
|
17
4
|
|
|
18
|
-
/**
|
|
19
|
-
* The minimal membership signal a request carries. Phase 1 never populates it;
|
|
20
|
-
* production derives it from the shopper's resolved account (a member-tier
|
|
21
|
-
* claim). Kept tiny + framework-free so it is trivially testable.
|
|
22
|
-
*/
|
|
5
|
+
/** The tier read from the shopper's live, approved account. */
|
|
23
6
|
export interface MembershipSignal {
|
|
24
7
|
/** The shopper's membership tier id, if they are a signed-in member. */
|
|
25
8
|
memberTierId?: string | null;
|
|
26
9
|
}
|
|
27
10
|
|
|
28
|
-
/**
|
|
29
|
-
* Resolve the shopper's {@link MemberContext} from an optional membership signal.
|
|
30
|
-
* No signal (Phase 1, or an anonymous shopper) → non-member.
|
|
31
|
-
*/
|
|
32
11
|
export function resolveMemberContext(signal?: MembershipSignal | null): MemberContext {
|
|
33
12
|
if (signal?.memberTierId) {
|
|
34
13
|
return { isMember: true, tierId: signal.memberTierId };
|
|
@@ -74,12 +74,19 @@ export async function verifyCdnForward(
|
|
|
74
74
|
* CloudFront edge, shared by every visitor behind it. Otherwise — a Cloudflare-served
|
|
75
75
|
* request, or a viewer-IP header with no valid forward proof — it is `cf-connecting-ip`,
|
|
76
76
|
* which Cloudflare sets and a client cannot. The first `x-forwarded-for` hop is the
|
|
77
|
-
* local dev fallback.
|
|
77
|
+
* local dev fallback. With a trusted source selected by routing, only that source
|
|
78
|
+
* is accepted and a missing or malformed address returns `unknown`.
|
|
78
79
|
*/
|
|
79
|
-
export async function requestClientIp(
|
|
80
|
-
|
|
80
|
+
export async function requestClientIp(
|
|
81
|
+
headers: Headers,
|
|
82
|
+
cdnOriginSecret: string | undefined,
|
|
83
|
+
trustedSource?: "cloudfront" | "cloudflare",
|
|
84
|
+
): Promise<string> {
|
|
85
|
+
const forward = trustedSource === "cloudflare" ? null : await verifyCdnForward(headers, cdnOriginSecret);
|
|
81
86
|
if (forward?.viewerIp) return forward.viewerIp;
|
|
87
|
+
if (trustedSource === "cloudfront") return "unknown";
|
|
82
88
|
const cf = headers.get("cf-connecting-ip");
|
|
89
|
+
if (trustedSource === "cloudflare") return cf && IP_SHAPE.test(cf) ? cf : "unknown";
|
|
83
90
|
if (cf) return cf;
|
|
84
91
|
const xff = headers.get("x-forwarded-for");
|
|
85
92
|
if (xff) return xff.split(",")[0]!.trim();
|