@tokenoftrust/storefront-runner 7.11.0 → 7.11.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.
@@ -114,6 +114,14 @@ export interface TotAccessClient {
114
114
  audience: string;
115
115
  ttlSeconds?: number;
116
116
  }): Promise<CatalogContributionMintResult>;
117
+ /**
118
+ * Mint a short-lived ES256 service read assertion bound to the configured
119
+ * Catalog read audience (member role, dpop_exempt: true, empty staff).
120
+ */
121
+ mintCatalogReadAssertion?(input: {
122
+ audience: string;
123
+ ttlSeconds?: number;
124
+ }): Promise<CatalogReadMintResult>;
117
125
  /**
118
126
  * STEP-UP COMPLETION (SMS), leg 1: ask tot CORE to send a one-time SMS code to
119
127
  * `identifier` (the identifier bound during a `step-up-required` challenge or a
@@ -150,6 +158,17 @@ export type FederatedVerifyResult =
150
158
 
151
159
  /** Result of {@link TotAccessClient.mintSignInToken}. The raw `token` is a single-use
152
160
  * secret — server-to-server only, NEVER logged. */
161
+ export type CatalogReadMintResult =
162
+ | {
163
+ ok: true;
164
+ id_token: string;
165
+ audience: string;
166
+ tenant: string;
167
+ ttlSeconds?: number;
168
+ expiresAt?: string;
169
+ }
170
+ | { ok: false; reason: "forbidden" | "unavailable" | "error" };
171
+
153
172
  export type CatalogContributionMintResult =
