@tokenoftrust/storefront-runner 6.9.2 → 6.11.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.
@@ -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 { ExciseTaxConfig } from "@tot/public-runtime";
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="Excise tax notice"
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)]">
@@ -578,8 +578,9 @@ const footerWidgets = await renderWidgetSlot(
578
578
  root-absolute links inside that prefix so navigation stays on the
579
579
  tenant. Host-routed requests have no base path and skip this entirely. */}
580
580
  <script>
581
- import { bindBasePathAnchors } from "@/lib/publication/shared/basePath";
582
- bindBasePathAnchors();
581
+ void import("@/lib/publication/shared/basePath")
582
+ .then(({ bindBasePathAnchors }) => bindBasePathAnchors())
583
+ .catch(() => console.warn("[storefront] bindBasePathAnchors failed to start"));
583
584
  </script>
584
585
 
585
586
  {/* Dev-loop theme hot-patch: tenant-hot-reload.mjs broadcasts a
@@ -603,8 +604,9 @@ const footerWidgets = await renderWidgetSlot(
603
604
  `[data-tot-widget-origin]` frames itself, so it doesn't need to know
604
605
  which slots rendered above. */}
605
606
  <script>
606
- import { mountWidgetPostMessageBridge } from "@tot/public-runtime";
607
- mountWidgetPostMessageBridge();
607
+ void import("@tot/public-runtime/widget-postmessage")
608
+ .then(({ mountWidgetPostMessageBridge }) => mountWidgetPostMessageBridge())
609
+ .catch(() => console.warn("[storefront] mountWidgetPostMessageBridge failed to start"));
608
610
  </script>
609
611
 
610
612
  {/* Scroll-reveal. Initial-viewport blocks stay visible (no .is-below).
@@ -647,8 +649,9 @@ const footerWidgets = await renderWidgetSlot(
647
649
  where PerformanceObserver is absent. This is the per-route-template
648
650
  signal the `core-web-vitals` monitor consumes. */}
649
651
  <script>
650
- import { startConsentGatedWebVitals } from "@/lib/observability/performance/webVitals";
651
- startConsentGatedWebVitals();
652
+ void import("@/lib/observability/performance/webVitals")
653
+ .then(({ startConsentGatedWebVitals }) => startConsentGatedWebVitals())
654
+ .catch(() => console.warn("[storefront] startConsentGatedWebVitals failed to start"));
652
655
  </script>
653
656
 
654
657
  {/* Protected-surface tamper sentinel (ext-policy-09, D-R7) — a DETECTIVE
@@ -659,8 +662,9 @@ const footerWidgets = await renderWidgetSlot(
659
662
  suspends the attributable integration. No-ops when no integration plan is
660
663
  present. */}
661
664
  <script>
662
- import { bootTamperSentinel } from "@/lib/compliance/tamper-sentinel-boot";
663
- bootTamperSentinel();
665
+ void import("@/lib/compliance/tamper-sentinel-boot")
666
+ .then(({ bootTamperSentinel }) => bootTamperSentinel())
667
+ .catch(() => console.warn("[storefront] bootTamperSentinel failed to start"));
664
668
  </script>
665
669
 
