@tokenoftrust/storefront-runner 7.10.1 → 7.11.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/apps/storefront/src/lib/checkout/commerce/checkoutRequirements.ts +45 -1
- package/apps/storefront/src/lib/customers/accounts/checkoutProof.ts +7 -5
- package/apps/storefront/src/lib/customers/accounts/orgKyb.ts +1 -1
- package/apps/storefront/src/pages/api/commerce/final-cart-authorization.ts +33 -4
- package/package.json +1 -1
- package/packages/public-runtime/package.json +1 -0
- package/packages/public-runtime/src/shipping-rate-policy.ts +94 -0
|
@@ -13,6 +13,7 @@
|
|
|
13
13
|
* checkout store, and production, keep the full fail-closed contract regardless of what is saved here.
|
|
14
14
|
*/
|
|
15
15
|
import { operationalSettingArtifactPath, readPublishedArtifact, type CustomizationEnv } from "@tot/public-runtime";
|
|
16
|
+
import { carrierRatePolicyProblem, quoteCarrierRate, type CarrierRatePolicy, type CarrierRateQuote, type LocationCarrierRate } from "@tot/public-runtime/shipping-rate-policy";
|
|
16
17
|
import { readKv } from "@/lib/publication/shared/runtimeEnv";
|
|
17
18
|
import { checkoutStoreHasExciseProducer } from "./sharedStoreAdmission";
|
|
18
19
|
|
|
@@ -38,6 +39,48 @@ export function checkoutStoreTaxBlocker(
|
|
|
38
39
|
|
|
39
40
|
export const CHECKOUT_REQUIREMENT_KEYS = ["verification", "tax", "rules"] as const;
|
|
40
41
|
|
|
42
|
+
/** The artifact key carrying the carrier-rate + per-order markup policy (not a boolean switch). */
|
|
43
|
+
export const SHIPPING_RATE_POLICY_KEY = "shippingRatePolicy";
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* The carrier-rate policy declared in a `checkout-requirements.json` artifact, or `null` when none
|
|
47
|
+
* is declared or the declaration is invalid (a reader must then quote no carrier rate).
|
|
48
|
+
*/
|
|
49
|
+
export function parseShippingRatePolicy(raw: string | null): CarrierRatePolicy | null {
|
|
50
|
+
if (raw === null) return null;
|
|
51
|
+
let parsed: unknown;
|
|
52
|
+
try {
|
|
53
|
+
parsed = JSON.parse(raw);
|
|
54
|
+
} catch (error) {
|
|
55
|
+
if (!(error instanceof SyntaxError)) throw error;
|
|
56
|
+
return null;
|
|
57
|
+
}
|
|
58
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
|
|
59
|
+
const declared = (parsed as Record<string, unknown>)[SHIPPING_RATE_POLICY_KEY];
|
|
60
|
+
if (!declared || typeof declared !== "object" || Array.isArray(declared)) return null;
|
|
61
|
+
const policy = declared as CarrierRatePolicy;
|
|
62
|
+
if (carrierRatePolicyProblem(policy) !== null) return null;
|
|
63
|
+
return { markupMinor: policy.markupMinor, signatureFeeMinor: policy.signatureFeeMinor, multiLocationPolicy: policy.multiLocationPolicy };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* The artifact bytes a switches save writes: the validated switches plus the store's existing
|
|
68
|
+
* `shippingRatePolicy`, so an ordinary save never drops it.
|
|
69
|
+
*/
|
|
70
|
+
export function serializeCheckoutRequirements(requirements: CheckoutRequirements, policy: CarrierRatePolicy | null): string {
|
|
71
|
+
return JSON.stringify(policy ? { ...requirements, [SHIPPING_RATE_POLICY_KEY]: policy } : requirements);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Quote an order's shipping from per-location carrier rates under the store's declared policy.
|
|
76
|
+
* Entry point for a rate hook: the markup and signature fee are charged once per order unless
|
|
77
|
+
* `per_location` is declared. `null` when the store declares no valid policy.
|
|
78
|
+
*/
|
|
79
|
+
export function quoteOrderShipping(rawArtifact: string | null, rates: readonly LocationCarrierRate[]): CarrierRateQuote | null {
|
|
80
|
+
const policy = parseShippingRatePolicy(rawArtifact);
|
|
81
|
+
return policy ? quoteCarrierRate(policy, rates) : null;
|
|
82
|
+
}
|
|
83
|
+
|
|
41
84
|
export const DEFAULT_CHECKOUT_REQUIREMENTS: Readonly<CheckoutRequirements> = Object.freeze({
|
|
42
85
|
verification: false,
|
|
43
86
|
tax: false,
|
|
@@ -63,7 +106,8 @@ export function parseCheckoutRequirements(raw: string | null): CheckoutRequireme
|
|
|
63
106
|
}
|
|
64
107
|
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
|
|
65
108
|
const value = parsed as Record<string, unknown>;
|
|
66
|
-
if (Object.keys(value).some(key => !(CHECKOUT_REQUIREMENT_KEYS as readonly string[]).includes(key))) return null;
|
|
109
|
+
if (Object.keys(value).some(key => key !== SHIPPING_RATE_POLICY_KEY && !(CHECKOUT_REQUIREMENT_KEYS as readonly string[]).includes(key))) return null;
|
|
110
|
+
if (SHIPPING_RATE_POLICY_KEY in value && parseShippingRatePolicy(raw) === null) return null;
|
|
67
111
|
const out = { ...DEFAULT_CHECKOUT_REQUIREMENTS };
|
|
68
112
|
for (const key of CHECKOUT_REQUIREMENT_KEYS) {
|
|
69
113
|
if (value[key] === undefined) continue;
|
|
@@ -34,21 +34,23 @@ export interface ShopperCheckoutWire {
|
|
|
34
34
|
proof: string;
|
|
35
35
|
providerCartSelectorDigest: string;
|
|
36
36
|
buyerConfirmation: string;
|
|
37
|
-
licensedDestinationDigest?: string;
|
|
38
37
|
}
|
|
39
38
|
|
|
40
39
|
export function readShopperCheckoutWire(value: unknown): ShopperCheckoutWire | null {
|
|
41
40
|
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
|
|
42
41
|
const wire = value as Record<string, unknown>;
|
|
43
|
-
if (Object.keys(wire).some(key => !["version", "proof", "providerCartSelectorDigest", "buyerConfirmation"
|
|
42
|
+
if (Object.keys(wire).some(key => !["version", "proof", "providerCartSelectorDigest", "buyerConfirmation"].includes(key)) ||
|
|
44
43
|
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;
|
|
44
|
+
typeof wire.providerCartSelectorDigest !== "string" || !HEX.test(wire.providerCartSelectorDigest)) return null;
|
|
47
45
|
return wire as unknown as ShopperCheckoutWire;
|
|
48
46
|
}
|
|
49
47
|
|
|
48
|
+
/**
|
|
49
|
+
* The v2 context material the provider caller digests: its final slot is a fixed `null`. The
|
|
50
|
+
* shopper wire carries no destination; org KYB reads the ship-to from the provider-signed snapshot.
|
|
51
|
+
*/
|
|
50
52
|
export const shopperCheckoutContextDigest = (wire: ShopperCheckoutWire): Promise<string> => sha256Hex(JSON.stringify([
|
|
51
|
-
"shopper-checkout-context/v2", wire.version, wire.proof, wire.providerCartSelectorDigest, wire.buyerConfirmation,
|
|
53
|
+
"shopper-checkout-context/v2", wire.version, wire.proof, wire.providerCartSelectorDigest, wire.buyerConfirmation, null,
|
|
52
54
|
]));
|
|
53
55
|
|
|
54
56
|
function signedMaterial(shopper: ScopedShopper, nonce: string, expiresAt: number): string {
|
|
@@ -6,7 +6,7 @@ export async function hasShopperOrgKyb(_db: Queryable, _shopper: ScopedShopper,
|
|
|
6
6
|
}
|
|
7
7
|
|
|
8
8
|
export async function shopperOrgKyb(
|
|
9
|
-
_db: Queryable, _shopper: ScopedShopper,
|
|
9
|
+
_db: Queryable, _shopper: ScopedShopper, _shipTo: unknown, _totalMinor: number, _now?: Date,
|
|
10
10
|
): Promise<{ expiresAt: string; updatedAt: number } | null> {
|
|
11
11
|
return null;
|
|
12
12
|
}
|
|
@@ -82,7 +82,31 @@ async function digest(value: string): Promise<string> {
|
|
|
82
82
|
* from a closed vocabulary; no other key. Optional: a snapshot without it is read as before.
|
|
83
83
|
*/
|
|
84
84
|
export { EXCISE_REASONS, type ExciseCarrier, exciseLinesDigest, exciseReconcilesWithTotals, exciseRequiredForTenant, resolveTaxEvidence, checkoutStoreHasExciseProducer };
|
|
85
|
-
|
|
85
|
+
/**
|
|
86
|
+
* `shipTo` is the provider's full ship-to address for this cart, signed into the snapshot by the
|
|
87
|
+
* caller. It agrees with `destination`, is used only to derive the org KYB licensed-destination
|
|
88
|
+
* digest, and is never persisted.
|
|
89
|
+
*/
|
|
90
|
+
type FinalCartWire = CommerceProviderCartSnapshot & { excise?: ExciseCarrier; shopperCheckout?: ShopperCheckoutWire; shipTo?: ShipTo };
|
|
91
|
+
interface ShipTo { line1: string; line2: string | null; city: string; region: string; postalCode: string; country: string }
|
|
92
|
+
const SHIP_TO_FIELDS = { line1: [200, true], line2: [200, false], city: [100, true], region: [60, false], postalCode: [20, false], country: [2, true] } as const;
|
|
93
|
+
/** The provider ship-to: the closed address keys, each bounded, control-free text; null when anything else. */
|
|
94
|
+
function readShipTo(value: unknown): ShipTo | null {
|
|
95
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
|
|
96
|
+
const record = value as Record<string, unknown>;
|
|
97
|
+
if (Object.keys(record).some(key => !Object.hasOwn(SHIP_TO_FIELDS, key))) return null;
|
|
98
|
+
const out: Record<string, string | null> = {};
|
|
99
|
+
for (const [key, [max, required]] of Object.entries(SHIP_TO_FIELDS)) {
|
|
100
|
+
const raw = record[key];
|
|
101
|
+
if (raw === undefined || raw === null || raw === "") { if (required) return null; out[key] = null; continue; }
|
|
102
|
+
if (typeof raw !== "string" || raw.length > max || /[\p{C}]/u.test(raw)) return null;
|
|
103
|
+
const trimmed = raw.trim();
|
|
104
|
+
if (!trimmed && required) return null;
|
|
105
|
+
out[key] = trimmed || null;
|
|
106
|
+
}
|
|
107
|
+
if (!/^[A-Za-z]{2}$/.test(out.country!)) return null;
|
|
108
|
+
return { line1: out.line1!, line2: out.line2 ?? null, city: out.city!, region: out.region ?? "", postalCode: out.postalCode ?? "", country: out.country!.toUpperCase() };
|
|
109
|
+
}
|
|
86
110
|
export function readExcise(value: unknown): ExciseCarrier | null {
|
|
87
111
|
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
|
|
88
112
|
const e = value as Record<string, unknown>;
|
|
@@ -98,7 +122,7 @@ function readSnapshot(value: unknown): FinalCartWire | null {
|
|
|
98
122
|
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
|
|
99
123
|
const v = value as Record<string, unknown>;
|
|
100
124
|
const allowed = ["provider", "providerCartId", "providerCartDigest", "tenantId", "stage", "currency", "lines", "totals", "destinationDigest", "destination"];
|
|
101
|
-
const optional = ["expectedAuthorizationId", "verificationRef", "contentVersionId", "excise", "shopperCheckout", "checkoutContextDigest"];
|
|
125
|
+
const optional = ["expectedAuthorizationId", "verificationRef", "contentVersionId", "excise", "shopperCheckout", "checkoutContextDigest", "shipTo"];
|
|
102
126
|
if (Object.keys(v).some(k => !allowed.includes(k) && !optional.includes(k)) || allowed.some(k => !(k in v))) return null;
|
|
103
127
|
if ("excise" in v && !readExcise(v.excise)) return null;
|
|
104
128
|
if ("contentVersionId" in v && (typeof v.contentVersionId !== "string" || !isContentVersionId(v.contentVersionId))) return null;
|
|
@@ -122,6 +146,11 @@ function readSnapshot(value: unknown): FinalCartWire | null {
|
|
|
122
146
|
Object.keys(t).some(k => !Number.isSafeInteger(t[k]) || Number(t[k]) < 0)) return null;
|
|
123
147
|
const d = v.destination as Record<string, unknown> | undefined;
|
|
124
148
|
if (!d || Object.keys(d).length !== 2 || typeof d.country !== "string" || !/^[A-Z]{2}$/.test(d.country) || typeof d.region !== "string" || !/^[A-Z0-9-]{1,8}$/.test(d.region)) return null;
|
|
149
|
+
if ("shipTo" in v) {
|
|
150
|
+
const shipTo = readShipTo(v.shipTo);
|
|
151
|
+
if (!shipTo || shipTo.country !== d.country || shipTo.region.toUpperCase() !== d.region) return null;
|
|
152
|
+
v.shipTo = shipTo;
|
|
153
|
+
}
|
|
125
154
|
const snapshot = v as unknown as FinalCartWire;
|
|
126
155
|
if (new Set(snapshot.lines.map(line => line.sku)).size !== snapshot.lines.length) return null;
|
|
127
156
|
if (!totalsMatch(snapshot.totals) || !exciseReconcilesWithTotals(snapshot.totals, snapshot.excise) ||
|
|
@@ -258,7 +287,7 @@ async function authorize(context: APIContext): Promise<Response> {
|
|
|
258
287
|
let wire: FinalCartWire | null;
|
|
259
288
|
try { wire = readSnapshot(JSON.parse(raw)); } catch { wire = null; }
|
|
260
289
|
if (!wire || !await exciseBindsSnapshot(wire)) return deny("malformed-request");
|
|
261
|
-
const { shopperCheckout, ...safeWire } = wire;
|
|
290
|
+
const { shopperCheckout, shipTo, ...safeWire } = wire;
|
|
262
291
|
const snapshot = keyedLines(safeWire);
|
|
263
292
|
const jwks = publicJwks(await readEnv("COMMERCE_CALLER_JWKS"));
|
|
264
293
|
const issuers = list(await readEnv("COMMERCE_CALLER_ISSUERS"));
|
|
@@ -395,7 +424,7 @@ async function authorize(context: APIContext): Promise<Response> {
|
|
|
395
424
|
const evidence: CommerceEvidence = { verification: "absent", tax: "absent", risk: "absent", stock: stockTracked ? "fresh" : "not-required" };
|
|
396
425
|
const orgKybRequired = resolveShopperAccessPolicy(tenant).b2bKybOrgVerification;
|
|
397
426
|
const orgKyb = orgKybRequired && scopedProof ? await shopperOrgKyb(queryable, scopedProof.shopper,
|
|
398
|
-
|
|
427
|
+
shipTo, snapshot.totals.totalMinor, new Date(now)) : null;
|
|
399
428
|
if (orgKybRequired && !orgKyb) return deny("shopper-org-kyb-review-required");
|
|
400
429
|
if (existing && orgKyb && Date.parse(existing.expiresAt) > Date.parse(orgKyb.expiresAt)) return deny("admission-expired");
|
|
401
430
|
const expiresAt = existing?.expiresAt ?? new Date(Math.min(Date.now() + CHECKOUT_ADMISSION_TTL_MS, stockExpiry,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tokenoftrust/storefront-runner",
|
|
3
|
-
"version": "7.
|
|
3
|
+
"version": "7.11.1",
|
|
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",
|
|
@@ -12,6 +12,7 @@
|
|
|
12
12
|
".": "./src/index.ts",
|
|
13
13
|
"./widget-postmessage": "./src/widget-postmessage.ts",
|
|
14
14
|
"./compliance-obligations": "./src/compliance-obligations.ts",
|
|
15
|
+
"./shipping-rate-policy": "./src/shipping-rate-policy.ts",
|
|
15
16
|
"./integration/consent-broker": "./src/integration/consent-broker.ts",
|
|
16
17
|
"./integration/environment": "./src/integration/environment.ts",
|
|
17
18
|
"./integration/render-phases": "./src/integration/render-phases.ts",
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Carrier-calculated shipping: carrier rate + a per-order markup, charged once per order.
|
|
3
|
+
*
|
|
4
|
+
* A rate hook (a private app such as the ShipStation connector) returns one carrier rate per
|
|
5
|
+
* ship-from location the order splits across. The order pays the carrier rates plus
|
|
6
|
+
* `markupMinor` and `signatureFeeMinor` exactly once, never once per location.
|
|
7
|
+
* All amounts are integer minor units of one currency.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
export type MultiLocationPolicy = "once_per_order" | "per_location";
|
|
11
|
+
|
|
12
|
+
export interface CarrierRatePolicy {
|
|
13
|
+
/** Fixed amount added to the order, minor units (200 = $2.00). */
|
|
14
|
+
markupMinor: number;
|
|
15
|
+
/** Order-level adult-signature fee, minor units. Defaults to 0. */
|
|
16
|
+
signatureFeeMinor?: number;
|
|
17
|
+
/** Defaults to `once_per_order`. */
|
|
18
|
+
multiLocationPolicy?: MultiLocationPolicy;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** The carrier's rate for one ship-from location's parcel(s). */
|
|
22
|
+
export interface LocationCarrierRate {
|
|
23
|
+
locationId: string;
|
|
24
|
+
carrierRateMinor: number;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface CarrierRateQuote {
|
|
28
|
+
carrierRateMinor: number;
|
|
29
|
+
markupMinor: number;
|
|
30
|
+
signatureFeeMinor: number;
|
|
31
|
+
totalMinor: number;
|
|
32
|
+
locationCount: number;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export class CarrierRatePolicyError extends Error {
|
|
36
|
+
readonly code = "carrier-rate-policy" as const;
|
|
37
|
+
constructor(message: string) {
|
|
38
|
+
super(message);
|
|
39
|
+
this.name = "CarrierRatePolicyError";
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function minor(value: unknown, what: string): number {
|
|
44
|
+
if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) {
|
|
45
|
+
throw new CarrierRatePolicyError(`${what} must be a non-negative integer of minor units.`);
|
|
46
|
+
}
|
|
47
|
+
return value;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** `null` when `policy` is a valid carrier-rate policy, else the reason it is not. */
|
|
51
|
+
export function carrierRatePolicyProblem(policy: CarrierRatePolicy): string | null {
|
|
52
|
+
const ok = (value: unknown, allowUndefined: boolean) =>
|
|
53
|
+
(allowUndefined && value === undefined) || (typeof value === "number" && Number.isSafeInteger(value) && value >= 0);
|
|
54
|
+
if (!ok(policy.markupMinor, false)) return "markupMinor must be a non-negative integer of minor units.";
|
|
55
|
+
if (!ok(policy.signatureFeeMinor, true)) return "signatureFeeMinor must be a non-negative integer of minor units.";
|
|
56
|
+
const mode = policy.multiLocationPolicy;
|
|
57
|
+
if (mode !== undefined && mode !== "once_per_order" && mode !== "per_location") {
|
|
58
|
+
return "multiLocationPolicy must be once_per_order or per_location.";
|
|
59
|
+
}
|
|
60
|
+
return null;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Price an order from per-location carrier rates. Throws `CarrierRatePolicyError` on an invalid
|
|
65
|
+
* policy, an empty or duplicate-location rate list, or a non-integer amount (fails closed).
|
|
66
|
+
*/
|
|
67
|
+
export function quoteCarrierRate(policy: CarrierRatePolicy, rates: readonly LocationCarrierRate[]): CarrierRateQuote {
|
|
68
|
+
const markup = minor(policy.markupMinor, "markupMinor");
|
|
69
|
+
const signature = minor(policy.signatureFeeMinor ?? 0, "signatureFeeMinor");
|
|
70
|
+
const mode = policy.multiLocationPolicy ?? "once_per_order";
|
|
71
|
+
if (mode !== "once_per_order" && mode !== "per_location") {
|
|
72
|
+
throw new CarrierRatePolicyError("multiLocationPolicy must be once_per_order or per_location.");
|
|
73
|
+
}
|
|
74
|
+
if (rates.length === 0) throw new CarrierRatePolicyError("At least one location rate is required.");
|
|
75
|
+
const seen = new Set<string>();
|
|
76
|
+
let carrier = 0;
|
|
77
|
+
for (const rate of rates) {
|
|
78
|
+
if (!rate.locationId || seen.has(rate.locationId)) {
|
|
79
|
+
throw new CarrierRatePolicyError("Each location rate needs a unique locationId.");
|
|
80
|
+
}
|
|
81
|
+
seen.add(rate.locationId);
|
|
82
|
+
carrier += minor(rate.carrierRateMinor, "carrierRateMinor");
|
|
83
|
+
}
|
|
84
|
+
const multiplier = mode === "per_location" ? rates.length : 1;
|
|
85
|
+
const markupMinor = markup * multiplier;
|
|
86
|
+
const signatureFeeMinor = signature * multiplier;
|
|
87
|
+
return {
|
|
88
|
+
carrierRateMinor: carrier,
|
|
89
|
+
markupMinor,
|
|
90
|
+
signatureFeeMinor,
|
|
91
|
+
totalMinor: carrier + markupMinor + signatureFeeMinor,
|
|
92
|
+
locationCount: rates.length,
|
|
93
|
+
};
|
|
94
|
+
}
|