@tokenoftrust/storefront-runner 6.9.1 → 6.10.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/components/compliance/storefront/compliance/ExciseTaxNotice.astro +15 -3
- package/apps/storefront/src/lib/checkout/commerce/checkoutRequirements.ts +33 -4
- package/apps/storefront/src/lib/checkout/commerce/sharedStoreAdmission.ts +158 -1
- package/apps/storefront/src/lib/orders/admin/orderSource.ts +15 -1
- package/apps/storefront/src/lib/orders/admin/services/orders.ts +19 -3
- package/apps/storefront/src/pages/api/commerce/final-cart-authorization.ts +40 -12
- package/package.json +1 -1
- package/packages/public-runtime/src/checkout-orders.ts +58 -0
- package/packages/public-runtime/src/checkout.ts +2 -0
package/apps/storefront/src/components/compliance/storefront/compliance/ExciseTaxNotice.astro
CHANGED
|
@@ -9,19 +9,26 @@
|
|
|
9
9
|
* spans (valid inside the primitive's paragraph) so it re-skins with the theme
|
|
10
10
|
* and never fabricates a figure the tenant didn't provide.
|
|
11
11
|
*/
|
|
12
|
-
import type
|
|
12
|
+
import { exciseTaxEngineLabel, type ExciseEngineTier, type ExciseTaxConfig } from "@tot/public-runtime";
|
|
13
13
|
import ComplianceNotice from "./ComplianceNotice.astro";
|
|
14
14
|
|
|
15
15
|
interface Props {
|
|
16
16
|
/** From tenant.compliance.exciseTax. */
|
|
17
17
|
config?: ExciseTaxConfig;
|
|
18
18
|
variant?: "bar" | "block" | "inline" | "footer";
|
|
19
|
+
engineTier?: ExciseEngineTier;
|
|
20
|
+
amountMinor?: number;
|
|
19
21
|
}
|
|
20
22
|
|
|
21
|
-
const { config, variant = "inline" } = Astro.props;
|
|
23
|
+
const { config, variant = "inline", engineTier, amountMinor } = Astro.props;
|
|
22
24
|
|
|
23
25
|
const note = config?.note?.trim();
|
|
24
26
|
const jurisdictions = (config?.jurisdictions ?? []).filter((j) => j && j.label && j.detail);
|
|
27
|
+
const noticeLabel = engineTier ? exciseTaxEngineLabel(engineTier) : "Excise tax notice";
|
|
28
|
+
const formattedAmount =
|
|
29
|
+
typeof amountMinor === "number" && Number.isSafeInteger(amountMinor) && amountMinor >= 0
|
|
30
|
+
? `$${(amountMinor / 100).toFixed(2)}`
|
|
31
|
+
: null;
|
|
25
32
|
---
|
|
26
33
|
|
|
27
34
|
{
|
|
@@ -30,9 +37,14 @@ const jurisdictions = (config?.jurisdictions ?? []).filter((j) => j && j.label &
|
|
|
30
37
|
variant={variant}
|
|
31
38
|
tone="info"
|
|
32
39
|
hook="excise-tax"
|
|
33
|
-
label=
|
|
40
|
+
label={noticeLabel}
|
|
34
41
|
>
|
|
35
42
|
{note}
|
|
43
|
+
{formattedAmount && (
|
|
44
|
+
<span class="ml-1.5 whitespace-nowrap text-[var(--color-muted)]" data-excise-amount={amountMinor}>
|
|
45
|
+
· <span class="font-semibold">{noticeLabel}</span> {formattedAmount}
|
|
46
|
+
</span>
|
|
47
|
+
)}
|
|
36
48
|
{jurisdictions.length > 0 &&
|
|
37
49
|
jurisdictions.map((j) => (
|
|
38
50
|
<span class="ml-1.5 whitespace-nowrap text-[var(--color-muted)]">
|
|
@@ -14,16 +14,28 @@
|
|
|
14
14
|
*/
|
|
15
15
|
import { operationalSettingArtifactPath, readPublishedArtifact, type CustomizationEnv } from "@tot/public-runtime";
|
|
16
16
|
import { readKv } from "@/lib/publication/shared/runtimeEnv";
|
|
17
|
+
import { checkoutStoreHasExciseProducer } from "./sharedStoreAdmission";
|
|
17
18
|
|
|
18
19
|
export interface CheckoutRequirements {
|
|
19
20
|
/** Require a real ID verification the final-cart authority re-reads server-side. */
|
|
20
21
|
verification: boolean;
|
|
21
|
-
/** Require tax evidence
|
|
22
|
+
/** Require tax evidence from the checkout store's excise tax producer. */
|
|
22
23
|
tax: boolean;
|
|
23
24
|
/** Enforce compliance rules (destination, flavor, purchase limits). */
|
|
24
25
|
rules: boolean;
|
|
25
26
|
}
|
|
26
27
|
|
|
28
|
+
export const MISSING_EXCISE_PRODUCER_BLOCKER = "Needs an excise tax producer on this checkout store";
|
|
29
|
+
export const MISSING_EXCISE_PRODUCER_REFUSAL =
|
|
30
|
+
"Tax evidence can't be required: this checkout store has no excise tax producer.";
|
|
31
|
+
|
|
32
|
+
export function checkoutStoreTaxBlocker(
|
|
33
|
+
commerce: { storeSubDomain?: unknown; exciseProducer?: unknown } | null | undefined,
|
|
34
|
+
declarations?: Readonly<Record<string, { exciseProducer?: unknown }>> | null,
|
|
35
|
+
): string | null {
|
|
36
|
+
return checkoutStoreHasExciseProducer(commerce, declarations) ? null : MISSING_EXCISE_PRODUCER_BLOCKER;
|
|
37
|
+
}
|
|
38
|
+
|
|
27
39
|
export const CHECKOUT_REQUIREMENT_KEYS = ["verification", "tax", "rules"] as const;
|
|
28
40
|
|
|
29
41
|
export const DEFAULT_CHECKOUT_REQUIREMENTS: Readonly<CheckoutRequirements> = Object.freeze({
|
|
@@ -65,8 +77,17 @@ export type CheckoutRequirementsInput =
|
|
|
65
77
|
| { ok: true; requirements: CheckoutRequirements }
|
|
66
78
|
| { ok: false; errors: string[] };
|
|
67
79
|
|
|
68
|
-
|
|
69
|
-
|
|
80
|
+
export interface ValidateCheckoutRequirementsOptions {
|
|
81
|
+
hasExciseProducer?: boolean;
|
|
82
|
+
checkoutStore?: { storeSubDomain?: unknown; exciseProducer?: unknown } | null;
|
|
83
|
+
declarations?: Readonly<Record<string, { exciseProducer?: unknown }>> | null;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** Validate a save from /admin. Tax evidence requires an excise producer on the checkout store. */
|
|
87
|
+
export function validateCheckoutRequirementsInput(
|
|
88
|
+
raw: unknown,
|
|
89
|
+
options: ValidateCheckoutRequirementsOptions = {},
|
|
90
|
+
): CheckoutRequirementsInput {
|
|
70
91
|
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return { ok: false, errors: ["body must be a JSON object"] };
|
|
71
92
|
const body = raw as Record<string, unknown>;
|
|
72
93
|
const errors: string[] = [];
|
|
@@ -75,7 +96,15 @@ export function validateCheckoutRequirementsInput(raw: unknown): CheckoutRequire
|
|
|
75
96
|
if (typeof body[key] !== "boolean") errors.push(`${key} must be true or false`);
|
|
76
97
|
else requirements[key] = body[key] as boolean;
|
|
77
98
|
}
|
|
78
|
-
|
|
99
|
+
const hasProducer =
|
|
100
|
+
typeof options.hasExciseProducer === "boolean"
|
|
101
|
+
? options.hasExciseProducer
|
|
102
|
+
: "checkoutStore" in options || "declarations" in options
|
|
103
|
+
? checkoutStoreHasExciseProducer(options.checkoutStore, options.declarations)
|
|
104
|
+
: true;
|
|
105
|
+
if (requirements.tax && !hasProducer) {
|
|
106
|
+
errors.push(MISSING_EXCISE_PRODUCER_REFUSAL);
|
|
107
|
+
}
|
|
79
108
|
return errors.length ? { ok: false, errors } : { ok: true, requirements };
|
|
80
109
|
}
|
|
81
110
|
|
|
@@ -7,7 +7,19 @@
|
|
|
7
7
|
* secret is therefore never issued to a partner. Production never declares the test tier, so it
|
|
8
8
|
* admits no one here.
|
|
9
9
|
*/
|
|
10
|
-
import {
|
|
10
|
+
import {
|
|
11
|
+
commerceTenantId,
|
|
12
|
+
isRegulated,
|
|
13
|
+
SHARED_DEMO_CHECKOUT,
|
|
14
|
+
type CommerceAuthoritySource,
|
|
15
|
+
type CustomizationEnv,
|
|
16
|
+
type ExciseCarrier,
|
|
17
|
+
type ExciseEngineTier,
|
|
18
|
+
type ExciseEvidenceReason,
|
|
19
|
+
type FinalCartLine,
|
|
20
|
+
type MinorTotals,
|
|
21
|
+
type TenantConfig,
|
|
22
|
+
} from "@tot/public-runtime";
|
|
11
23
|
import { resolveAdminTargetTenant } from "@/config/adminTargetTenant";
|
|
12
24
|
import { resolveTenantCommerce } from "@/lib/checkout/shared/checkoutCommerce";
|
|
13
25
|
import { readEnv } from "@/lib/publication/shared/runtimeEnv";
|
|
@@ -47,9 +59,154 @@ export const SHARED_STORE_POLICY_REVISION = "shared-test-store-v1";
|
|
|
47
59
|
export const SHARED_STORE_VERIFICATION_SOURCE = "tot-verification-provider";
|
|
48
60
|
/** Provenance stamped on verification the sandbox profile simulated for an internal-test tenant. */
|
|
49
61
|
export const SHARED_STORE_SANDBOX_VERIFICATION_SOURCE = "tot-sandbox-verification";
|
|
62
|
+
/** Provenance stamped on tax evidence resolved from the checkout store's signed excise carrier. */
|
|
63
|
+
export const SHARED_STORE_TAX_SOURCE = "provider-computed-tax";
|
|
50
64
|
/** The cart's signed `verification` ref that asks the sandbox profile to simulate a cleared verification. */
|
|
51
65
|
export const SANDBOX_CLEARED_REF = /^sandbox-cleared:[a-zA-Z0-9._-]{1,64}$/;
|
|
52
66
|
|
|
67
|
+
export interface CheckoutStoreDeclaration {
|
|
68
|
+
readonly exciseProducer: boolean;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Platform declarations for managed checkout stores. Default-on for the shared test store;
|
|
73
|
+
* an unknown or unreadable declaration fails closed (`false`).
|
|
74
|
+
*/
|
|
75
|
+
export const CHECKOUT_STORE_DECLARATIONS: Readonly<Record<string, CheckoutStoreDeclaration>> = Object.freeze({
|
|
76
|
+
[SHARED_DEMO_CHECKOUT.storeSubDomain]: Object.freeze({ exciseProducer: true }),
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Whether a store's resolved checkout store declares an excise tax producer.
|
|
81
|
+
* Fails closed (`false`) when the checkout store or declaration is absent or unreadable.
|
|
82
|
+
*/
|
|
83
|
+
export function checkoutStoreHasExciseProducer(
|
|
84
|
+
commerce: { storeSubDomain?: unknown; exciseProducer?: unknown } | null | undefined,
|
|
85
|
+
declarations: Readonly<Record<string, { exciseProducer?: unknown }>> | null | undefined = CHECKOUT_STORE_DECLARATIONS,
|
|
86
|
+
): boolean {
|
|
87
|
+
if (!commerce || typeof commerce !== "object") return false;
|
|
88
|
+
if ("exciseProducer" in commerce && commerce.exciseProducer !== undefined) {
|
|
89
|
+
return commerce.exciseProducer === true;
|
|
90
|
+
}
|
|
91
|
+
if (!declarations || typeof declarations !== "object") return false;
|
|
92
|
+
const subDomain = commerce.storeSubDomain;
|
|
93
|
+
if (typeof subDomain !== "string" || !subDomain.trim()) return false;
|
|
94
|
+
const entry = declarations[subDomain];
|
|
95
|
+
return Boolean(entry && typeof entry === "object" && entry.exciseProducer === true);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
async function sha256Hex(value: string): Promise<string> {
|
|
99
|
+
return [...new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(value)))]
|
|
100
|
+
.map(b => b.toString(16).padStart(2, "0"))
|
|
101
|
+
.join("");
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Lowercase hex SHA-256 of the JSON (no whitespace) of the `[sku, quantity, unitMinor]` triples,
|
|
106
|
+
* sorted by `sku` in code-unit order, with each `sku` exactly as the signed wire snapshot carries it.
|
|
107
|
+
*/
|
|
108
|
+
export async function exciseLinesDigest(
|
|
109
|
+
lines: readonly { sku: string; quantity: number; unitMinor: number }[],
|
|
110
|
+
): Promise<string> {
|
|
111
|
+
const triples = lines
|
|
112
|
+
.map(line => [line.sku, line.quantity, line.unitMinor] as const)
|
|
113
|
+
.sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : a[1] - b[1] || a[2] - b[2]));
|
|
114
|
+
return sha256Hex(JSON.stringify(triples));
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export interface ResolveTaxEvidenceInput {
|
|
118
|
+
wireLines: readonly FinalCartLine[];
|
|
119
|
+
destinationDigest: string;
|
|
120
|
+
totals: MinorTotals & { exciseMinor?: number };
|
|
121
|
+
excise?: ExciseCarrier;
|
|
122
|
+
hasProducer?: boolean;
|
|
123
|
+
policyRevision?: string;
|
|
124
|
+
expiresAt: string;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export interface ResolvedTaxEvidence {
|
|
128
|
+
state: "computed" | "not-computed";
|
|
129
|
+
evidenceState: "fresh" | "not-computed";
|
|
130
|
+
amountMinor?: number;
|
|
131
|
+
engineTier?: ExciseEngineTier;
|
|
132
|
+
reason: ExciseEvidenceReason;
|
|
133
|
+
provenance: CommerceAuthoritySource;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* Pure tax-evidence resolver for a tax-required final cart.
|
|
138
|
+
* Marks tax evidence `computed` (`evidenceState: "fresh"`) only when the checkout store has a
|
|
139
|
+
* declared producer and the signed snapshot carries a `computed` excise carrier whose `linesDigest`
|
|
140
|
+
* matches storefront's recomputation over the signed wire lines (before `keyedLines`), whose
|
|
141
|
+
* `destinationDigest` matches the snapshot's, and whose `amountMinor` reconciles with the signed totals.
|
|
142
|
+
* Every other case yields `state: "not-computed"` (`evidenceState: "not-computed"`) with a closed
|
|
143
|
+
* `unavailable:<reason>` provenance reason.
|
|
144
|
+
*/
|
|
145
|
+
export async function resolveTaxEvidence(input: ResolveTaxEvidenceInput): Promise<ResolvedTaxEvidence> {
|
|
146
|
+
const policyRevision = input.policyRevision ?? SHARED_STORE_POLICY_REVISION;
|
|
147
|
+
const expiresAt = input.expiresAt;
|
|
148
|
+
const notComputed = (reason: ExciseEvidenceReason, engineTier?: ExciseEngineTier): ResolvedTaxEvidence => ({
|
|
149
|
+
state: "not-computed",
|
|
150
|
+
evidenceState: "not-computed",
|
|
151
|
+
...(engineTier ? { engineTier } : {}),
|
|
152
|
+
reason,
|
|
153
|
+
provenance: {
|
|
154
|
+
requirement: "required",
|
|
155
|
+
state: "not-computed",
|
|
156
|
+
source: SHARED_STORE_TAX_SOURCE,
|
|
157
|
+
policyRevision,
|
|
158
|
+
expiresAt,
|
|
159
|
+
...(engineTier ? { engineTier } : {}),
|
|
160
|
+
reason,
|
|
161
|
+
},
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
if (input.hasProducer === false) {
|
|
165
|
+
return notComputed("unavailable:producer-undeclared");
|
|
166
|
+
}
|
|
167
|
+
const carrier = input.excise;
|
|
168
|
+
if (!carrier) {
|
|
169
|
+
return notComputed("unavailable:carrier-absent");
|
|
170
|
+
}
|
|
171
|
+
if (carrier.status === "not-computed") {
|
|
172
|
+
return notComputed(`unavailable:${carrier.reason}`, carrier.engineTier);
|
|
173
|
+
}
|
|
174
|
+
const expectedLinesDigest = await exciseLinesDigest(input.wireLines);
|
|
175
|
+
if (carrier.linesDigest !== expectedLinesDigest) {
|
|
176
|
+
return notComputed("unavailable:carrier-lines-mismatch", carrier.engineTier);
|
|
177
|
+
}
|
|
178
|
+
if (carrier.destinationDigest !== input.destinationDigest) {
|
|
179
|
+
return notComputed("unavailable:carrier-destination-mismatch", carrier.engineTier);
|
|
180
|
+
}
|
|
181
|
+
const totalsReconcile = typeof input.totals.exciseMinor === "number"
|
|
182
|
+
? Number.isSafeInteger(input.totals.exciseMinor) &&
|
|
183
|
+
input.totals.exciseMinor >= 0 &&
|
|
184
|
+
input.totals.subtotalMinor + input.totals.shippingMinor + input.totals.taxMinor + input.totals.exciseMinor === input.totals.totalMinor &&
|
|
185
|
+
carrier.amountMinor === input.totals.exciseMinor
|
|
186
|
+
: input.totals.subtotalMinor + input.totals.shippingMinor + input.totals.taxMinor === input.totals.totalMinor &&
|
|
187
|
+
carrier.amountMinor === input.totals.taxMinor;
|
|
188
|
+
if (!totalsReconcile) {
|
|
189
|
+
return notComputed("unavailable:carrier-amount-unreconciled", carrier.engineTier);
|
|
190
|
+
}
|
|
191
|
+
return {
|
|
192
|
+
state: "computed",
|
|
193
|
+
evidenceState: "fresh",
|
|
194
|
+
amountMinor: carrier.amountMinor,
|
|
195
|
+
engineTier: carrier.engineTier,
|
|
196
|
+
reason: "computed",
|
|
197
|
+
provenance: {
|
|
198
|
+
requirement: "required",
|
|
199
|
+
state: "satisfied",
|
|
200
|
+
source: SHARED_STORE_TAX_SOURCE,
|
|
201
|
+
policyRevision,
|
|
202
|
+
expiresAt,
|
|
203
|
+
engineTier: carrier.engineTier,
|
|
204
|
+
reason: "computed",
|
|
205
|
+
amountMinor: carrier.amountMinor,
|
|
206
|
+
},
|
|
207
|
+
};
|
|
208
|
+
}
|
|
209
|
+
|
|
53
210
|
/**
|
|
54
211
|
* What the shared test store requires of a tenant. A regulated tenant (`isRegulated`) always
|
|
55
212
|
* requires verification, tax and enforced rules, whatever the store saved. For any other tenant
|
|
@@ -252,6 +252,20 @@ function ledgerOrder(entry: CommerceOrderBookEntry, contactAvailability: OrderCo
|
|
|
252
252
|
verification[`${key}Source`] = entry.admitted?.provenance[key].source ?? "commerce-ledger";
|
|
253
253
|
verification[`${key}AsOf`] = placedAt;
|
|
254
254
|
}
|
|
255
|
+
const taxProvenance = entry.admitted?.provenance.tax;
|
|
256
|
+
if (typeof taxProvenance?.reason === "string" && taxProvenance.reason.length > 0) {
|
|
257
|
+
verification.taxReason = taxProvenance.reason;
|
|
258
|
+
}
|
|
259
|
+
if (taxProvenance?.engineTier === "test" || taxProvenance?.engineTier === "production") {
|
|
260
|
+
verification.taxEngineTier = taxProvenance.engineTier;
|
|
261
|
+
}
|
|
262
|
+
const exciseMinor =
|
|
263
|
+
evidence.tax === "fresh" && typeof taxProvenance?.amountMinor === "number"
|
|
264
|
+
? taxProvenance.amountMinor
|
|
265
|
+
: undefined;
|
|
266
|
+
if (exciseMinor !== undefined) {
|
|
267
|
+
verification.taxAmountMinor = String(exciseMinor);
|
|
268
|
+
}
|
|
255
269
|
|
|
256
270
|
const summary: CheckoutOrderSummary = {
|
|
257
271
|
id: entry.orderId,
|
|
@@ -276,7 +290,7 @@ function ledgerOrder(entry: CommerceOrderBookEntry, contactAvailability: OrderCo
|
|
|
276
290
|
subtotal: toMajor(totals.subtotalMinor),
|
|
277
291
|
shipping: toMajor(totals.shippingMinor),
|
|
278
292
|
estimatedTax: toMajor(totals.taxMinor),
|
|
279
|
-
taxesAndFees: 0,
|
|
293
|
+
taxesAndFees: exciseMinor !== undefined ? toMajor(exciseMinor) : 0,
|
|
280
294
|
total: toMajor(totals.totalMinor),
|
|
281
295
|
},
|
|
282
296
|
shippingAddress: null,
|
|
@@ -33,6 +33,7 @@ import {
|
|
|
33
33
|
actorMayCommand,
|
|
34
34
|
decideCommerceCommand,
|
|
35
35
|
evidencePermitsRelease,
|
|
36
|
+
exciseTaxEngineLabel,
|
|
36
37
|
paginateOrders,
|
|
37
38
|
paymentIsCaptured,
|
|
38
39
|
publicCommerceEvent,
|
|
@@ -478,6 +479,23 @@ function deriveReadinessChecks(d: CheckoutOrderDetail, scope: CommerceScope): Or
|
|
|
478
479
|
const tax = column("tax");
|
|
479
480
|
const verification = column("verification");
|
|
480
481
|
const ageHold = d.blocker === "Age verification hold";
|
|
482
|
+
const taxReason =
|
|
483
|
+
typeof d.verification?.taxReason === "string" && d.verification.taxReason.length > 0
|
|
484
|
+
? d.verification.taxReason
|
|
485
|
+
: null;
|
|
486
|
+
const taxEngineTier =
|
|
487
|
+
d.verification?.taxEngineTier === "test" || d.verification?.taxEngineTier === "production"
|
|
488
|
+
? d.verification.taxEngineTier
|
|
489
|
+
: null;
|
|
490
|
+
const taxEngineLabel = taxEngineTier ? exciseTaxEngineLabel(taxEngineTier) : null;
|
|
491
|
+
const taxDetail =
|
|
492
|
+
tax.state === "not-computed"
|
|
493
|
+
? taxEngineLabel || taxReason
|
|
494
|
+
? `${taxEngineLabel ? `${taxEngineLabel}: ` : ""}Tax is required and the provider did not compute it for this order${taxReason ? ` (${taxReason})` : ""}.`
|
|
495
|
+
: "Tax is required and the provider did not compute it for this order."
|
|
496
|
+
: taxEngineLabel || taxReason
|
|
497
|
+
? `${taxEngineLabel ?? "Excise tax"} $${d.totals.taxesAndFees.toFixed(2)} — tax evidence is ${tax.state}${taxReason ? ` (${taxReason})` : ""}.`
|
|
498
|
+
: `Tax evidence is ${tax.state}.`;
|
|
481
499
|
return [
|
|
482
500
|
{
|
|
483
501
|
key: "payment_capture",
|
|
@@ -494,9 +512,7 @@ function deriveReadinessChecks(d: CheckoutOrderDetail, scope: CommerceScope): Or
|
|
|
494
512
|
key: "tax_and_fees",
|
|
495
513
|
label: "Tax and fees",
|
|
496
514
|
value: tax.state,
|
|
497
|
-
detail:
|
|
498
|
-
? "Tax is required and the provider did not compute it for this order."
|
|
499
|
-
: `Tax evidence is ${tax.state}.`,
|
|
515
|
+
detail: taxDetail,
|
|
500
516
|
tone: tax.state === "fresh" || tax.state === "not-required" ? "blue" : "amber",
|
|
501
517
|
action: "View total",
|
|
502
518
|
blocking: !["fresh", "not-required", "not-computed"].includes(tax.state),
|
|
@@ -3,8 +3,8 @@ import type { APIContext } from "astro";
|
|
|
3
3
|
import { createLocalJWKSet, decodeProtectedHeader, jwtVerify, type JSONWebKeySet } from "jose";
|
|
4
4
|
import {
|
|
5
5
|
commerceTenantId, isRegulated, isInternalTestTenant, totalsMatch, shippingMinorFor, isContentVersionId, catalogPinDigestFinding, cartLineKey,
|
|
6
|
-
type CallerToken, type CatalogProduct, type CatalogVariant, type CommerceEvidence, type CommerceEvidenceProvenance,
|
|
7
|
-
type CommerceProviderCartSnapshot, type FinalCartBinding, type TenantConfig,
|
|
6
|
+
EXCISE_REASONS, type CallerToken, type CatalogProduct, type CatalogVariant, type CommerceEvidence, type CommerceEvidenceProvenance,
|
|
7
|
+
type CommerceProviderCartSnapshot, type ExciseCarrier, type FinalCartBinding, type TenantConfig,
|
|
8
8
|
} from "@tot/public-runtime";
|
|
9
9
|
import { skuFromToken } from "@tot/public-runtime/sku";
|
|
10
10
|
import { fromD1 } from "@/lib/catalog/d1/catalog.js";
|
|
@@ -16,8 +16,10 @@ import { admissionMatches, readCommerceAdmission, admissionSnapshotStatement } f
|
|
|
16
16
|
import { evaluatePreflight } from "../compliance/preflight.js";
|
|
17
17
|
import {
|
|
18
18
|
admitSharedStoreTenant, testStoreEvidencePolicy, SHARED_STORE_POLICY_REVISION, SHARED_STORE_POLICY_SOURCE,
|
|
19
|
-
SHARED_STORE_VERIFICATION_SOURCE, SHARED_STORE_SANDBOX_VERIFICATION_SOURCE, SANDBOX_CLEARED_REF,
|
|
19
|
+
SHARED_STORE_VERIFICATION_SOURCE, SHARED_STORE_SANDBOX_VERIFICATION_SOURCE, SANDBOX_CLEARED_REF,
|
|
20
|
+
checkoutStoreHasExciseProducer, exciseLinesDigest, resolveTaxEvidence, type SharedStoreEvidencePolicy,
|
|
20
21
|
} from "@/lib/checkout/commerce/sharedStoreAdmission.js";
|
|
22
|
+
import { resolveTenantCommerce } from "@/lib/checkout/shared/checkoutCommerce";
|
|
21
23
|
import { isSandboxVerificationProvider } from "@/lib/compliance/enforcement.js";
|
|
22
24
|
import { readCheckoutRequirements } from "@/lib/checkout/commerce/checkoutRequirements.js";
|
|
23
25
|
import { DeclaredTenantConfigUnreadError, withDeclaredTenantConfig } from "@/config/declaredTenantConfig";
|
|
@@ -62,12 +64,31 @@ function publicJwks(value: string | undefined): JSONWebKeySet | null {
|
|
|
62
64
|
async function digest(value: string): Promise<string> {
|
|
63
65
|
return [...new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(value)))].map(b => b.toString(16).padStart(2, "0")).join("");
|
|
64
66
|
}
|
|
65
|
-
|
|
67
|
+
/**
|
|
68
|
+
* The excise field tot-foxycart signs into every shared-store final cart: the excise producer's own
|
|
69
|
+
* verified result for this cart. `amountMinor` only when computed, `reason` only when not computed,
|
|
70
|
+
* from a closed vocabulary; no other key. Optional: a snapshot without it is read as before.
|
|
71
|
+
*/
|
|
72
|
+
export { EXCISE_REASONS, type ExciseCarrier, exciseLinesDigest, resolveTaxEvidence, checkoutStoreHasExciseProducer };
|
|
73
|
+
type FinalCartWire = CommerceProviderCartSnapshot & { excise?: ExciseCarrier };
|
|
74
|
+
export function readExcise(value: unknown): ExciseCarrier | null {
|
|
75
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
|
|
76
|
+
const e = value as Record<string, unknown>;
|
|
77
|
+
const common = ["status", "linesDigest", "destinationDigest", "engineTier"];
|
|
78
|
+
const keys = e.status === "computed" ? [...common, "amountMinor"] : e.status === "not-computed" ? [...common, "reason"] : null;
|
|
79
|
+
if (!keys || Object.keys(e).length !== keys.length || !keys.every(k => Object.hasOwn(e, k))) return null;
|
|
80
|
+
if (typeof e.linesDigest !== "string" || !HEX.test(e.linesDigest) || typeof e.destinationDigest !== "string" || !HEX.test(e.destinationDigest) ||
|
|
81
|
+
(e.engineTier !== "test" && e.engineTier !== "production")) return null;
|
|
82
|
+
if (e.status === "computed" ? !Number.isSafeInteger(e.amountMinor) || Number(e.amountMinor) < 0 : !(EXCISE_REASONS as readonly unknown[]).includes(e.reason)) return null;
|
|
83
|
+
return e as unknown as ExciseCarrier;
|
|
84
|
+
}
|
|
85
|
+
function readSnapshot(value: unknown): FinalCartWire | null {
|
|
66
86
|
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
|
|
67
87
|
const v = value as Record<string, unknown>;
|
|
68
88
|
const allowed = ["provider", "providerCartId", "providerCartDigest", "tenantId", "stage", "currency", "lines", "totals", "destinationDigest", "destination"];
|
|
69
|
-
const optional = ["expectedAuthorizationId", "verificationRef", "contentVersionId"];
|
|
89
|
+
const optional = ["expectedAuthorizationId", "verificationRef", "contentVersionId", "excise"];
|
|
70
90
|
if (Object.keys(v).some(k => !allowed.includes(k) && !optional.includes(k)) || allowed.some(k => !(k in v))) return null;
|
|
91
|
+
if ("excise" in v && !readExcise(v.excise)) return null;
|
|
71
92
|
if ("contentVersionId" in v && (typeof v.contentVersionId !== "string" || !isContentVersionId(v.contentVersionId))) return null;
|
|
72
93
|
if ("expectedAuthorizationId" in v && (typeof v.expectedAuthorizationId !== "string" || !/^[a-z0-9][a-z0-9-]{0,80}$/.test(v.expectedAuthorizationId))) return null;
|
|
73
94
|
if ("verificationRef" in v && (typeof v.verificationRef !== "string" || !VERIFICATION_REF.test(v.verificationRef))) return null;
|
|
@@ -82,7 +103,7 @@ function readSnapshot(value: unknown): CommerceProviderCartSnapshot | null {
|
|
|
82
103
|
!["subtotalMinor", "shippingMinor", "taxMinor", "totalMinor"].every(k => Number.isSafeInteger((v.totals as Record<string, unknown>)[k]) && Number((v.totals as Record<string, unknown>)[k]) >= 0)) return null;
|
|
83
104
|
const d = v.destination as Record<string, unknown> | undefined;
|
|
84
105
|
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;
|
|
85
|
-
const snapshot = v as unknown as
|
|
106
|
+
const snapshot = v as unknown as FinalCartWire;
|
|
86
107
|
if (new Set(snapshot.lines.map(line => line.sku)).size !== snapshot.lines.length) return null;
|
|
87
108
|
if (!totalsMatch(snapshot.totals) || snapshot.lines.reduce((sum, line) => sum + line.quantity * line.unitMinor, 0) !== snapshot.totals.subtotalMinor) return null;
|
|
88
109
|
return snapshot;
|
|
@@ -201,7 +222,7 @@ async function authorize(context: APIContext): Promise<Response> {
|
|
|
201
222
|
if (Number(context.request.headers.get("content-length") ?? 0) > 65536) return deny("malformed-request");
|
|
202
223
|
const raw = await context.request.text();
|
|
203
224
|
if (raw.length > 65536) return deny("malformed-request");
|
|
204
|
-
let wire:
|
|
225
|
+
let wire: FinalCartWire | null;
|
|
205
226
|
try { wire = readSnapshot(JSON.parse(raw)); } catch { wire = null; }
|
|
206
227
|
if (!wire) return deny("malformed-request");
|
|
207
228
|
const snapshot = keyedLines(wire);
|
|
@@ -342,11 +363,18 @@ async function authorize(context: APIContext): Promise<Response> {
|
|
|
342
363
|
destinationDigest: snapshot.destinationDigest, verificationExpiresAt: expiresAt, taxExpiresAt: expiresAt };
|
|
343
364
|
const seamView = await seam(authorityContext, snapshot, selected, policy);
|
|
344
365
|
if (policy.tax === "required") {
|
|
345
|
-
const
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
:
|
|
366
|
+
const hasProducer = checkoutStoreHasExciseProducer(await resolveTenantCommerce(tenant));
|
|
367
|
+
const taxResolution = await resolveTaxEvidence({
|
|
368
|
+
wireLines: wire.lines,
|
|
369
|
+
destinationDigest: snapshot.destinationDigest,
|
|
370
|
+
totals: snapshot.totals,
|
|
371
|
+
excise: snapshot.excise,
|
|
372
|
+
hasProducer,
|
|
373
|
+
policyRevision: SHARED_STORE_POLICY_REVISION,
|
|
374
|
+
expiresAt,
|
|
375
|
+
});
|
|
376
|
+
evidence.tax = taxResolution.evidenceState;
|
|
377
|
+
provenance.tax = taxResolution.provenance;
|
|
350
378
|
}
|
|
351
379
|
if (policy.verification === "required" && seamView.verified) {
|
|
352
380
|
evidence.verification = "fresh";
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tokenoftrust/storefront-runner",
|
|
3
|
-
"version": "6.
|
|
3
|
+
"version": "6.10.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",
|
|
@@ -258,6 +258,56 @@ export const SCRAPPY_ORDERS_FIXTURE_DOMAIN = "scrappy-orders-v1";
|
|
|
258
258
|
export const FINAL_CART_DOMAIN = "scrappy-final-cart-v1";
|
|
259
259
|
export const CALLER_TOKEN_MAX_LIFETIME_MS = 15 * 60 * 1000;
|
|
260
260
|
|
|
261
|
+
export const EXCISE_REASONS = [
|
|
262
|
+
"engine-error",
|
|
263
|
+
"engine-refused",
|
|
264
|
+
"summary-missing",
|
|
265
|
+
"sku-unregistered",
|
|
266
|
+
"postal-code-missing",
|
|
267
|
+
"tenant-mismatch",
|
|
268
|
+
"no-producer-result",
|
|
269
|
+
"result-unauthenticated",
|
|
270
|
+
"result-lines-changed",
|
|
271
|
+
"result-destination-changed",
|
|
272
|
+
] as const;
|
|
273
|
+
export type ExciseReason = (typeof EXCISE_REASONS)[number];
|
|
274
|
+
|
|
275
|
+
export type ExciseEngineTier = "test" | "production";
|
|
276
|
+
|
|
277
|
+
export type ExciseCarrier =
|
|
278
|
+
| {
|
|
279
|
+
status: "computed";
|
|
280
|
+
amountMinor: number;
|
|
281
|
+
linesDigest: string;
|
|
282
|
+
destinationDigest: string;
|
|
283
|
+
engineTier: ExciseEngineTier;
|
|
284
|
+
}
|
|
285
|
+
| {
|
|
286
|
+
status: "not-computed";
|
|
287
|
+
reason: ExciseReason;
|
|
288
|
+
linesDigest: string;
|
|
289
|
+
destinationDigest: string;
|
|
290
|
+
engineTier: ExciseEngineTier;
|
|
291
|
+
};
|
|
292
|
+
|
|
293
|
+
export const EXCISE_STOREFRONT_UNAVAILABLE_REASONS = [
|
|
294
|
+
"carrier-absent",
|
|
295
|
+
"carrier-lines-mismatch",
|
|
296
|
+
"carrier-destination-mismatch",
|
|
297
|
+
"carrier-amount-unreconciled",
|
|
298
|
+
"producer-undeclared",
|
|
299
|
+
] as const;
|
|
300
|
+
export type ExciseStorefrontUnavailableReason = (typeof EXCISE_STOREFRONT_UNAVAILABLE_REASONS)[number];
|
|
301
|
+
export type ExciseUnavailableReason = ExciseReason | ExciseStorefrontUnavailableReason;
|
|
302
|
+
export type ExciseEvidenceReason = "computed" | `unavailable:${ExciseUnavailableReason}`;
|
|
303
|
+
|
|
304
|
+
export const EXCISE_TAX_LABEL = "Excise tax";
|
|
305
|
+
export function exciseTaxEngineLabel(engineTier?: ExciseEngineTier | string | null): string {
|
|
306
|
+
if (engineTier === "test") return "Excise tax (test engine)";
|
|
307
|
+
if (engineTier === "production") return "Excise tax (production engine)";
|
|
308
|
+
return EXCISE_TAX_LABEL;
|
|
309
|
+
}
|
|
310
|
+
|
|
261
311
|
export interface CommerceEvidence {
|
|
262
312
|
verification: EvidenceState;
|
|
263
313
|
tax: EvidenceState;
|
|
@@ -372,6 +422,11 @@ export interface CommerceProviderCartSnapshot {
|
|
|
372
422
|
* final-cart authority re-reads its status from the verification provider.
|
|
373
423
|
*/
|
|
374
424
|
verificationRef?: string;
|
|
425
|
+
/**
|
|
426
|
+
* The excise producer's server-side result for this cart, signed into the final-cart snapshot.
|
|
427
|
+
* Optional: a snapshot without it yields not-computed tax evidence with reason `unavailable:carrier-absent`.
|
|
428
|
+
*/
|
|
429
|
+
excise?: ExciseCarrier;
|
|
375
430
|
}
|
|
376
431
|
|
|
377
432
|
const CONTENT_VERSION_ID = /^[A-Za-z0-9._-]{1,128}$/;
|
|
@@ -444,6 +499,9 @@ export interface CommerceAuthoritySource {
|
|
|
444
499
|
source: string;
|
|
445
500
|
policyRevision: string;
|
|
446
501
|
expiresAt: string;
|
|
502
|
+
engineTier?: ExciseEngineTier;
|
|
503
|
+
reason?: string;
|
|
504
|
+
amountMinor?: number;
|
|
447
505
|
}
|
|
448
506
|
export type CommerceEvidenceProvenance = Record<keyof CommerceEvidence, CommerceAuthoritySource>;
|
|
449
507
|
|
|
@@ -79,6 +79,8 @@ export interface ManagedCheckoutConfig {
|
|
|
79
79
|
* checkout page is a separate origin, themed through checkout settings.
|
|
80
80
|
*/
|
|
81
81
|
cartDrawerCss?: string;
|
|
82
|
+
/** Whether the managed checkout store runs an excise tax producer. */
|
|
83
|
+
exciseProducer?: boolean;
|
|
82
84
|
}
|
|
83
85
|
|
|
84
86
|
/** Runtime tenant records must name a supported mode before they can build or admit a cart. */
|