154
173
  | {
155
174
  ok: true;
@@ -406,6 +425,34 @@ export class HttpTotAccessClient implements TotAccessClient {
406
425
  return normalizeCatalogContributionMint(body, res.status, input.tenant, input.audience);
407
426
  }
408
427
 
428
+ async mintCatalogReadAssertion(input: {
429
+ audience: string;
430
+ ttlSeconds?: number;
431
+ }): Promise<CatalogReadMintResult> {
432
+ let res: HttpResponseLike;
433
+ try {
434
+ res = await this.transport.post(
435
+ `${this.baseUrl}/api/internal/access-code/catalog-read`,
436
+ {},
437
+ {
438
+ audience: input.audience,
439
+ ...(input.ttlSeconds != null ? { ttlSeconds: input.ttlSeconds } : {}),
440
+ ...this.credentialFields(),
441
+ },
442
+ );
443
+ } catch {
444
+ return { ok: false, reason: "error" };
445
+ }
446
+ if (res.status >= 300 && res.status < 400) return { ok: false, reason: "error" };
447
+ let body: unknown;
448
+ try {
449
+ body = await res.json();
450
+ } catch {
451
+ return { ok: false, reason: "error" };
452
+ }
453
+ return normalizeCatalogReadMint(body, res.status, input.audience);
454
+ }
455
+
409
456
  async sendSmsChallenge(identifier: string): Promise<{ ok: true }> {
410
457
  // Neutral by contract, mirroring sendFederatedCode: a transport error still
411
458
  // resolves { ok: true } so the caller never learns eligibility. Best-effort
@@ -542,6 +589,40 @@ export function normalizeCatalogContributionMint(
542
589
  return { ok: false, reason: "error" };
543
590
  }
544
591
 
592
+ /** Parse tot20's `/catalog-read` response into a typed result (fail closed). */
593
+ export function normalizeCatalogReadMint(
594
+ body: unknown,
595
+ status: number,
596
+ expectedAudience: string,
597
+ ): CatalogReadMintResult {
598
+ const raw = (body ?? {}) as Record<string, unknown>;
599
+ const b = (raw.content && typeof raw.content === "object" ? raw.content : raw) as Record<string, unknown>;
600
+ if (
601
+ status >= 200 &&
602
+ status < 300 &&
603
+ b.ok === true &&
604
+ typeof b.id_token === "string" &&
605
+ b.id_token &&
606
+ typeof b.audience === "string" &&
607
+ b.audience === expectedAudience &&
608
+ typeof b.tenant === "string" &&
609
+ b.tenant.trim().length > 0
610
+ ) {
611
+ const result: CatalogReadMintResult = {
612
+ ok: true,
613
+ id_token: b.id_token,
614
+ audience: b.audience,
615
+ tenant: b.tenant.trim().toLowerCase(),
616
+ };
617
+ if (typeof b.ttlSeconds === "number") result.ttlSeconds = b.ttlSeconds;
618
+ if (typeof b.expiresAt === "string") result.expiresAt = b.expiresAt;
619
+ return result;
620
+ }
621
+ if (status === 403) return { ok: false, reason: "forbidden" };
622
+ if (status === 503) return { ok: false, reason: "unavailable" };
623
+ return { ok: false, reason: "error" };
624
+ }
625
+
545
626
  /** Parse tot20's SMS step-up-completion verify response (fail closed). */
546
627
  export function normalizeSmsVerify(body: unknown): SmsVerifyResult {
547
628
  // Same envelope-unwrap convention as normalizeVerify/normalizeFederatedVerify.
@@ -761,6 +842,21 @@ export class MockTotAccessClient implements TotAccessClient {
761
842
  };
762
843
  }
763
844
 
845
+ async mintCatalogReadAssertion(input: {
846
+ audience: string;
847
+ ttlSeconds?: number;
848
+ }): Promise<CatalogReadMintResult> {
849
+ const ttlSeconds = input.ttlSeconds ?? 300;
850
+ return {
851
+ ok: true,
852
+ id_token: `mock-read|${input.audience}|tokenoftrust.com`,
853
+ audience: input.audience,
854
+ tenant: "tokenoftrust.com",
855
+ ttlSeconds,
856
+ expiresAt: new Date(Date.now() + ttlSeconds * 1000).toISOString(),
857
+ };
858
+ }
859
+
764
860
  async sendSmsChallenge(identifier: string): Promise<{ ok: true }> {
765
861
  this.smsSent.push(identifier);
766
862
  return { ok: true }; // neutral regardless of eligibility
@@ -34,21 +34,23 @@ export interface ShopperCheckoutWire {
34
34
  proof: string;
35
35
  providerCartSelectorDigest: string;
36
36
  buyerConfirmation: string;
37
- licensedDestinationDigest?: string;
38
37
  }
39
38
 
40
39
  export function readShopperCheckoutWire(value: unknown): ShopperCheckoutWire | null {
41
40
  if (!value || typeof value !== "object" || Array.isArray(value)) return null;
42
41
  const wire = value as Record<string, unknown>;
43
- if (Object.keys(wire).some(key => !["version", "proof", "providerCartSelectorDigest", "buyerConfirmation", "licensedDestinationDigest"].includes(key)) ||
42
+ if (Object.keys(wire).some(key => !["version", "proof", "providerCartSelectorDigest", "buyerConfirmation"].includes(key)) ||
44
43
  wire.version !== 2 || typeof wire.proof !== "string" || !PROOF.test(wire.proof) || !isShopperToken(wire.buyerConfirmation) ||
45
- typeof wire.providerCartSelectorDigest !== "string" || !HEX.test(wire.providerCartSelectorDigest) ||
46
- ("licensedDestinationDigest" in wire && (typeof wire.licensedDestinationDigest !== "string" || !HEX.test(wire.licensedDestinationDigest)))) return null;
44
+ typeof wire.providerCartSelectorDigest !== "string" || !HEX.test(wire.providerCartSelectorDigest)) return null;
47
45
  return wire as unknown as ShopperCheckoutWire;
48
46
  }
49
47
 
48
+ /**
49
+ * The v2 context material the provider caller digests: its final slot is a fixed `null`. The
50
+ * shopper wire carries no destination; org KYB reads the ship-to from the provider-signed snapshot.
51
+ */
50
52
  export const shopperCheckoutContextDigest = (wire: ShopperCheckoutWire): Promise<string> => sha256Hex(JSON.stringify([
51
- "shopper-checkout-context/v2", wire.version, wire.proof, wire.providerCartSelectorDigest, wire.buyerConfirmation, wire.licensedDestinationDigest ?? null,
53
+ "shopper-checkout-context/v2", wire.version, wire.proof, wire.providerCartSelectorDigest, wire.buyerConfirmation, null,
52
54
  ]));
53
55
 
54
56
  function signedMaterial(shopper: ScopedShopper, nonce: string, expiresAt: number): string {
@@ -6,7 +6,7 @@ export async function hasShopperOrgKyb(_db: Queryable, _shopper: ScopedShopper,
6
6
  }
7
7
 
8
8
  export async function shopperOrgKyb(
9
- _db: Queryable, _shopper: ScopedShopper, _destinationDigest: string | undefined, _totalMinor: number, _now?: Date,
9
+ _db: Queryable, _shopper: ScopedShopper, _shipTo: unknown, _totalMinor: number, _now?: Date,
10
10
  ): Promise<{ expiresAt: string; updatedAt: number } | null> {
11
11
  return null;
12
12
  }
@@ -82,7 +82,31 @@ async function digest(value: string): Promise<string> {
82
82
  * from a closed vocabulary; no other key. Optional: a snapshot without it is read as before.
83
83
  */
84
84
  export { EXCISE_REASONS, type ExciseCarrier, exciseLinesDigest, exciseReconcilesWithTotals, exciseRequiredForTenant, resolveTaxEvidence, checkoutStoreHasExciseProducer };
85
- type FinalCartWire = CommerceProviderCartSnapshot & { excise?: ExciseCarrier; shopperCheckout?: ShopperCheckoutWire };
85
+ /**
86
+ * `shipTo` is the provider's full ship-to address for this cart, signed into the snapshot by the
87
+ * caller. It agrees with `destination`, is used only to derive the org KYB licensed-destination
88
+ * digest, and is never persisted.
89
+ */
90
+ type FinalCartWire = CommerceProviderCartSnapshot & { excise?: ExciseCarrier; shopperCheckout?: ShopperCheckoutWire; shipTo?: ShipTo };
91
+ interface ShipTo { line1: string; line2: string | null; city: string; region: string; postalCode: string; country: string }
92
+ const SHIP_TO_FIELDS = { line1: [200, true], line2: [200, false], city: [100, true], region: [60, false], postalCode: [20, false], country: [2, true] } as const;
93
+ /** The provider ship-to: the closed address keys, each bounded, control-free text; null when anything else. */
94
+ function readShipTo(value: unknown): ShipTo | null {
95
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
96
+ const record = value as Record<string, unknown>;
97
+ if (Object.keys(record).some(key => !Object.hasOwn(SHIP_TO_FIELDS, key))) return null;
98
+ const out: Record<string, string | null> = {};
99
+ for (const [key, [max, required]] of Object.entries(SHIP_TO_FIELDS)) {
100
+ const raw = record[key];
101
+ if (raw === undefined || raw === null || raw === "") { if (required) return null; out[key] = null; continue; }
102
+ if (typeof raw !== "string" || raw.length > max || /[\p{C}]/u.test(raw)) return null;
103
+ const trimmed = raw.trim();
104
+ if (!trimmed && required) return null;
105
+ out[key] = trimmed || null;
106
+ }
107
+ if (!/^[A-Za-z]{2}$/.test(out.country!)) return null;
108
+ return { line1: out.line1!, line2: out.line2 ?? null, city: out.city!, region: out.region ?? "", postalCode: out.postalCode ?? "", country: out.country!.toUpperCase() };
109
+ }
86
110
  export function readExcise(value: unknown): ExciseCarrier | null {
87
111
  if (!value || typeof value !== "object" || Array.isArray(value)) return null;
88
112
  const e = value as Record<string, unknown>;
@@ -98,7 +122,7 @@ function readSnapshot(value: unknown): FinalCartWire | null {
98
122
  if (!value || typeof value !== "object" || Array.isArray(value)) return null;
99
123
  const v = value as Record<string, unknown>;
100
124
  const allowed = ["provider", "providerCartId", "providerCartDigest", "tenantId", "stage", "currency", "lines", "totals", "destinationDigest", "destination"];
101
- const optional = ["expectedAuthorizationId", "verificationRef", "contentVersionId", "excise", "shopperCheckout", "checkoutContextDigest"];
125
+ const optional = ["expectedAuthorizationId", "verificationRef", "contentVersionId", "excise", "shopperCheckout", "checkoutContextDigest", "shipTo"];
102
126
  if (Object.keys(v).some(k => !allowed.includes(k) && !optional.includes(k)) || allowed.some(k => !(k in v))) return null;
103
127
  if ("excise" in v && !readExcise(v.excise)) return null;
104
128
  if ("contentVersionId" in v && (typeof v.contentVersionId !== "string" || !isContentVersionId(v.contentVersionId))) return null;
@@ -122,6 +146,11 @@ function readSnapshot(value: unknown): FinalCartWire | null {
122
146
  Object.keys(t).some(k => !Number.isSafeInteger(t[k]) || Number(t[k]) < 0)) return null;
123
147
  const d = v.destination as Record<string, unknown> | undefined;
124
148
  if (!d || Object.keys(d).length !== 2 || typeof d.country !== "string" || !/^[A-Z]{2}$/.test(d.country) || typeof d.region !== "string" || !/^[A-Z0-9-]{1,8}$/.test(d.region)) return null;
149
+ if ("shipTo" in v) {
150
+ const shipTo = readShipTo(v.shipTo);
151
+ if (!shipTo || shipTo.country !== d.country || shipTo.region.toUpperCase() !== d.region) return null;
152
+ v.shipTo = shipTo;
153
+ }
125
154
  const snapshot = v as unknown as FinalCartWire;
126
155
  if (new Set(snapshot.lines.map(line => line.sku)).size !== snapshot.lines.length) return null;
127
156
  if (!totalsMatch(snapshot.totals) || !exciseReconcilesWithTotals(snapshot.totals, snapshot.excise) ||
@@ -258,7 +287,7 @@ async function authorize(context: APIContext): Promise<Response> {
258
287
  let wire: FinalCartWire | null;
259
288
  try { wire = readSnapshot(JSON.parse(raw)); } catch { wire = null; }
260
289
  if (!wire || !await exciseBindsSnapshot(wire)) return deny("malformed-request");
261
- const { shopperCheckout, ...safeWire } = wire;
290
+ const { shopperCheckout, shipTo, ...safeWire } = wire;
262
291
  const snapshot = keyedLines(safeWire);
263
292
  const jwks = publicJwks(await readEnv("COMMERCE_CALLER_JWKS"));
264
293
  const issuers = list(await readEnv("COMMERCE_CALLER_ISSUERS"));
@@ -395,7 +424,7 @@ async function authorize(context: APIContext): Promise<Response> {
395
424
  const evidence: CommerceEvidence = { verification: "absent", tax: "absent", risk: "absent", stock: stockTracked ? "fresh" : "not-required" };
396
425
  const orgKybRequired = resolveShopperAccessPolicy(tenant).b2bKybOrgVerification;
397
426
  const orgKyb = orgKybRequired && scopedProof ? await shopperOrgKyb(queryable, scopedProof.shopper,
398
- shopperCheckout?.licensedDestinationDigest, snapshot.totals.totalMinor, new Date(now)) : null;
427
+ shipTo, snapshot.totals.totalMinor, new Date(now)) : null;
399
428
  if (orgKybRequired && !orgKyb) return deny("shopper-org-kyb-review-required");
400
429
  if (existing && orgKyb && Date.parse(existing.expiresAt) > Date.parse(orgKyb.expiresAt)) return deny("admission-expired");
401
430
  const expiresAt = existing?.expiresAt ?? new Date(Math.min(Date.now() + CHECKOUT_ADMISSION_TTL_MS, stockExpiry,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tokenoftrust/storefront-runner",
3
- "version": "7.11.0",
3
+ "version": "7.11.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",