@tokenoftrust/storefront-runner 6.9.0 → 6.9.2

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.
@@ -16,7 +16,7 @@
16
16
  * idempotency key, `actorId` the authenticated install.
17
17
  */
18
18
  import { isStoredSku, parseSku, skuKey } from "@tot/public-runtime/sku";
19
- import type { CommerceStage } from "@tot/public-runtime";
19
+ import type { CatalogProduct, CommerceStage } from "@tot/public-runtime";
20
20
  import type { Queryable, QueryStatement } from "../../catalog/d1/catalog.js";
21
21
  import {
22
22
  guardedCorrectionStatement,
@@ -282,6 +282,11 @@ async function classifyRefused(
282
282
  return inventoryRefusal("balance-out-of-range");
283
283
  }
284
284
 
285
+ /** Every stored sku of the catalog's variants: the skus an app may write for this tenant. */
286
+ export function catalogSkus(products: readonly CatalogProduct[]): string[] {
287
+ return products.flatMap((product) => product.variants.flatMap((variant) => (variant.sku ? [variant.sku] : [])));
288
+ }
289
+
285
290
  /** The stored catalog sku matching `sku` under the platform sku comparison, or null. */
286
291
  export function matchCatalogSku(catalogSkus: Iterable<string>, sku: string): string | null {
287
292
  const wanted = skuKey(sku);
@@ -62,12 +62,49 @@ function publicJwks(value: string | undefined): JSONWebKeySet | null {
62
62
  async function digest(value: string): Promise<string> {
63
63
  return [...new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(value)))].map(b => b.toString(16).padStart(2, "0")).join("");
64
64
  }
65
- function readSnapshot(value: unknown): CommerceProviderCartSnapshot | null {
65
+ /**
66
+ * The excise field tot-foxycart signs into every shared-store final cart: the excise producer's own
67
+ * verified result for this cart. `amountMinor` only when computed, `reason` only when not computed,
68
+ * from a closed vocabulary; no other key. Optional: a snapshot without it is read as before.
69
+ */
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" };
75
+ type FinalCartWire = CommerceProviderCartSnapshot & { excise?: ExciseCarrier };
76
+ export function readExcise(value: unknown): ExciseCarrier | null {
77
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
78
+ const e = value as Record<string, unknown>;
79
+ const common = ["status", "linesDigest", "destinationDigest", "engineTier"];
80
+ const keys = e.status === "computed" ? [...common, "amountMinor"] : e.status === "not-computed" ? [...common, "reason"] : null;
81
+ if (!keys || Object.keys(e).length !== keys.length || !keys.every(k => Object.hasOwn(e, k))) return null;
82
+ if (typeof e.linesDigest !== "string" || !HEX.test(e.linesDigest) || typeof e.destinationDigest !== "string" || !HEX.test(e.destinationDigest) ||
83
+ (e.engineTier !== "test" && e.engineTier !== "production")) return null;
84
+ if (e.status === "computed" ? !Number.isSafeInteger(e.amountMinor) || Number(e.amountMinor) < 0 : !(EXCISE_REASONS as readonly unknown[]).includes(e.reason)) return null;
85
+ return e as unknown as ExciseCarrier;
86
+ }
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
+ function readSnapshot(value: unknown): FinalCartWire | null {
66
102
  if (!value || typeof value !== "object" || Array.isArray(value)) return null;
67
103
  const v = value as Record<string, unknown>;
68
104
  const allowed = ["provider", "providerCartId", "providerCartDigest", "tenantId", "stage", "currency", "lines", "totals", "destinationDigest", "destination"];
69
- const optional = ["expectedAuthorizationId", "verificationRef", "contentVersionId"];
105
+ const optional = ["expectedAuthorizationId", "verificationRef", "contentVersionId", "excise"];
70
106
  if (Object.keys(v).some(k => !allowed.includes(k) && !optional.includes(k)) || allowed.some(k => !(k in v))) return null;
107
+ if ("excise" in v && !readExcise(v.excise)) return null;
71
108
  if ("contentVersionId" in v && (typeof v.contentVersionId !== "string" || !isContentVersionId(v.contentVersionId))) return null;
72
109
  if ("expectedAuthorizationId" in v && (typeof v.expectedAuthorizationId !== "string" || !/^[a-z0-9][a-z0-9-]{0,80}$/.test(v.expectedAuthorizationId))) return null;
73
110
  if ("verificationRef" in v && (typeof v.verificationRef !== "string" || !VERIFICATION_REF.test(v.verificationRef))) return null;
@@ -82,7 +119,7 @@ function readSnapshot(value: unknown): CommerceProviderCartSnapshot | null {
82
119
  !["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
120
  const d = v.destination as Record<string, unknown> | undefined;
84
121
  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 CommerceProviderCartSnapshot;
122
+ const snapshot = v as unknown as FinalCartWire;
86
123
  if (new Set(snapshot.lines.map(line => line.sku)).size !== snapshot.lines.length) return null;
87
124
  if (!totalsMatch(snapshot.totals) || snapshot.lines.reduce((sum, line) => sum + line.quantity * line.unitMinor, 0) !== snapshot.totals.subtotalMinor) return null;
88
125
  return snapshot;
@@ -201,9 +238,9 @@ async function authorize(context: APIContext): Promise<Response> {
201
238
  if (Number(context.request.headers.get("content-length") ?? 0) > 65536) return deny("malformed-request");
202
239
  const raw = await context.request.text();
203
240
  if (raw.length > 65536) return deny("malformed-request");
204
- let wire: CommerceProviderCartSnapshot | null;
241
+ let wire: FinalCartWire | null;
205
242
  try { wire = readSnapshot(JSON.parse(raw)); } catch { wire = null; }
206
- if (!wire) return deny("malformed-request");
243
+ if (!wire || !await exciseBindsSnapshot(wire)) return deny("malformed-request");
207
244
  const snapshot = keyedLines(wire);
208
245
  const jwks = publicJwks(await readEnv("COMMERCE_CALLER_JWKS"));
209
246
  const issuers = list(await readEnv("COMMERCE_CALLER_ISSUERS"));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tokenoftrust/storefront-runner",
3
- "version": "6.9.0",
3
+ "version": "6.9.2",
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",