666
670
  {/* Declarative interaction tracking (dt-contract-v1) — ONE delegated click
@@ -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. No producer exists yet, so the save refuses `true`. */
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
- /** Validate a save from /admin. Tax evidence cannot be required until it has a producer. */
69
- export function validateCheckoutRequirementsInput(raw: unknown): CheckoutRequirementsInput {
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
- if (requirements.tax) errors.push("Tax evidence can't be required yet: it needs excise setup first.");
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 { commerceTenantId, isRegulated, SHARED_DEMO_CHECKOUT, type CustomizationEnv, type TenantConfig } from "@tot/public-runtime";
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
@@ -16,14 +16,13 @@ import {
16
16
  PROTECTED_SURFACE_ATTR,
17
17
  type TamperSink,
18
18
  } from "./tamper-sentinel";
19
+ import type { ProtectedSurface } from "@tot/public-runtime/compliance-obligations";
19
20
  import type {
20
- ProtectedSurface,
21
21
  TamperAttribution,
22
22
  TamperEvidenceBeacon,
23
- IntegrationEnvironment,
24
- IntegrationSiteSurface,
25
- } from "@tot/public-runtime";
26
- import { INTEGRATION_PLAN_GLOBAL } from "@tot/public-runtime";
23
+ } from "@tot/public-runtime/integration/tamper-evidence";
24
+ import type { IntegrationEnvironment, IntegrationSiteSurface } from "@tot/public-runtime/integration/environment";
25
+ import { INTEGRATION_PLAN_GLOBAL } from "@tot/public-runtime/integration/render-phases";
27
26
  import { withClientApiBase } from "@/lib/publication/shared/basePath";
28
27
 
29
28
  /** Where the browser posts a tamper beacon; the server receiver records + suspends. */
@@ -26,14 +26,12 @@
26
26
  import {
27
27
  buildTamperEvidenceBeacon,
28
28
  attributeSoleSuspect,
29
- PROTECTED_SURFACES,
30
- type ProtectedSurface,
31
29
  type TamperKind,
32
30
  type TamperAttribution,
33
31
  type TamperEvidenceBeacon,
34
- type IntegrationEnvironment,
35
- type IntegrationSiteSurface,
36
- } from "@tot/public-runtime";
32
+ } from "@tot/public-runtime/integration/tamper-evidence";
33
+ import { PROTECTED_SURFACES, type ProtectedSurface } from "@tot/public-runtime/compliance-obligations";
34
+ import type { IntegrationEnvironment, IntegrationSiteSurface } from "@tot/public-runtime/integration/environment";
37
35
 
38
36
  /** The DOM marker a protected surface stamps; its value is a `ProtectedSurface`. */
39
37
  export const PROTECTED_SURFACE_ATTR = "data-tot-protected-surface";
@@ -28,12 +28,12 @@
28
28
  * budget gate and regression alert (`rumAlert.ts`) reason over.
29
29
  */
30
30
  import { classifyPath, PERF_BUDGETS, type PerfBudgetManifest, type RouteClass } from "./perfBudgets.js";
31
+ import { INTEGRATION_CONSENT_GLOBAL } from "@tot/public-runtime/integration/render-phases";
31
32
  import {
32
- INTEGRATION_CONSENT_GLOBAL,
33
33
  VIEWER_ANALYTICS_CONSENT_CHANGE_EVENT,
34
34
  isPurposeEligible,
35
35
  parseConsentSnapshot,
36
- } from "@tot/public-runtime";
36
+ } from "@tot/public-runtime/integration/consent-broker";
37
37
  import { withClientApiBase } from "@/lib/publication/shared/basePath";
38
38
 
39
39
  /** The three field metrics we collect. INP is field-only (no lab equivalent). */
