@tokenoftrust/storefront-runner 6.8.1 → 6.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/apps/storefront/src/lib/checkout/browser/checkoutExciseForm.ts +39 -0
- package/apps/storefront/src/lib/checkout/commerce/checkoutExcise.ts +110 -0
- package/apps/storefront/src/lib/checkout/commerce/checkoutHandoffRoute.ts +8 -1
- package/apps/storefront/src/lib/checkout/commerce/checkoutSettings.ts +2 -8
- package/apps/storefront/src/lib/checkout/shared/cartState.ts +1 -0
- package/apps/storefront/src/lib/integrations/apps/inventoryWrite.ts +290 -0
- package/apps/storefront/src/lib/integrations/apps/scopes.ts +2 -1
- package/apps/storefront/src/lib/inventory/mirrorStock.ts +127 -9
- package/package.json +1 -1
- package/packages/public-runtime/src/activity/catalog.ts +7 -0
- package/packages/public-runtime/src/checkout.ts +25 -2
- package/packages/public-runtime/src/customization-runtime.ts +1 -1
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/** Browser wiring for the /admin "Excise tax" form: collect the switch, POST, report. */
|
|
2
|
+
|
|
3
|
+
import { saveResultStatus } from "./checkoutRequirementsForm";
|
|
4
|
+
import { announceSettingChanged } from "./settingDraftActions";
|
|
5
|
+
|
|
6
|
+
export function mountCheckoutExciseForm(form: HTMLElement): void {
|
|
7
|
+
const endpoint = form.dataset.endpoint || "/api/preview/checkout-excise";
|
|
8
|
+
const targetTenant = form.dataset.targetTenant || "";
|
|
9
|
+
const field = form.querySelector<HTMLInputElement>("[data-excise-field]");
|
|
10
|
+
const status = form.querySelector<HTMLElement>("[data-excise-status]");
|
|
11
|
+
const saveBtn = form.querySelector<HTMLButtonElement>("[data-excise-save]");
|
|
12
|
+
const setStatus = (message: string, state?: "ok" | "err") => {
|
|
13
|
+
if (!status) return;
|
|
14
|
+
status.textContent = message;
|
|
15
|
+
if (state) status.dataset.state = state;
|
|
16
|
+
else delete status.dataset.state;
|
|
17
|
+
};
|
|
18
|
+
saveBtn?.addEventListener("click", async () => {
|
|
19
|
+
const body: Record<string, unknown> = { excise: field?.checked ?? false, ...(targetTenant ? { targetTenant } : {}) };
|
|
20
|
+
setStatus("Saving…");
|
|
21
|
+
saveBtn.disabled = true;
|
|
22
|
+
try {
|
|
23
|
+
const res = await fetch(endpoint, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
|
|
24
|
+
let data: Parameters<typeof saveResultStatus>[2] = {};
|
|
25
|
+
try {
|
|
26
|
+
data = await res.json();
|
|
27
|
+
} catch {
|
|
28
|
+
// non-JSON error body
|
|
29
|
+
}
|
|
30
|
+
const result = saveResultStatus(res.ok, res.status, data);
|
|
31
|
+
setStatus(result.message, result.state);
|
|
32
|
+
if (res.ok) announceSettingChanged("checkout-excise");
|
|
33
|
+
} catch {
|
|
34
|
+
setStatus("Save failed — network error", "err");
|
|
35
|
+
} finally {
|
|
36
|
+
saveBtn.disabled = false;
|
|
37
|
+
}
|
|
38
|
+
});
|
|
39
|
+
}
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A store's excise setting: whether its checkout collects excise tax. It is a merchant-operated
|
|
3
|
+
* commerce setting (ADR 0035 "operational"), saved as the tenant-owned artifact
|
|
4
|
+
* `tenants/<id>/checkout-excise.json` exactly like the checkout requirements: a save writes the
|
|
5
|
+
* draft (`test`) the preview reads, the live store reads the published value (`live`) until the
|
|
6
|
+
* owner publishes the draft, and every reader resolves it through `readPublishedArtifact` for its
|
|
7
|
+
* own env. The setting is served by the Worker on both CDN providers, because the checkout handoff
|
|
8
|
+
* that signs it into the cart is a Worker route for Cloudflare and CloudFront stores alike.
|
|
9
|
+
*
|
|
10
|
+
* An absent artifact means the capability default (`capabilities.exciseTax`, on for a store whose
|
|
11
|
+
* compliance rules owe excise). A store whose compliance rules require excise keeps it on whatever
|
|
12
|
+
* is saved: the save refuses off and a reader ignores a stored off.
|
|
13
|
+
*/
|
|
14
|
+
import {
|
|
15
|
+
operationalSettingArtifactPath,
|
|
16
|
+
readPublishedArtifact,
|
|
17
|
+
resolveComplianceObligations,
|
|
18
|
+
type CapabilityConfig,
|
|
19
|
+
type CustomizationEnv,
|
|
20
|
+
type TenantConfig,
|
|
21
|
+
} from "@tot/public-runtime";
|
|
22
|
+
import { readKv } from "@/lib/publication/shared/runtimeEnv";
|
|
23
|
+
|
|
24
|
+
export interface CheckoutExcise {
|
|
25
|
+
/** Collect excise tax at checkout. */
|
|
26
|
+
excise: boolean;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* What a read found: `unset` (nothing saved, so the capability default), `set`, or `unreadable`
|
|
31
|
+
* (corrupt or unavailable, so a reader must fail closed, never treat it as off).
|
|
32
|
+
*/
|
|
33
|
+
export type SavedExcise = { state: "unset" } | { state: "set"; excise: boolean } | { state: "unreadable" };
|
|
34
|
+
|
|
35
|
+
const UNREADABLE: SavedExcise = { state: "unreadable" };
|
|
36
|
+
|
|
37
|
+
export const REQUIRED_EXCISE_REFUSAL = "This store's compliance rules require excise tax collection, so it can't be turned off.";
|
|
38
|
+
|
|
39
|
+
export function checkoutExciseArtifactPath(tenantId: string): string {
|
|
40
|
+
return operationalSettingArtifactPath(tenantId, "checkout-excise.json");
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Whether the store's compliance rules require excise collection. */
|
|
44
|
+
export function exciseRequired(tenant: Pick<TenantConfig, "compliance" | "siteType">): boolean {
|
|
45
|
+
return resolveComplianceObligations(tenant).exciseTax.required;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Parse a published artifact: absent is `unset`; anything but an object holding exactly a boolean `excise` is `unreadable`. */
|
|
49
|
+
export function parseCheckoutExcise(raw: string | null): SavedExcise {
|
|
50
|
+
if (raw === null) return { state: "unset" };
|
|
51
|
+
const parsed = parseJson(raw);
|
|
52
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return UNREADABLE;
|
|
53
|
+
const value = parsed as Record<string, unknown>;
|
|
54
|
+
if (Object.keys(value).some((key) => key !== "excise")) return UNREADABLE;
|
|
55
|
+
if (typeof value.excise !== "boolean") return UNREADABLE;
|
|
56
|
+
return { state: "set", excise: value.excise };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function parseJson(raw: string): unknown {
|
|
60
|
+
try {
|
|
61
|
+
return JSON.parse(raw);
|
|
62
|
+
} catch (err) {
|
|
63
|
+
if (err instanceof SyntaxError) return undefined;
|
|
64
|
+
throw err;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export type CheckoutExciseInput = { ok: true; setting: CheckoutExcise } | { ok: false; errors: string[] };
|
|
69
|
+
|
|
70
|
+
/** Validate a save from /admin. A store whose compliance rules require excise cannot save it off. */
|
|
71
|
+
export function validateCheckoutExciseInput(raw: unknown, required: boolean): CheckoutExciseInput {
|
|
72
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return { ok: false, errors: ["body must be a JSON object"] };
|
|
73
|
+
const excise = (raw as Record<string, unknown>).excise;
|
|
74
|
+
if (typeof excise !== "boolean") return { ok: false, errors: ["excise must be true or false"] };
|
|
75
|
+
if (required && !excise) return { ok: false, errors: [REQUIRED_EXCISE_REFUSAL] };
|
|
76
|
+
return { ok: true, setting: { excise } };
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* The effective setting from what is saved: a required store is always on, otherwise the saved
|
|
81
|
+
* value, otherwise the capability default. An unreadable save is on: collecting tax is the stricter
|
|
82
|
+
* outcome, so a corrupt or unavailable store never switches it off.
|
|
83
|
+
*/
|
|
84
|
+
export function resolveExcise(saved: SavedExcise, input: { required: boolean; capabilities: Pick<CapabilityConfig, "exciseTax"> }): boolean {
|
|
85
|
+
if (input.required || saved.state === "unreadable") return true;
|
|
86
|
+
return saved.state === "set" ? saved.excise : input.capabilities.exciseTax.enabled;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** The store's saved setting for `env`. */
|
|
90
|
+
export async function readCheckoutExcise(tenantId: string, env: CustomizationEnv): Promise<SavedExcise> {
|
|
91
|
+
const kv = await readKv("TENANT_CACHE");
|
|
92
|
+
if (!kv) return UNREADABLE;
|
|
93
|
+
let raw: string | null;
|
|
94
|
+
try {
|
|
95
|
+
raw = await readPublishedArtifact((key) => kv.get(key), tenantId, env, checkoutExciseArtifactPath(tenantId));
|
|
96
|
+
} catch (err) {
|
|
97
|
+
console.warn(`[checkout-excise] unreadable ${JSON.stringify({ tenant: tenantId, env, error: err instanceof Error ? err.name : "unknown" })}`);
|
|
98
|
+
return UNREADABLE;
|
|
99
|
+
}
|
|
100
|
+
return parseCheckoutExcise(raw);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Whether checkout collects excise for `env`. */
|
|
104
|
+
export async function effectiveExcise(
|
|
105
|
+
tenant: Pick<TenantConfig, "tenant_id" | "compliance" | "siteType">,
|
|
106
|
+
capabilities: Pick<CapabilityConfig, "exciseTax">,
|
|
107
|
+
env: CustomizationEnv,
|
|
108
|
+
): Promise<boolean> {
|
|
109
|
+
return resolveExcise(await readCheckoutExcise(tenant.tenant_id, env), { required: exciseRequired(tenant), capabilities });
|
|
110
|
+
}
|
|
@@ -31,6 +31,7 @@ import {
|
|
|
31
31
|
withVerificationRef,
|
|
32
32
|
withShippingPolicy,
|
|
33
33
|
withReturnUrl,
|
|
34
|
+
withExcise,
|
|
34
35
|
trustedCartReturnUrl,
|
|
35
36
|
tenantPublicOrigin,
|
|
36
37
|
CHECKOUT_NAVIGATION_REFERRER_POLICY,
|
|
@@ -45,6 +46,7 @@ import {
|
|
|
45
46
|
import { resolveCheckoutHandoffCorrelation } from "@/lib/checkout/commerce/checkoutHandoffCorrelation";
|
|
46
47
|
import { bindCartSession, CART_UNAVAILABLE_MESSAGE, withCartSession } from "@/lib/checkout/commerce/cartSession";
|
|
47
48
|
import { resolveCartSigning, shopperCartDenialMessage } from "@/lib/checkout/shared/checkoutCommerce";
|
|
49
|
+
import { effectiveExcise } from "@/lib/checkout/commerce/checkoutExcise";
|
|
48
50
|
import { fromD1 } from "@/lib/catalog/d1/catalog";
|
|
49
51
|
import { readD1 } from "@/lib/publication/shared/env";
|
|
50
52
|
import { handoffStockFinding, MIRROR_LOCATION_UNSPECIFIED, readMirrorBalance } from "@/lib/inventory/mirrorStock";
|
|
@@ -230,7 +232,12 @@ async function cartFormPost(context: APIContext): Promise<Response> {
|
|
|
230
232
|
const verified = await withVerificationRef(result.fields, { mode: commerce.mode, secret: signing.secret, ref });
|
|
231
233
|
const shippable = await boundShippingPolicy(verified, tenant, commerce.mode, signing.secret);
|
|
232
234
|
if (!shippable) return cartDenial("shipping", SHIPPING_UNAVAILABLE_CART_MESSAGE, 409);
|
|
233
|
-
const
|
|
235
|
+
const excised = await withExcise(shippable, {
|
|
236
|
+
mode: commerce.mode,
|
|
237
|
+
secret: signing.secret,
|
|
238
|
+
excise: await effectiveExcise(tenant, context.locals.capabilities, context.locals.customizationEnv ?? "test"),
|
|
239
|
+
});
|
|
240
|
+
const returned = await withReturnUrl(excised, {
|
|
234
241
|
mode: commerce.mode, secret: signing.secret, returnUrl: submittedFromUrl(context.request, tenant),
|
|
235
242
|
});
|
|
236
243
|
const location = await sessionedCartLocation(context, commerce, tenant, returned);
|
|
@@ -12,8 +12,8 @@
|
|
|
12
12
|
* cart_include[drawer] / receipt / email), set and refreshed
|
|
13
13
|
* through the commerce service.
|
|
14
14
|
* The colors/fonts/logo live INSIDE the hosted template file.
|
|
15
|
-
* 3. `store` — storeSubDomain +
|
|
16
|
-
*
|
|
15
|
+
* 3. `store` — storeSubDomain + the age/ID verification loader toggle.
|
|
16
|
+
* Non-visual; no theme default.
|
|
17
17
|
*
|
|
18
18
|
* Prepopulation lands on the parts with a theme default — the brand colors and
|
|
19
19
|
* the template pointers (defaulted to a ToT-hosted, theme-derived template URL).
|
|
@@ -67,7 +67,6 @@ export interface CheckoutTemplatePointer {
|
|
|
67
67
|
/** Store + loader feature config. Non-visual. */
|
|
68
68
|
export interface CheckoutStoreConfig {
|
|
69
69
|
storeSubDomain: string;
|
|
70
|
-
exciseTaxCollectionEnabled: boolean;
|
|
71
70
|
verificationEnabled: boolean;
|
|
72
71
|
}
|
|
73
72
|
|
|
@@ -132,7 +131,6 @@ export function deriveCheckoutSettings(
|
|
|
132
131
|
store: {
|
|
133
132
|
storeSubDomain: commerce?.storeSubDomain ?? "",
|
|
134
133
|
// Feature toggles have no theme default — start off; not prepopulatable.
|
|
135
|
-
exciseTaxCollectionEnabled: false,
|
|
136
134
|
verificationEnabled: false,
|
|
137
135
|
},
|
|
138
136
|
};
|
|
@@ -238,10 +236,6 @@ export function buildCheckoutSettingsFields(
|
|
|
238
236
|
resettable: false,
|
|
239
237
|
help: "Internal checkout store identifier for this tenant.",
|
|
240
238
|
}),
|
|
241
|
-
field("store", "store.exciseTaxCollectionEnabled", "Collect excise tax", "boolean", {
|
|
242
|
-
resettable: false,
|
|
243
|
-
help: "Managed pre-cart excise tax collection.",
|
|
244
|
-
}),
|
|
245
239
|
field("store", "store.verificationEnabled", "Age / identity verification", "boolean", {
|
|
246
240
|
resettable: false,
|
|
247
241
|
help: "Token of Trust verification at checkout.",
|
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Private Apps inventory correction: an installed app with scope `inventory:write` reports a
|
|
3
|
+
* per-sku, per-location stock delta into the tenant's mirror ledger
|
|
4
|
+
* (`commerce_inventory_movements`, ADR 0033). It is a merchant-consented mirror correction: it
|
|
5
|
+
* never decrements for an order, never reserves, and is never an authoritative provider.
|
|
6
|
+
*
|
|
7
|
+
* One D1 transaction holds admission, movement, audit and receipt. The movement INSERT is the
|
|
8
|
+
* first statement and carries every check as a condition of the insert: the install is active on
|
|
9
|
+
* the host tenant, in the stage's install env, with `inventory:write` in its live scopes; the
|
|
10
|
+
* location is known; the balance stays in range. The audit row and the idempotency record (which
|
|
11
|
+
* holds the receipt) insert only when that movement inserted. Zero rows means refused: no
|
|
12
|
+
* movement, no audit, no receipt.
|
|
13
|
+
*
|
|
14
|
+
* Every movement field the caller could forge is derived here: `asOf` is the server receive time,
|
|
15
|
+
* `source` the app namespace of the install, `sourceEventId` a digest of the namespaced
|
|
16
|
+
* idempotency key, `actorId` the authenticated install.
|
|
17
|
+
*/
|
|
18
|
+
import { isStoredSku, parseSku, skuKey } from "@tot/public-runtime/sku";
|
|
19
|
+
import type { CommerceStage } from "@tot/public-runtime";
|
|
20
|
+
import type { Queryable, QueryStatement } from "../../catalog/d1/catalog.js";
|
|
21
|
+
import {
|
|
22
|
+
guardedCorrectionStatement,
|
|
23
|
+
mirrorLocationKnown,
|
|
24
|
+
MIRROR_LOCATION_UNSPECIFIED,
|
|
25
|
+
type SqlCondition,
|
|
26
|
+
} from "../../inventory/mirrorStock.js";
|
|
27
|
+
import { checkIdempotency, computeBodyHash } from "./orders/idempotency.js";
|
|
28
|
+
|
|
29
|
+
export const INVENTORY_WRITE_SCOPE = "inventory:write";
|
|
30
|
+
export const INVENTORY_AUDIT_EVENT = "inventory.corrected";
|
|
31
|
+
|
|
32
|
+
const ID = /^[A-Za-z0-9._:-]{1,128}$/;
|
|
33
|
+
const IDEMPOTENCY_KEY = /^[\x21-\x7e]{8,128}$/;
|
|
34
|
+
const BODY_KEYS = new Set(["sku", "locationId", "quantityDelta"]);
|
|
35
|
+
/** Fields the platform derives; a body naming any of them is refused, never trusted or ignored. */
|
|
36
|
+
export const SERVER_DERIVED_FIELDS = ["asOf", "source", "sourceEventId", "actorId"] as const;
|
|
37
|
+
|
|
38
|
+
export type InventoryRefusalCode =
|
|
39
|
+
| "malformed"
|
|
40
|
+
| "server-derived-field"
|
|
41
|
+
| "invalid_token"
|
|
42
|
+
| "scope_denied"
|
|
43
|
+
| "denied"
|
|
44
|
+
| "unknown-sku"
|
|
45
|
+
| "unknown-location"
|
|
46
|
+
| "balance-out-of-range"
|
|
47
|
+
| "idempotency-conflict"
|
|
48
|
+
| "unavailable";
|
|
49
|
+
|
|
50
|
+
const STATUS: Record<InventoryRefusalCode, number> = {
|
|
51
|
+
malformed: 400,
|
|
52
|
+
"server-derived-field": 400,
|
|
53
|
+
invalid_token: 401,
|
|
54
|
+
scope_denied: 403,
|
|
55
|
+
denied: 403,
|
|
56
|
+
"unknown-sku": 422,
|
|
57
|
+
"unknown-location": 422,
|
|
58
|
+
"balance-out-of-range": 409,
|
|
59
|
+
"idempotency-conflict": 409,
|
|
60
|
+
unavailable: 503,
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
export interface InventoryReceipt {
|
|
64
|
+
receiptId: string;
|
|
65
|
+
sku: string;
|
|
66
|
+
locationId: string;
|
|
67
|
+
quantityDelta: number;
|
|
68
|
+
asOf: string;
|
|
69
|
+
balance: number;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export interface InventoryWriteResponse {
|
|
73
|
+
status: number;
|
|
74
|
+
body: InventoryReceipt | { code: InventoryRefusalCode; error: string };
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export interface AppInventoryDelta {
|
|
78
|
+
sku: string;
|
|
79
|
+
locationId: string;
|
|
80
|
+
quantityDelta: number;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** The authenticated install a write runs as. Built by the route from the verified token, never from the body. */
|
|
84
|
+
export interface InventoryWriteActor {
|
|
85
|
+
tenantId: string;
|
|
86
|
+
stage: CommerceStage;
|
|
87
|
+
installId: string;
|
|
88
|
+
appId: string;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export function inventoryRefusal(code: InventoryRefusalCode): InventoryWriteResponse {
|
|
92
|
+
if (code === "invalid_token") return { status: 401, body: { code, error: "Unauthorized" } };
|
|
93
|
+
return { status: STATUS[code], body: { code, error: code } };
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
97
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** The body in the closed schema, or the refusal code. */
|
|
101
|
+
export function parseInventoryDelta(body: unknown): AppInventoryDelta | "malformed" | "server-derived-field" {
|
|
102
|
+
if (!isRecord(body)) return "malformed";
|
|
103
|
+
const keys = Object.keys(body);
|
|
104
|
+
if (keys.some((key) => (SERVER_DERIVED_FIELDS as readonly string[]).includes(key))) return "server-derived-field";
|
|
105
|
+
if (keys.some((key) => !BODY_KEYS.has(key))) return "malformed";
|
|
106
|
+
const sku = parseSku(body.sku);
|
|
107
|
+
if (!sku.ok) return "malformed";
|
|
108
|
+
const delta = body.quantityDelta;
|
|
109
|
+
if (typeof delta !== "number" || !Number.isSafeInteger(delta) || delta === 0) return "malformed";
|
|
110
|
+
const location = body.locationId ?? MIRROR_LOCATION_UNSPECIFIED;
|
|
111
|
+
if (typeof location !== "string" || !ID.test(location)) return "malformed";
|
|
112
|
+
return { sku: sku.sku, locationId: location, quantityDelta: delta };
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** The install env a stage admits: the same mapping widget rendering uses (`live` -> production, `test` -> test). */
|
|
116
|
+
export function installEnvForStage(stage: CommerceStage): "production" | "test" {
|
|
117
|
+
return stage === "publication" ? "production" : "test";
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
async function hex(text: string): Promise<string> {
|
|
121
|
+
const bytes = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text)));
|
|
122
|
+
return [...bytes].map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** The idempotency ledger key: tenant, stage, operation and caller key. The install is the ledger's other key column. */
|
|
126
|
+
export function namespacedKey(actor: InventoryWriteActor, key: string): string {
|
|
127
|
+
return ["inventory.write", actor.tenantId, actor.stage, key].join("\n");
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** The movement source: the app namespace of the install. */
|
|
131
|
+
export async function appSource(appId: string): Promise<string> {
|
|
132
|
+
const raw = `app:${appId}`;
|
|
133
|
+
return ID.test(raw) ? raw : `app:${(await hex(appId)).slice(0, 40)}`;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** SQL condition (no leading AND): the install is active on the tenant, in the stage's env, with `inventory:write` live. */
|
|
137
|
+
export function installAdmissionCondition(actor: InventoryWriteActor): SqlCondition {
|
|
138
|
+
return {
|
|
139
|
+
sql: `EXISTS (
|
|
140
|
+
SELECT 1 FROM app_installs AS ai
|
|
141
|
+
WHERE ai.install_id = ? AND ai.tenant_id = ? AND ai.env = ? AND ai.status = 'active'
|
|
142
|
+
AND EXISTS (SELECT 1 FROM json_each(ai.scopes) WHERE json_each.value = '${INVENTORY_WRITE_SCOPE}')
|
|
143
|
+
)`,
|
|
144
|
+
params: [actor.installId, actor.tenantId, installEnvForStage(actor.stage)],
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function lostRace(error: unknown): boolean {
|
|
149
|
+
for (let cause: unknown = error, depth = 0; cause instanceof Error && depth < 4; depth++, cause = cause.cause) {
|
|
150
|
+
if (cause.message.includes("UNIQUE constraint failed")) return true;
|
|
151
|
+
}
|
|
152
|
+
return false;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** Runs the statements as one transaction and returns each one's changed-row count; a unique-key loss is all zeros. */
|
|
156
|
+
async function transact(db: Queryable, statements: readonly QueryStatement[]): Promise<number[]> {
|
|
157
|
+
if (!db.batchResults) throw new Error("transaction-results-required");
|
|
158
|
+
let results: readonly { results: readonly Record<string, unknown>[] }[];
|
|
159
|
+
try {
|
|
160
|
+
results = await db.batchResults(statements.flatMap((statement) => [statement, { sql: "SELECT changes() AS affected" }]));
|
|
161
|
+
} catch (error) {
|
|
162
|
+
if (lostRace(error)) return statements.map(() => 0);
|
|
163
|
+
throw error;
|
|
164
|
+
}
|
|
165
|
+
return statements.map((_, index) => Number(results[index * 2 + 1]?.results[0]?.affected ?? 0));
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function receiptFrom(recorded: unknown): InventoryWriteResponse | null {
|
|
169
|
+
if (!isRecord(recorded) || !Number.isSafeInteger(recorded.status) || !isRecord(recorded.body)) return null;
|
|
170
|
+
return { status: Number(recorded.status), body: recorded.body as unknown as InventoryReceipt };
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
async function priorAnswer(db: Queryable, installId: string, key: string, bodyHash: string): Promise<InventoryWriteResponse | null> {
|
|
174
|
+
const check = await checkIdempotency(db, installId, key, bodyHash);
|
|
175
|
+
if (check.status === "proceed") return null;
|
|
176
|
+
if (check.status === "conflict") return inventoryRefusal("idempotency-conflict");
|
|
177
|
+
return receiptFrom(check.responseBody) ?? inventoryRefusal("idempotency-conflict");
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
export interface InventoryWriteRequest {
|
|
181
|
+
actor: InventoryWriteActor;
|
|
182
|
+
idempotencyKey: string;
|
|
183
|
+
delta: AppInventoryDelta;
|
|
184
|
+
/** The tenant catalog's stored form of `sku`, or null when the catalog has no such sku. */
|
|
185
|
+
resolveSku: (sku: string) => Promise<string | null>;
|
|
186
|
+
now: () => string;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** Applies one app delta; every answer is a receipt or a coded refusal. */
|
|
190
|
+
export async function applyAppInventoryDelta(db: Queryable, request: InventoryWriteRequest): Promise<InventoryWriteResponse> {
|
|
191
|
+
const { actor, delta } = request;
|
|
192
|
+
if (!IDEMPOTENCY_KEY.test(request.idempotencyKey)) return inventoryRefusal("malformed");
|
|
193
|
+
if (!ID.test(actor.installId) || !actor.tenantId) return inventoryRefusal("invalid_token");
|
|
194
|
+
const key = namespacedKey(actor, request.idempotencyKey);
|
|
195
|
+
const bodyHash = await computeBodyHash({ operation: "inventory.write", ...delta });
|
|
196
|
+
const prior = await priorAnswer(db, actor.installId, key, bodyHash);
|
|
197
|
+
if (prior) return prior;
|
|
198
|
+
|
|
199
|
+
const sku = await request.resolveSku(delta.sku);
|
|
200
|
+
if (sku === null || !isStoredSku(sku)) return inventoryRefusal("unknown-sku");
|
|
201
|
+
const asOf = request.now();
|
|
202
|
+
const receiptId = `app.${(await hex(`${actor.installId}\n${key}`)).slice(0, 48)}`;
|
|
203
|
+
const actorId = `app:${actor.installId}`;
|
|
204
|
+
const movement = guardedCorrectionStatement(
|
|
205
|
+
{
|
|
206
|
+
tenantId: actor.tenantId,
|
|
207
|
+
stage: actor.stage,
|
|
208
|
+
source: await appSource(actor.appId),
|
|
209
|
+
sourceEventId: receiptId,
|
|
210
|
+
sku,
|
|
211
|
+
locationId: delta.locationId,
|
|
212
|
+
quantityDelta: delta.quantityDelta,
|
|
213
|
+
asOf,
|
|
214
|
+
actorId,
|
|
215
|
+
},
|
|
216
|
+
installAdmissionCondition(actor),
|
|
217
|
+
);
|
|
218
|
+
const detail = JSON.stringify({ receiptId, sku, locationId: delta.locationId, quantityDelta: delta.quantityDelta });
|
|
219
|
+
const changes = await transact(db, [
|
|
220
|
+
{ sql: movement.sql, params: movement.params },
|
|
221
|
+
{
|
|
222
|
+
sql: `INSERT INTO app_audit_log (id, install_id, tenant_id, event, actor, trace_id, detail, at)
|
|
223
|
+
SELECT ?, ?, ?, '${INVENTORY_AUDIT_EVENT}', ?, NULL, ?, ? WHERE changes() = 1`,
|
|
224
|
+
params: [crypto.randomUUID(), actor.installId, actor.tenantId, actorId, detail, asOf],
|
|
225
|
+
},
|
|
226
|
+
{
|
|
227
|
+
sql: `INSERT INTO idempotency_keys (install_id, idempotency_key, body_hash, response_body, created_at)
|
|
228
|
+
SELECT ?, ?, ?, json_object('status', 201, 'body', json_object(
|
|
229
|
+
'receiptId', ?, 'sku', ?, 'locationId', ?, 'quantityDelta', CAST(? AS INTEGER), 'asOf', ?,
|
|
230
|
+
'balance', (SELECT SUM(quantity_delta) FROM commerce_inventory_movements
|
|
231
|
+
WHERE tenant_id = ? AND stage = ? AND sku = ? AND location_id = ?))), ?
|
|
232
|
+
WHERE changes() = 1`,
|
|
233
|
+
params: [
|
|
234
|
+
actor.installId,
|
|
235
|
+
key,
|
|
236
|
+
bodyHash,
|
|
237
|
+
receiptId,
|
|
238
|
+
sku,
|
|
239
|
+
delta.locationId,
|
|
240
|
+
delta.quantityDelta,
|
|
241
|
+
asOf,
|
|
242
|
+
actor.tenantId,
|
|
243
|
+
actor.stage,
|
|
244
|
+
sku,
|
|
245
|
+
delta.locationId,
|
|
246
|
+
asOf,
|
|
247
|
+
],
|
|
248
|
+
},
|
|
249
|
+
]);
|
|
250
|
+
if ((changes[0] ?? 0) === 1 && (changes[2] ?? 0) === 1) {
|
|
251
|
+
return (await priorAnswer(db, actor.installId, key, bodyHash)) ?? inventoryRefusal("unavailable");
|
|
252
|
+
}
|
|
253
|
+
return classifyRefused(db, actor, delta, key, bodyHash);
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/** Why a write did not commit, read after it: a same-key winner, the install, the location, else the bound. */
|
|
257
|
+
async function classifyRefused(
|
|
258
|
+
db: Queryable,
|
|
259
|
+
actor: InventoryWriteActor,
|
|
260
|
+
delta: AppInventoryDelta,
|
|
261
|
+
key: string,
|
|
262
|
+
bodyHash: string,
|
|
263
|
+
): Promise<InventoryWriteResponse> {
|
|
264
|
+
const prior = await priorAnswer(db, actor.installId, key, bodyHash);
|
|
265
|
+
if (prior) return prior;
|
|
266
|
+
const install = await db.first<{ tenant_id: string; env: string; status: string; scopes: string }>(
|
|
267
|
+
`SELECT tenant_id, env, status, scopes FROM app_installs WHERE install_id = ?`,
|
|
268
|
+
actor.installId,
|
|
269
|
+
);
|
|
270
|
+
if (!install || install.tenant_id !== actor.tenantId || install.status !== "active") return inventoryRefusal("invalid_token");
|
|
271
|
+
if (install.env !== installEnvForStage(actor.stage)) return inventoryRefusal("denied");
|
|
272
|
+
let scopes: unknown = null;
|
|
273
|
+
try {
|
|
274
|
+
scopes = JSON.parse(install.scopes);
|
|
275
|
+
} catch {
|
|
276
|
+
scopes = null;
|
|
277
|
+
}
|
|
278
|
+
if (!Array.isArray(scopes) || !scopes.includes(INVENTORY_WRITE_SCOPE)) return inventoryRefusal("scope_denied");
|
|
279
|
+
if (!(await mirrorLocationKnown(db, { tenantId: actor.tenantId, stage: actor.stage, locationId: delta.locationId }))) {
|
|
280
|
+
return inventoryRefusal("unknown-location");
|
|
281
|
+
}
|
|
282
|
+
return inventoryRefusal("balance-out-of-range");
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/** The stored catalog sku matching `sku` under the platform sku comparison, or null. */
|
|
286
|
+
export function matchCatalogSku(catalogSkus: Iterable<string>, sku: string): string | null {
|
|
287
|
+
const wanted = skuKey(sku);
|
|
288
|
+
for (const candidate of catalogSkus) if (skuKey(candidate) === wanted) return candidate;
|
|
289
|
+
return null;
|
|
290
|
+
}
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* Scope validation — the compliance-floor gate for Storefront Private Apps.
|
|
3
3
|
* See `docs/private-apps/feature-brief.md` §"The
|
|
4
4
|
* compliance floor" and the machine-readable contract:
|
|
5
|
-
* - `docs/private-apps/contract/scopes.json` — the
|
|
5
|
+
* - `docs/private-apps/contract/scopes.json` — the V1 scope catalog.
|
|
6
6
|
* - `docs/private-apps/contract/forbidden-scopes.json` — the 8 ids that map
|
|
7
7
|
* to floor clauses (`checkout:mutate`, `tax:mutate`, …) and must NEVER be
|
|
8
8
|
* grantable.
|
|
@@ -25,6 +25,7 @@ export const V1_SCOPES = [
|
|
|
25
25
|
"orders:webhook",
|
|
26
26
|
"customers:read:minimal",
|
|
27
27
|
"inventory:read",
|
|
28
|
+
"inventory:write",
|
|
28
29
|
"reports:read",
|
|
29
30
|
"attribution:write",
|
|
30
31
|
"widgets:launch",
|
|
@@ -178,18 +178,52 @@ export async function readMirrorBalances(
|
|
|
178
178
|
return balances;
|
|
179
179
|
}
|
|
180
180
|
|
|
181
|
+
/** SQL: the sum of every movement for one balance key except one event. Binds tenant, stage, sku, location, source, event. */
|
|
182
|
+
const OTHER_MOVEMENTS_SUM = `COALESCE((SELECT SUM(quantity_delta) FROM commerce_inventory_movements
|
|
183
|
+
WHERE tenant_id=? AND stage=? AND sku=? AND location_id=? AND NOT (source=? AND source_event_id=?)), 0)`;
|
|
184
|
+
|
|
181
185
|
/**
|
|
182
186
|
* One source on-hand observation. The stored delta is on-hand minus the sum of every other
|
|
183
|
-
* movement,
|
|
187
|
+
* movement, computed inside the insert, so the balance after it is exactly on-hand: a movement
|
|
188
|
+
* committed before it (an app correction included) is absorbed, and one committed after it stays
|
|
189
|
+
* on top. Precedence is commit order; both rows remain. A replay of this event adds nothing, and
|
|
190
|
+
* a replay whose on-hand no longer reproduces the stored delta is a conflict.
|
|
184
191
|
*/
|
|
185
192
|
export async function appendSourceOnHand(
|
|
186
193
|
db: Queryable,
|
|
187
194
|
input: Omit<MirrorMovement, "quantityDelta"> & { onHand: number },
|
|
188
195
|
): Promise<void> {
|
|
189
|
-
if (
|
|
190
|
-
|
|
191
|
-
|
|
196
|
+
if (
|
|
197
|
+
!Number.isSafeInteger(input.onHand) ||
|
|
198
|
+
![input.tenantId, input.source, input.sourceEventId, input.locationId, input.actorId].every((v) => ID.test(v)) ||
|
|
199
|
+
!isStoredSku(input.sku) ||
|
|
200
|
+
!Number.isFinite(Date.parse(input.asOf)) ||
|
|
201
|
+
!["preview", "publication"].includes(input.stage)
|
|
202
|
+
)
|
|
203
|
+
throw new InventoryMovementError("invalid-movement");
|
|
204
|
+
const others = [input.tenantId, input.stage, input.sku, input.locationId, input.source, input.sourceEventId];
|
|
205
|
+
await db.run(
|
|
206
|
+
`INSERT INTO commerce_inventory_movements
|
|
207
|
+
(tenant_id,stage,source,source_event_id,sku,location_id,quantity_delta,as_of,actor_id)
|
|
208
|
+
SELECT ?,?,?,?,?,?,CAST(? AS INTEGER) - ${OTHER_MOVEMENTS_SUM},?,? WHERE true
|
|
209
|
+
ON CONFLICT DO NOTHING`,
|
|
210
|
+
input.tenantId,
|
|
211
|
+
input.stage,
|
|
212
|
+
input.source,
|
|
213
|
+
input.sourceEventId,
|
|
214
|
+
input.sku,
|
|
215
|
+
input.locationId,
|
|
216
|
+
input.onHand,
|
|
217
|
+
...others,
|
|
218
|
+
input.asOf,
|
|
219
|
+
input.actorId,
|
|
220
|
+
);
|
|
221
|
+
const actual = await db.first<{ quantity_delta: number; as_of: string; actor_id: string; expected: number }>(
|
|
222
|
+
`SELECT quantity_delta, as_of, actor_id, CAST(? AS INTEGER) - ${OTHER_MOVEMENTS_SUM} AS expected
|
|
223
|
+
FROM commerce_inventory_movements
|
|
192
224
|
WHERE tenant_id=? AND stage=? AND source=? AND source_event_id=? AND sku=? AND location_id=?`,
|
|
225
|
+
input.onHand,
|
|
226
|
+
...others,
|
|
193
227
|
input.tenantId,
|
|
194
228
|
input.stage,
|
|
195
229
|
input.source,
|
|
@@ -197,11 +231,95 @@ export async function appendSourceOnHand(
|
|
|
197
231
|
input.sku,
|
|
198
232
|
input.locationId,
|
|
199
233
|
);
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
234
|
+
if (
|
|
235
|
+
!actual ||
|
|
236
|
+
Number(actual.quantity_delta) !== Number(actual.expected) ||
|
|
237
|
+
actual.as_of !== input.asOf ||
|
|
238
|
+
actual.actor_id !== input.actorId
|
|
239
|
+
)
|
|
240
|
+
throw new InventoryMovementError("conflict");
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/** The largest balance a key may hold: the mirror ledger never stores or reports an unsafe integer. */
|
|
244
|
+
export const MIRROR_BALANCE_MAX = Number.MAX_SAFE_INTEGER;
|
|
245
|
+
|
|
246
|
+
export interface SqlCondition {
|
|
247
|
+
sql: string;
|
|
248
|
+
params: readonly unknown[];
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/**
|
|
252
|
+
* A guarded correction: one INSERT that writes `movement` only when every check holds at write
|
|
253
|
+
* time, inside the statement. The balance after it stays within 0..MIRROR_BALANCE_MAX, except
|
|
254
|
+
* that a positive delta on a negative balance is admitted because it moves the balance toward
|
|
255
|
+
* zero; overflow is always refused, never clamped. The location is `unspecified` or one the
|
|
256
|
+
* tenant's movements for that stage already name. `guard` is an SQL condition (no leading AND)
|
|
257
|
+
* the caller's admission adds. Zero rows changed means refused.
|
|
258
|
+
*/
|
|
259
|
+
export function guardedCorrectionStatement(movement: MirrorMovement, guard: SqlCondition): SqlCondition {
|
|
260
|
+
if (
|
|
261
|
+
![movement.tenantId, movement.source, movement.sourceEventId, movement.locationId, movement.actorId].every((v) =>
|
|
262
|
+
ID.test(v),
|
|
263
|
+
) ||
|
|
264
|
+
!isStoredSku(movement.sku) ||
|
|
265
|
+
!Number.isSafeInteger(movement.quantityDelta) ||
|
|
266
|
+
movement.quantityDelta === 0 ||
|
|
267
|
+
!Number.isFinite(Date.parse(movement.asOf)) ||
|
|
268
|
+
!["preview", "publication"].includes(movement.stage)
|
|
269
|
+
)
|
|
270
|
+
throw new InventoryMovementError("invalid-movement");
|
|
271
|
+
const delta = movement.quantityDelta;
|
|
272
|
+
return {
|
|
273
|
+
sql: `INSERT INTO commerce_inventory_movements
|
|
274
|
+
(tenant_id,stage,source,source_event_id,sku,location_id,quantity_delta,as_of,actor_id)
|
|
275
|
+
SELECT ?,?,?,?,?,?,CAST(? AS INTEGER),?,?
|
|
276
|
+
FROM (SELECT COALESCE(SUM(quantity_delta), 0) AS balance FROM commerce_inventory_movements
|
|
277
|
+
WHERE tenant_id=? AND stage=? AND sku=? AND location_id=?) AS current
|
|
278
|
+
WHERE current.balance + CAST(? AS INTEGER) <= ${MIRROR_BALANCE_MAX}
|
|
279
|
+
AND (current.balance + CAST(? AS INTEGER) >= 0 OR CAST(? AS INTEGER) > 0)
|
|
280
|
+
AND (? = '${MIRROR_LOCATION_UNSPECIFIED}' OR EXISTS (
|
|
281
|
+
SELECT 1 FROM commerce_inventory_movements WHERE tenant_id=? AND stage=? AND location_id=?
|
|
282
|
+
))
|
|
283
|
+
AND (${guard.sql})`,
|
|
284
|
+
params: [
|
|
285
|
+
movement.tenantId,
|
|
286
|
+
movement.stage,
|
|
287
|
+
movement.source,
|
|
288
|
+
movement.sourceEventId,
|
|
289
|
+
movement.sku,
|
|
290
|
+
movement.locationId,
|
|
291
|
+
delta,
|
|
292
|
+
movement.asOf,
|
|
293
|
+
movement.actorId,
|
|
294
|
+
movement.tenantId,
|
|
295
|
+
movement.stage,
|
|
296
|
+
movement.sku,
|
|
297
|
+
movement.locationId,
|
|
298
|
+
delta,
|
|
299
|
+
delta,
|
|
300
|
+
delta,
|
|
301
|
+
movement.locationId,
|
|
302
|
+
movement.tenantId,
|
|
303
|
+
movement.stage,
|
|
304
|
+
movement.locationId,
|
|
305
|
+
...guard.params,
|
|
306
|
+
],
|
|
307
|
+
};
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/** True when `locationId` is one a guarded correction may name for this tenant and stage. */
|
|
311
|
+
export async function mirrorLocationKnown(
|
|
312
|
+
db: Queryable,
|
|
313
|
+
input: { tenantId: string; stage: CommerceStage; locationId: string },
|
|
314
|
+
): Promise<boolean> {
|
|
315
|
+
if (input.locationId === MIRROR_LOCATION_UNSPECIFIED) return true;
|
|
316
|
+
const row = await db.first<{ n: number }>(
|
|
317
|
+
`SELECT 1 AS n FROM commerce_inventory_movements WHERE tenant_id=? AND stage=? AND location_id=? LIMIT 1`,
|
|
318
|
+
input.tenantId,
|
|
319
|
+
input.stage,
|
|
320
|
+
input.locationId,
|
|
321
|
+
);
|
|
322
|
+
return row !== null;
|
|
205
323
|
}
|
|
206
324
|
|
|
207
325
|
export async function catalogImportEventId(runId: string, sku: string, onHand: number): Promise<string> {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tokenoftrust/storefront-runner",
|
|
3
|
-
"version": "6.
|
|
3
|
+
"version": "6.9.0",
|
|
4
4
|
"license": "SEE LICENSE IN LICENSE",
|
|
5
5
|
"description": "World-shareable storefront runner: multi-tenant renderer on Astro/Cloudflare. No control plane.",
|
|
6
6
|
"packageManager": "pnpm@11.9.0",
|
|
@@ -338,6 +338,13 @@ export const ACTION_CATALOG = {
|
|
|
338
338
|
argsAllow: ["versionId", "scope", ...OPERATIONAL_READ_BACK_ARGS], renderedAllow: [],
|
|
339
339
|
desc: "A store's checkout requirements were saved to a version.",
|
|
340
340
|
},
|
|
341
|
+
"content.checkout_excise.saved": {
|
|
342
|
+
// A store's excise setting (Settings → Checkout requirements) was saved to the store's
|
|
343
|
+
// operational selection. Same actors, spine and read-back args as the checkout requirements.
|
|
344
|
+
actors: ["merchant", "admin"], source: "server", sinks: LIFECYCLE,
|
|
345
|
+
argsAllow: ["versionId", "scope", ...OPERATIONAL_READ_BACK_ARGS], renderedAllow: [],
|
|
346
|
+
desc: "A store's excise setting was saved to a version.",
|
|
347
|
+
},
|
|
341
348
|
"content.operational_setting.published": {
|
|
342
349
|
// An operational setting's saved draft (checkout requirements or styling) was made the live
|
|
343
350
|
// store's value (/api/preview/settings-live). `scope` names the setting.
|
|
@@ -239,9 +239,10 @@ export class CartSigningUnavailableError extends Error {
|
|
|
239
239
|
* ref when the gate produced one (`withVerificationRef`). `shipping_policy` carries the
|
|
240
240
|
* store's declared shipping charge (`withShippingPolicy`). `return_url` carries the page the
|
|
241
241
|
* shopper submitted from (`withReturnUrl`). `content_version` carries the candidate
|
|
242
|
-
* content pin the page rendered, and only then.
|
|
242
|
+
* content pin the page rendered, and only then. `excise` carries the store's excise setting
|
|
243
|
+
* (`withExcise`), `on` or `off`.
|
|
243
244
|
*/
|
|
244
|
-
export const INTERNAL_CART_FIELDS = ["currency", "tenant", "verification", "shipping_policy", "return_url", "content_version"] as const;
|
|
245
|
+
export const INTERNAL_CART_FIELDS = ["currency", "tenant", "verification", "shipping_policy", "return_url", "content_version", "excise"] as const;
|
|
245
246
|
|
|
246
247
|
/** Signed cart option naming the content version the preview page rendered. */
|
|
247
248
|
export const CONTENT_VERSION_CART_FIELD = "content_version";
|
|
@@ -265,6 +266,9 @@ export const RETURN_URL_CART_FIELD = "return_url";
|
|
|
265
266
|
*/
|
|
266
267
|
export const CHECKOUT_NAVIGATION_REFERRER_POLICY = "no-referrer-when-downgrade";
|
|
267
268
|
|
|
269
|
+
/** The signed cart option the checkout store reads the store's excise setting from. */
|
|
270
|
+
export const EXCISE_CART_FIELD = "excise";
|
|
271
|
+
|
|
268
272
|
/** The signed cart option the checkout store reads the shipping charge from. */
|
|
269
273
|
export const SHIPPING_POLICY_CART_FIELD = "shipping_policy";
|
|
270
274
|
|
|
@@ -1048,6 +1052,25 @@ export async function withShippingPolicy(
|
|
|
1048
1052
|
return [...kept, await signField(opts.secret, code, field)];
|
|
1049
1053
|
}
|
|
1050
1054
|
|
|
1055
|
+
/**
|
|
1056
|
+
* Bind the store's excise setting into an enforced cart as the internal `excise` option (`on` or
|
|
1057
|
+
* `off`), signed against the cart's product code. Any `excise` the shopper submitted is dropped
|
|
1058
|
+
* first, so only the store's own setting reaches the cart. A cart with no product code is
|
|
1059
|
+
* returned without one.
|
|
1060
|
+
*/
|
|
1061
|
+
export async function withExcise(
|
|
1062
|
+
fields: readonly CartSubmissionField[],
|
|
1063
|
+
opts: { mode: ManagedCheckoutConfig["mode"]; secret?: string; excise: boolean },
|
|
1064
|
+
): Promise<CartSubmissionField[]> {
|
|
1065
|
+
const kept = fields.filter((field) => field.name.split("||")[0] !== EXCISE_CART_FIELD);
|
|
1066
|
+
const code = kept.find((field) => field.name.split("||")[0] === "code")?.value;
|
|
1067
|
+
if (!code) return kept;
|
|
1068
|
+
const field: CartField = { name: EXCISE_CART_FIELD, value: opts.excise ? "on" : "off" };
|
|
1069
|
+
if (opts.mode !== "signed") return [...kept, unsignedField(field)];
|
|
1070
|
+
if (!opts.secret) throw new CartSigningUnavailableError();
|
|
1071
|
+
return [...kept, await signField(opts.secret, code, field)];
|
|
1072
|
+
}
|
|
1073
|
+
|
|
1051
1074
|
const MAX_RETURN_URL_LENGTH = 1500;
|
|
1052
1075
|
|
|
1053
1076
|
/**
|
|
@@ -87,7 +87,7 @@ export const CATALOG_LISTING_ARTIFACT = "catalog-listing.json";
|
|
|
87
87
|
* or carried by a preview→live promotion. A store with no live site yet saves to both. A path not
|
|
88
88
|
* listed here is repo-authored content: a channel pointer, when engaged, owns it.
|
|
89
89
|
*/
|
|
90
|
-
export const OPERATIONAL_SETTING_FILES = Object.freeze(["checkout-requirements.json", "checkout-style.json"] as const);
|
|
90
|
+
export const OPERATIONAL_SETTING_FILES = Object.freeze(["checkout-requirements.json", "checkout-style.json", "checkout-excise.json"] as const);
|
|
91
91
|
export type OperationalSettingFile = (typeof OPERATIONAL_SETTING_FILES)[number];
|
|
92
92
|
|
|
93
93
|
export function operationalSettingArtifactPath(tenantId: string, file: OperationalSettingFile): string {
|