@@ -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: tax.state === "not-computed"
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, type SharedStoreEvidencePolicy,
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";
@@ -67,11 +69,7 @@ async function digest(value: string): Promise<string> {
67
69
  * verified result for this cart. `amountMinor` only when computed, `reason` only when not computed,
68
70
  * from a closed vocabulary; no other key. Optional: a snapshot without it is read as before.
69
71
  */
70
- export const EXCISE_REASONS = ["engine-error", "engine-refused", "summary-missing", "sku-unregistered", "postal-code-missing",
71
- "tenant-mismatch", "no-producer-result", "result-unauthenticated", "result-lines-changed", "result-destination-changed"] as const;
72
- export type ExciseCarrier =
73
- | { status: "computed"; amountMinor: number; linesDigest: string; destinationDigest: string; engineTier: "test" | "production" }
74
- | { status: "not-computed"; reason: (typeof EXCISE_REASONS)[number]; linesDigest: string; destinationDigest: string; engineTier: "test" | "production" };
72
+ export { EXCISE_REASONS, type ExciseCarrier, exciseLinesDigest, resolveTaxEvidence, checkoutStoreHasExciseProducer };
75
73
  type FinalCartWire = CommerceProviderCartSnapshot & { excise?: ExciseCarrier };
76
74
  export function readExcise(value: unknown): ExciseCarrier | null {
77
75
  if (!value || typeof value !== "object" || Array.isArray(value)) return null;
@@ -84,20 +82,6 @@ export function readExcise(value: unknown): ExciseCarrier | null {
84
82
  if (e.status === "computed" ? !Number.isSafeInteger(e.amountMinor) || Number(e.amountMinor) < 0 : !(EXCISE_REASONS as readonly unknown[]).includes(e.reason)) return null;
85
83
  return e as unknown as ExciseCarrier;
86
84
  }
87
- /**
88
- * Lowercase hex SHA-256 of the JSON (no whitespace) of the [sku, quantity, unitMinor] triples, sorted
89
- * by sku in code-unit order, with each sku exactly as the snapshot's lines carry it.
90
- */
91
- export async function exciseLinesDigest(lines: readonly { sku: string; quantity: number; unitMinor: number }[]): Promise<string> {
92
- const triples = lines.map(line => [line.sku, line.quantity, line.unitMinor] as const)
93
- .sort((a, b) => a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : a[1] - b[1] || a[2] - b[2]);
94
- return digest(JSON.stringify(triples));
95
- }
96
- /** A computed excise must have been computed over exactly this snapshot's lines and destination. */
97
- async function exciseBindsSnapshot(wire: FinalCartWire): Promise<boolean> {
98
- if (wire.excise?.status !== "computed") return true;
99
- return wire.excise.destinationDigest === wire.destinationDigest && wire.excise.linesDigest === await exciseLinesDigest(wire.lines);
100
- }
101
85
  function readSnapshot(value: unknown): FinalCartWire | null {
102
86
  if (!value || typeof value !== "object" || Array.isArray(value)) return null;
103
87
  const v = value as Record<string, unknown>;
@@ -240,7 +224,7 @@ async function authorize(context: APIContext): Promise<Response> {
240
224
  if (raw.length > 65536) return deny("malformed-request");
241
225
  let wire: FinalCartWire | null;
242
226
  try { wire = readSnapshot(JSON.parse(raw)); } catch { wire = null; }
243
- if (!wire || !await exciseBindsSnapshot(wire)) return deny("malformed-request");
227
+ if (!wire) return deny("malformed-request");
244
228
  const snapshot = keyedLines(wire);
245
229
  const jwks = publicJwks(await readEnv("COMMERCE_CALLER_JWKS"));
246
230
  const issuers = list(await readEnv("COMMERCE_CALLER_ISSUERS"));
@@ -379,11 +363,18 @@ async function authorize(context: APIContext): Promise<Response> {
379
363
  destinationDigest: snapshot.destinationDigest, verificationExpiresAt: expiresAt, taxExpiresAt: expiresAt };
380
364
  const seamView = await seam(authorityContext, snapshot, selected, policy);
381
365
  if (policy.tax === "required") {
382
- const computed = snapshot.totals.taxMinor > 0;
383
- evidence.tax = computed ? "fresh" : "not-computed";
384
- provenance.tax = computed
385
- ? { requirement: "required", state: "satisfied", source: "provider-computed-tax", policyRevision: SHARED_STORE_POLICY_REVISION, expiresAt }
386
- : { requirement: "required", state: "not-computed", source: "provider-computed-tax", policyRevision: SHARED_STORE_POLICY_REVISION, expiresAt };
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;
387
378
  }
388
379
  if (policy.verification === "required" && seamView.verified) {
389
380
  evidence.verification = "fresh";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tokenoftrust/storefront-runner",
3
- "version": "6.9.2",
3
+ "version": "6.11.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",
@@ -5,10 +5,17 @@
5
5
  "private": true,
6
6
  "license": "SEE LICENSE IN LICENSE",
7
7
  "type": "module",
8
+ "sideEffects": false,
8
9
  "main": "./src/index.ts",
9
10
  "types": "./src/index.ts",
10
11
  "exports": {
11
12
  ".": "./src/index.ts",
13
+ "./widget-postmessage": "./src/widget-postmessage.ts",
14
+ "./compliance-obligations": "./src/compliance-obligations.ts",
15
+ "./integration/consent-broker": "./src/integration/consent-broker.ts",
16
+ "./integration/environment": "./src/integration/environment.ts",
17
+ "./integration/render-phases": "./src/integration/render-phases.ts",
18
+ "./integration/tamper-evidence": "./src/integration/tamper-evidence.ts",
12
19
  "./blog-visibility": "./src/blog-visibility.mjs",
13
20
  "./sitemap-index": "./src/sitemap-index.mjs",
14
21
  "./preview-url": "./src/preview-url.mjs",
@@ -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. */