@tokenoftrust/storefront-runner 7.3.1 → 7.5.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.
Files changed (414) hide show
  1. package/agency-kit/tools/lib/catalog-model/files.mjs +11 -4
  2. package/agency-kit/tools/lib/catalog-model/model.mjs +5 -1
  3. package/agency-kit/tools/lib/redirect-shadows.mjs +261 -0
  4. package/apps/storefront/astro.config.mjs +8 -2
  5. package/apps/storefront/package.json +1 -2
  6. package/apps/storefront/src/components/catalog/storefront/ProductCard.astro +20 -6
  7. package/apps/storefront/src/components/catalog/storefront/islands/ImageGallery.tsx +17 -6
  8. package/apps/storefront/src/components/compliance/storefront/islands/CheckoutComplianceGate.tsx +1 -32
  9. package/apps/storefront/src/config/compliance/rulesets.ts +1 -1
  10. package/apps/storefront/src/layouts/Layout.astro +17 -0
  11. package/apps/storefront/src/lib/access/auth/agentRoles.ts +20 -0
  12. package/apps/storefront/src/lib/access/auth/agentSessionGate.ts +147 -0
  13. package/apps/storefront/src/lib/access/auth/brokerAssertion.ts +67 -1
  14. package/apps/storefront/src/lib/access/auth/contactReaderAuthority.ts +39 -0
  15. package/apps/storefront/src/lib/access/auth/loginGate.ts +15 -17
  16. package/apps/storefront/src/lib/access/auth/session.ts +79 -0
  17. package/apps/storefront/src/lib/access/dashboard/staffAdmission.ts +5 -0
  18. package/apps/storefront/src/lib/access/dashboard/tenantSelection.ts +2 -0
  19. package/apps/storefront/src/lib/access/shared/capability.ts +14 -6
  20. package/apps/storefront/src/lib/access/shared/generated/capabilityCatalog.generated.ts +161 -0
  21. package/apps/storefront/src/lib/activity/activityScope.ts +36 -0
  22. package/apps/storefront/src/lib/activity/recordActivity.ts +23 -1
  23. package/apps/storefront/src/lib/activity/serverFanOut.ts +31 -0
  24. package/apps/storefront/src/lib/activity/store.ts +9 -3
  25. package/apps/storefront/src/lib/checkout/commerce/cardCartForm.ts +2 -0
  26. package/apps/storefront/src/lib/checkout/commerce/cartSession.ts +109 -12
  27. package/apps/storefront/src/lib/checkout/commerce/checkoutHandoffRoute.ts +53 -25
  28. package/apps/storefront/src/lib/checkout/commerce/finalCartAuthorization.ts +48 -6
  29. package/apps/storefront/src/lib/checkout/proposal/cartProposal.ts +388 -0
  30. package/apps/storefront/src/lib/checkout/proposal/listMatcher.ts +149 -0
  31. package/apps/storefront/src/lib/checkout/proposal/proposalRoutes.ts +447 -0
  32. package/apps/storefront/src/lib/checkout/proposal/reviewHtml.ts +100 -0
  33. package/apps/storefront/src/lib/compliance/browser/checkoutVerificationFlow.ts +26 -2
  34. package/apps/storefront/src/lib/content/shared/redirects.ts +21 -4
  35. package/apps/storefront/src/lib/publication/shared/edgeCache.ts +5 -2
  36. package/apps/storefront/src/lib/publication/shared/previewAnnotations/renderDecorator.ts +15 -8
  37. package/apps/storefront/src/lib/publication/shared/runtimeEnv.ts +1 -1
  38. package/apps/storefront/src/middleware/controlPlane.ts +15 -1
  39. package/apps/storefront/src/middleware/index.ts +40 -1
  40. package/apps/storefront/src/middleware/renderChain.ts +46 -33
  41. package/apps/storefront/src/pages/api/cart-proposal/confirm.ts +12 -0
  42. package/apps/storefront/src/pages/api/cart-proposal/review.ts +26 -0
  43. package/apps/storefront/src/pages/api/commerce/final-cart-authorization.ts +29 -6
  44. package/apps/storefront/src/pages/api/compliance/preflight.ts +25 -1
  45. package/apps/storefront/src/pages/products/[handle].astro +2 -15
  46. package/apps/storefront/tsconfig.astro.json +11 -0
  47. package/package.json +1 -1
  48. package/packages/public-runtime/src/activity/README.md +12 -0
  49. package/packages/public-runtime/src/activity/catalog.ts +7 -0
  50. package/packages/public-runtime/src/activity/event.ts +19 -0
  51. package/packages/public-runtime/src/activity/redaction.ts +31 -2
  52. package/packages/public-runtime/src/catalog-files.ts +3 -2
  53. package/packages/public-runtime/src/checkout-orders.ts +18 -19
  54. package/packages/public-runtime/src/checkout.ts +70 -0
  55. package/packages/public-runtime/src/compliance/evaluate.ts +60 -1
  56. package/packages/public-runtime/src/compliance/index.ts +1 -1
  57. package/packages/public-runtime/src/compliance/pact-report.ts +184 -3
  58. package/packages/public-runtime/src/compliance/profile.ts +268 -20
  59. package/packages/public-runtime/src/compliance/ruleset.ts +42 -0
  60. package/packages/public-runtime/src/customization-runtime.ts +1 -1
  61. package/packages/public-runtime/src/product.ts +9 -1
  62. package/packages/public-runtime/src/publication-content-redirects.ts +16 -3
  63. package/packages/public-runtime/tests/fixtures/compliance-decisions.golden.json +252 -52
  64. package/pnpm-lock.runner.yaml +0 -15
  65. package/scripts/tenant/materialize-tenant-content.mjs +3 -0
  66. package/scripts/tenant/validate.mjs +128 -0
  67. package/apps/storefront/dev-plugins/dev-publish.mjs +0 -55
  68. package/apps/storefront/drizzle.config.apps.ts +0 -13
  69. package/apps/storefront/integrations/preview-annotations-client-bundle.mjs +0 -80
  70. package/apps/storefront/migrations-apps/0000_fast_millenium_guard.sql +0 -129
  71. package/apps/storefront/migrations-apps/0001_woozy_lyja.sql +0 -22
  72. package/apps/storefront/migrations-apps/0002_good_switch.sql +0 -26
  73. package/apps/storefront/migrations-apps/0003_mute_marauders.sql +0 -12
  74. package/apps/storefront/migrations-apps/0004_deep_morph.sql +0 -36
  75. package/apps/storefront/migrations-apps/0005_common_mystique.sql +0 -23
  76. package/apps/storefront/migrations-apps/0006_broad_microchip.sql +0 -16
  77. package/apps/storefront/migrations-apps/0007_brave_outlaw_kid.sql +0 -15
  78. package/apps/storefront/migrations-apps/0008_blue_dazzler.sql +0 -11
  79. package/apps/storefront/migrations-apps/0009_bored_shinobi_shaw.sql +0 -15
  80. package/apps/storefront/migrations-apps/0010_ws4_verified_provider_measurement.sql +0 -35
  81. package/apps/storefront/migrations-apps/0011_dt_tracking_tenant_databases.sql +0 -23
  82. package/apps/storefront/migrations-apps/0012_test_destinations.sql +0 -29
  83. package/apps/storefront/migrations-apps/0013_publication_space_editorial.sql +0 -64
  84. package/apps/storefront/migrations-apps/0014_retire_candidate_ledger.sql +0 -12
  85. package/apps/storefront/migrations-apps/0015_merchant_calculation_settings.sql +0 -31
  86. package/apps/storefront/migrations-apps/0016_scrappy_commerce_contract.sql +0 -166
  87. package/apps/storefront/migrations-apps/0017_commerce_durable_projection.sql +0 -28
  88. package/apps/storefront/migrations-apps/0018_commerce_provider_cart_identity.sql +0 -13
  89. package/apps/storefront/migrations-apps/0019_commerce_source_authority.sql +0 -23
  90. package/apps/storefront/migrations-apps/0020_contact_messages.sql +0 -18
  91. package/apps/storefront/migrations-apps/0021_contact_vault.sql +0 -166
  92. package/apps/storefront/migrations-apps/0022_contact_vault_fields.sql +0 -342
  93. package/apps/storefront/migrations-apps/0023_principal_grant_contacts.sql +0 -15
  94. package/apps/storefront/migrations-apps/0024_order_contact_erasure_state.sql +0 -22
  95. package/apps/storefront/migrations-apps/0025_shipment_audit_order_lookup.sql +0 -2
  96. package/apps/storefront/migrations-apps/0026_fulfillment_assignment.sql +0 -44
  97. package/apps/storefront/migrations-apps/0027_app_contact_authority.sql +0 -70
  98. package/apps/storefront/migrations-apps/0028_app_jwk_and_candidates.sql +0 -133
  99. package/apps/storefront/migrations-apps/0029_inventory_locations_wms.sql +0 -38
  100. package/apps/storefront/migrations-apps/0030_assignment_split_shipments.sql +0 -149
  101. package/apps/storefront/migrations-apps/meta/0000_snapshot.json +0 -843
  102. package/apps/storefront/migrations-apps/meta/0001_snapshot.json +0 -990
  103. package/apps/storefront/migrations-apps/meta/0002_snapshot.json +0 -1160
  104. package/apps/storefront/migrations-apps/meta/0003_snapshot.json +0 -1235
  105. package/apps/storefront/migrations-apps/meta/0004_snapshot.json +0 -1474
  106. package/apps/storefront/migrations-apps/meta/0005_snapshot.json +0 -1617
  107. package/apps/storefront/migrations-apps/meta/0006_snapshot.json +0 -1716
  108. package/apps/storefront/migrations-apps/meta/0007_snapshot.json +0 -1812
  109. package/apps/storefront/migrations-apps/meta/0008_snapshot.json +0 -1881
  110. package/apps/storefront/migrations-apps/meta/0009_snapshot.json +0 -1979
  111. package/apps/storefront/migrations-apps/meta/_journal.json +0 -76
  112. package/apps/storefront/perf/README.md +0 -64
  113. package/apps/storefront/perf/assert-budgets.ts +0 -159
  114. package/apps/storefront/platform-reconcile-tenants.json +0 -3
  115. package/apps/storefront/playwright.config.ts +0 -23
  116. package/apps/storefront/public/js/dashboard-access-banner.js +0 -53
  117. package/apps/storefront/public/js/dashboard-apps.js +0 -183
  118. package/apps/storefront/public/js/dashboard-contact-capture.js +0 -52
  119. package/apps/storefront/public/js/dashboard-delegate.js +0 -167
  120. package/apps/storefront/public/js/dashboard-team.js +0 -356
  121. package/apps/storefront/public/js/dashboard-vendor-search.js +0 -115
  122. package/apps/storefront/src/components/content/storefront/AsyncStylesheet.astro +0 -26
  123. package/apps/storefront/src/components/integrations/storefront/WidgetFrame.astro +0 -34
  124. package/apps/storefront/src/config/adminTenantLookup.ts +0 -35
  125. package/apps/storefront/src/config/evidenceTenantRoster.ts +0 -25
  126. package/apps/storefront/src/config/staffProvisionProjection.ts +0 -24
  127. package/apps/storefront/src/config/storeName.ts +0 -34
  128. package/apps/storefront/src/lib/access/admin/README.md +0 -122
  129. package/apps/storefront/src/lib/access/admin/adminShell.ts +0 -281
  130. package/apps/storefront/src/lib/access/admin/envelope.ts +0 -9
  131. package/apps/storefront/src/lib/access/admin/viewmodels/settings.ts +0 -64
  132. package/apps/storefront/src/lib/access/auth/adminApiGuard.ts +0 -66
  133. package/apps/storefront/src/lib/access/auth/adminEntry.ts +0 -126
  134. package/apps/storefront/src/lib/access/auth/mcpClientAssertion.ts +0 -217
  135. package/apps/storefront/src/lib/access/auth/operatorSession.ts +0 -120
  136. package/apps/storefront/src/lib/access/dashboard/delegateGate.ts +0 -130
  137. package/apps/storefront/src/lib/access/dashboard/staffStoreEntry.ts +0 -150
  138. package/apps/storefront/src/lib/access/dashboard/staffVendorAccess.ts +0 -452
  139. package/apps/storefront/src/lib/access/dashboard/vendorQuery.ts +0 -61
  140. package/apps/storefront/src/lib/access/fixtures/settings.ts +0 -67
  141. package/apps/storefront/src/lib/access/fixtures/tenants.ts +0 -29
  142. package/apps/storefront/src/lib/access/notifications/magicLinkInviteEmail.ts +0 -62
  143. package/apps/storefront/src/lib/access/shared/grantContactLookup.ts +0 -97
  144. package/apps/storefront/src/lib/access/shared/principalGrants.ts +0 -775
  145. package/apps/storefront/src/lib/activity/alerts.ts +0 -426
  146. package/apps/storefront/src/lib/activity/candidateSubmitLease.ts +0 -87
  147. package/apps/storefront/src/lib/activity/changeActorAttribution.ts +0 -181
  148. package/apps/storefront/src/lib/activity/evidence/evidenceReference.ts +0 -32
  149. package/apps/storefront/src/lib/activity/fixtures/evidence.ts +0 -99
  150. package/apps/storefront/src/lib/activity/query.ts +0 -403
  151. package/apps/storefront/src/lib/activity/uiActor.ts +0 -152
  152. package/apps/storefront/src/lib/admin/services/mock/index.ts +0 -12
  153. package/apps/storefront/src/lib/assets/addons/catalog.ts +0 -60
  154. package/apps/storefront/src/lib/assets/addons/storeEntitlements.ts +0 -260
  155. package/apps/storefront/src/lib/assets/durableAssetsRoute.ts +0 -65
  156. package/apps/storefront/src/lib/assets/durableR2.ts +0 -473
  157. package/apps/storefront/src/lib/assets/durableR2Bindings.ts +0 -33
  158. package/apps/storefront/src/lib/automation/admin/viewmodels/aiWorkflows.ts +0 -65
  159. package/apps/storefront/src/lib/automation/ai/approvalMode.ts +0 -20
  160. package/apps/storefront/src/lib/automation/ai/askEnvelope.ts +0 -47
  161. package/apps/storefront/src/lib/automation/ai/audit.ts +0 -12
  162. package/apps/storefront/src/lib/automation/ai/operationalRuns.ts +0 -155
  163. package/apps/storefront/src/lib/automation/ai/recommendation.ts +0 -20
  164. package/apps/storefront/src/lib/automation/fixtures/aiWorkflows.ts +0 -59
  165. package/apps/storefront/src/lib/catalog/admin/catalogSettingsClient.ts +0 -250
  166. package/apps/storefront/src/lib/catalog/admin/catalogSettingsFields.ts +0 -134
  167. package/apps/storefront/src/lib/catalog/admin/catalogSettingsPreview.ts +0 -37
  168. package/apps/storefront/src/lib/catalog/admin/catalogSettingsPricingView.ts +0 -39
  169. package/apps/storefront/src/lib/catalog/admin/catalogSettingsRuleView.ts +0 -44
  170. package/apps/storefront/src/lib/catalog/admin/catalogSettingsSkuView.ts +0 -21
  171. package/apps/storefront/src/lib/catalog/admin/catalogSettingsState.ts +0 -132
  172. package/apps/storefront/src/lib/catalog/admin/productSetupPhoto.ts +0 -23
  173. package/apps/storefront/src/lib/catalog/admin/productsTabClient.ts +0 -193
  174. package/apps/storefront/src/lib/catalog/admin/services/catalogProducts.ts +0 -32
  175. package/apps/storefront/src/lib/catalog/admin/viewmodels/catalogProducts.ts +0 -164
  176. package/apps/storefront/src/lib/catalog/admin/viewmodels/products.ts +0 -267
  177. package/apps/storefront/src/lib/catalog/fixtures/products.ts +0 -105
  178. package/apps/storefront/src/lib/catalog/tot/syncState.ts +0 -111
  179. package/apps/storefront/src/lib/checkout/admin/checkoutStyleInput.ts +0 -172
  180. package/apps/storefront/src/lib/checkout/admin/checkoutStyleTarget.ts +0 -65
  181. package/apps/storefront/src/lib/checkout/browser/checkoutExciseForm.ts +0 -152
  182. package/apps/storefront/src/lib/checkout/browser/checkoutRequirementsForm.ts +0 -72
  183. package/apps/storefront/src/lib/checkout/browser/checkoutStyleForm.ts +0 -110
  184. package/apps/storefront/src/lib/checkout/browser/settingDraftActions.ts +0 -367
  185. package/apps/storefront/src/lib/checkout/commerce/checkoutSettings.ts +0 -246
  186. package/apps/storefront/src/lib/checkout/fixtures/checkoutSettings.ts +0 -77
  187. package/apps/storefront/src/lib/content/blog/markdown.ts +0 -174
  188. package/apps/storefront/src/lib/content/chrome/examples/tokenoftrust.chrome-assignments.example.json +0 -6
  189. package/apps/storefront/src/lib/content/chrome/examples/tokenoftrust.chrome.example.json +0 -79
  190. package/apps/storefront/src/lib/content/index.ts +0 -27
  191. package/apps/storefront/src/lib/content/the-build/readingTime.ts +0 -35
  192. package/apps/storefront/src/lib/content/the-build/toc.ts +0 -95
  193. package/apps/storefront/src/lib/customers/admin/viewmodels/customers.ts +0 -56
  194. package/apps/storefront/src/lib/customers/contactVault/blindIndex.ts +0 -28
  195. package/apps/storefront/src/lib/customers/contactVault/contactAudit.ts +0 -149
  196. package/apps/storefront/src/lib/customers/contactVault/dataKeys.ts +0 -283
  197. package/apps/storefront/src/lib/customers/contactVault/fieldEnvelope.ts +0 -88
  198. package/apps/storefront/src/lib/customers/contactVault/isolateMetrics.ts +0 -37
  199. package/apps/storefront/src/lib/customers/contactVault/kms.ts +0 -292
  200. package/apps/storefront/src/lib/customers/contactVault/retention.ts +0 -302
  201. package/apps/storefront/src/lib/customers/contactVault/retentionPolicy.ts +0 -290
  202. package/apps/storefront/src/lib/customers/contactVault/zip3.ts +0 -24
  203. package/apps/storefront/src/lib/customers/fixtures/customers.ts +0 -86
  204. package/apps/storefront/src/lib/developer-experience/admin/memoizeByEnvelope.ts +0 -27
  205. package/apps/storefront/src/lib/developer-experience/admin/seed.ts +0 -54
  206. package/apps/storefront/src/lib/developer-experience/dev/activityIngestToken.ts +0 -85
  207. package/apps/storefront/src/lib/developer-experience/dev/activityStore.ts +0 -82
  208. package/apps/storefront/src/lib/developer-experience/dev/ai-widget-client.js +0 -308
  209. package/apps/storefront/src/lib/developer-experience/dev/apiBase.ts +0 -17
  210. package/apps/storefront/src/lib/developer-experience/dev/cliSignInCode.ts +0 -124
  211. package/apps/storefront/src/lib/developer-experience/dev/cockpit/ask.ts +0 -49
  212. package/apps/storefront/src/lib/developer-experience/dev/cockpit/clickToSource.ts +0 -71
  213. package/apps/storefront/src/lib/developer-experience/dev/cockpit/copyCommand.ts +0 -227
  214. package/apps/storefront/src/lib/developer-experience/dev/cockpit/files.ts +0 -249
  215. package/apps/storefront/src/lib/developer-experience/dev/cockpit/hostedActivity.ts +0 -500
  216. package/apps/storefront/src/lib/developer-experience/dev/cockpit/infoPopover.ts +0 -12
  217. package/apps/storefront/src/lib/developer-experience/dev/cockpit/mcpCopy.ts +0 -34
  218. package/apps/storefront/src/lib/developer-experience/dev/cockpit/monitor.ts +0 -107
  219. package/apps/storefront/src/lib/developer-experience/dev/cockpit/stepper.ts +0 -116
  220. package/apps/storefront/src/lib/developer-experience/dev/cockpit/themeToggle.ts +0 -23
  221. package/apps/storefront/src/lib/developer-experience/dev/livePreview.ts +0 -77
  222. package/apps/storefront/src/lib/developer-experience/dev/obstacleStore.ts +0 -214
  223. package/apps/storefront/src/lib/developer-experience/dev/previewStatus.ts +0 -87
  224. package/apps/storefront/src/lib/developer-experience/dev/rendezvousBroker.ts +0 -226
  225. package/apps/storefront/src/lib/developer-experience/dev/runtimeStore.ts +0 -291
  226. package/apps/storefront/src/lib/developer-experience/dev/storeStatus.ts +0 -142
  227. package/apps/storefront/src/lib/developer-experience/dev/subjectReissue.ts +0 -67
  228. package/apps/storefront/src/lib/developer-experience/fixtures/regulated-commerce-truth/index.ts +0 -540
  229. package/apps/storefront/src/lib/developer-experience/fixtures/ws3-readonly-clone-preflight/index.ts +0 -495
  230. package/apps/storefront/src/lib/engagement/contact/contactMessages.ts +0 -671
  231. package/apps/storefront/src/lib/engagement/contact/messagesTabClient.ts +0 -175
  232. package/apps/storefront/src/lib/engagement/contact/submission.ts +0 -112
  233. package/apps/storefront/src/lib/engagement/messaging/messagesClient.ts +0 -149
  234. package/apps/storefront/src/lib/engagement/newsletter/digest.ts +0 -117
  235. package/apps/storefront/src/lib/engagement/newsletter/resendClient.ts +0 -79
  236. package/apps/storefront/src/lib/engagement/newsletter/send.ts +0 -265
  237. package/apps/storefront/src/lib/engagement/social/golive.ts +0 -212
  238. package/apps/storefront/src/lib/engagement/social/notify.ts +0 -32
  239. package/apps/storefront/src/lib/engagement/social/tokenStore.ts +0 -171
  240. package/apps/storefront/src/lib/fulfillment/admin/commerceDesk.ts +0 -180
  241. package/apps/storefront/src/lib/fulfillment/admin/commerceDeskRouting.ts +0 -45
  242. package/apps/storefront/src/lib/fulfillment/admin/viewmodels/fulfillment.ts +0 -1071
  243. package/apps/storefront/src/lib/fulfillment/appShipmentEvidence.ts +0 -271
  244. package/apps/storefront/src/lib/fulfillment/carrierEvidence.ts +0 -105
  245. package/apps/storefront/src/lib/fulfillment/commerceProjection.ts +0 -157
  246. package/apps/storefront/src/lib/fulfillment/commerceReadback.ts +0 -60
  247. package/apps/storefront/src/lib/fulfillment/commerceRecovery.ts +0 -84
  248. package/apps/storefront/src/lib/fulfillment/commerceRuntime.ts +0 -41
  249. package/apps/storefront/src/lib/fulfillment/fulfillmentService.ts +0 -2842
  250. package/apps/storefront/src/lib/fulfillment/readiness.ts +0 -217
  251. package/apps/storefront/src/lib/fulfillment/splitShipments.ts +0 -388
  252. package/apps/storefront/src/lib/fulfillment/syntheticPreviewOrders.ts +0 -292
  253. package/apps/storefront/src/lib/integrations/apps/appContactAuthority.ts +0 -27
  254. package/apps/storefront/src/lib/integrations/apps/appContactConsents.ts +0 -118
  255. package/apps/storefront/src/lib/integrations/apps/appInstallEnv.ts +0 -28
  256. package/apps/storefront/src/lib/integrations/apps/gtmMigrationDraft.ts +0 -103
  257. package/apps/storefront/src/lib/integrations/apps/inventoryWrite.ts +0 -906
  258. package/apps/storefront/src/lib/integrations/apps/orders/customerHash.ts +0 -28
  259. package/apps/storefront/src/lib/integrations/apps/orders/idempotency.ts +0 -100
  260. package/apps/storefront/src/lib/integrations/apps/reports/salesVelocityReport.ts +0 -96
  261. package/apps/storefront/src/lib/integrations/apps/routeParams.ts +0 -45
  262. package/apps/storefront/src/lib/integrations/webhooks/cloudflareQueueDispatcher.ts +0 -82
  263. package/apps/storefront/src/lib/integrations/webhooks/commercePayloads.ts +0 -159
  264. package/apps/storefront/src/lib/integrations/webhooks/deliveryEngine.ts +0 -379
  265. package/apps/storefront/src/lib/integrations/webhooks/deliveryMapper.ts +0 -34
  266. package/apps/storefront/src/lib/integrations/webhooks/deliveryStore.ts +0 -903
  267. package/apps/storefront/src/lib/integrations/webhooks/dispatcher.ts +0 -168
  268. package/apps/storefront/src/lib/integrations/webhooks/emit.ts +0 -245
  269. package/apps/storefront/src/lib/integrations/webhooks/events.ts +0 -105
  270. package/apps/storefront/src/lib/integrations/webhooks/getDispatcher.ts +0 -77
  271. package/apps/storefront/src/lib/integrations/webhooks/orderFulfilledClaim.ts +0 -75
  272. package/apps/storefront/src/lib/measurement/admin/analyticsRegionPolicy.ts +0 -151
  273. package/apps/storefront/src/lib/measurement/admin/analyticsRegionsClient.ts +0 -84
  274. package/apps/storefront/src/lib/measurement/admin/consentSettingsClient.ts +0 -113
  275. package/apps/storefront/src/lib/measurement/analytics/index.ts +0 -44
  276. package/apps/storefront/src/lib/measurement/attribution/attributionService.ts +0 -206
  277. package/apps/storefront/src/lib/measurement/attribution/orderConversionD1.ts +0 -150
  278. package/apps/storefront/src/lib/measurement/attribution/verifiedProviderMeasurement.ts +0 -118
  279. package/apps/storefront/src/lib/measurement/tracking/interactionCollector.ts +0 -205
  280. package/apps/storefront/src/lib/measurement/tracking/pruneRollup.ts +0 -260
  281. package/apps/storefront/src/lib/measurement/tracking/tenantReadAccess.ts +0 -138
  282. package/apps/storefront/src/lib/measurement/tracking-writeback/rewriteTrackingIds.ts +0 -175
  283. package/apps/storefront/src/lib/measurement/tracking-writeback/writebackCandidate.ts +0 -110
  284. package/apps/storefront/src/lib/observability/diag/capture.ts +0 -162
  285. package/apps/storefront/src/lib/observability/diag/consoleLine.ts +0 -76
  286. package/apps/storefront/src/lib/observability/diag/debugConsole.ts +0 -118
  287. package/apps/storefront/src/lib/observability/diag/debugMode.ts +0 -163
  288. package/apps/storefront/src/lib/observability/diag/debugWindow.ts +0 -111
  289. package/apps/storefront/src/lib/observability/diag/redact.ts +0 -17
  290. package/apps/storefront/src/lib/observability/diag/reference.ts +0 -148
  291. package/apps/storefront/src/lib/observability/diag/referenceStore.ts +0 -113
  292. package/apps/storefront/src/lib/observability/diag/report.ts +0 -110
  293. package/apps/storefront/src/lib/observability/diag/serverResponseTime.ts +0 -91
  294. package/apps/storefront/src/lib/observability/diag/session.ts +0 -93
  295. package/apps/storefront/src/lib/observability/monitoring/manifest.ts +0 -301
  296. package/apps/storefront/src/lib/observability/performance/lighthouseReport.ts +0 -109
  297. package/apps/storefront/src/lib/observability/performance/rumAlert.ts +0 -179
  298. package/apps/storefront/src/lib/orders/admin/orderActions.ts +0 -556
  299. package/apps/storefront/src/lib/orders/admin/orderClient.ts +0 -248
  300. package/apps/storefront/src/lib/orders/admin/orderSource.ts +0 -410
  301. package/apps/storefront/src/lib/orders/admin/services/orders.ts +0 -922
  302. package/apps/storefront/src/lib/orders/admin/viewmodels/orders.ts +0 -135
  303. package/apps/storefront/src/lib/orders/data/commerceCallerConfig.ts +0 -37
  304. package/apps/storefront/src/lib/orders/data/ledgerContractOrders.ts +0 -148
  305. package/apps/storefront/src/lib/orders/data/orderForwardReceiver.ts +0 -532
  306. package/apps/storefront/src/lib/orders/data/orderMapper.ts +0 -454
  307. package/apps/storefront/src/lib/orders/data/ordersStore.ts +0 -623
  308. package/apps/storefront/src/lib/orders/data/sourceAuthorityContract.ts +0 -380
  309. package/apps/storefront/src/lib/orders/data/sourceAuthorityStore.ts +0 -830
  310. package/apps/storefront/src/lib/orders/fixtures/orders.ts +0 -186
  311. package/apps/storefront/src/lib/orders/providers/foxyOrderClient.ts +0 -207
  312. package/apps/storefront/src/lib/orders/vault/appRecipientRead.ts +0 -222
  313. package/apps/storefront/src/lib/orders/vault/contactIntake.ts +0 -63
  314. package/apps/storefront/src/lib/orders/vault/contactRoutes.ts +0 -110
  315. package/apps/storefront/src/lib/orders/vault/kmsEnv.ts +0 -11
  316. package/apps/storefront/src/lib/orders/vault/orderContact.ts +0 -96
  317. package/apps/storefront/src/lib/orders/vault/orderContactVault.ts +0 -1427
  318. package/apps/storefront/src/lib/orders/vault/vault-test-support.ts +0 -258
  319. package/apps/storefront/src/lib/publication/d1/schema-apps.ts +0 -808
  320. package/apps/storefront/src/lib/publication/notifications/candidateConflictEmail.ts +0 -80
  321. package/apps/storefront/src/lib/publication/servingMode.ts +0 -52
  322. package/apps/storefront/src/lib/publication/shared/previewAnnotations/moduleAsset.ts +0 -65
  323. package/apps/storefront/src/lib/publication/shared/routedApiParam.ts +0 -38
  324. package/apps/storefront/src/lib/reporting/admin/viewmodels/reporting.ts +0 -34
  325. package/apps/storefront/src/lib/reporting/fixtures/reporting.ts +0 -51
  326. package/apps/storefront/src/lib/subscriptions/admin/viewmodels/subscriptions.ts +0 -106
  327. package/apps/storefront/src/lib/subscriptions/fixtures/subscriptions.ts +0 -398
  328. package/apps/storefront/src/pages/api/admin/activity-alerts.ts +0 -58
  329. package/apps/storefront/src/pages/api/admin/commerce-readiness.ts +0 -172
  330. package/apps/storefront/src/pages/api/admin/fulfillment/batches.ts +0 -59
  331. package/apps/storefront/src/pages/api/admin/fulfillment/orders/[id]/address.ts +0 -66
  332. package/apps/storefront/src/pages/api/admin/fulfillment/orders/[id].ts +0 -118
  333. package/apps/storefront/src/pages/api/admin/fulfillment/orders/contact-search.ts +0 -26
  334. package/apps/storefront/src/pages/api/admin/fulfillment/orders/contacts.ts +0 -22
  335. package/apps/storefront/src/pages/api/admin/interaction-insights.ts +0 -101
  336. package/apps/storefront/src/pages/api/admin/orders/[id].ts +0 -63
  337. package/apps/storefront/src/pages/api/admin/orders.ts +0 -65
  338. package/apps/storefront/src/pages/api/contact.ts +0 -144
  339. package/apps/storefront/src/scheduled/contactVaultSweep.ts +0 -113
  340. package/apps/storefront/src/styles/admin.css +0 -1161
  341. package/apps/storefront/test/pipeline/fake-preview-services.ts +0 -288
  342. package/apps/storefront/test/pipeline/harness.ts +0 -209
  343. package/apps/storefront/test/pipeline/intake-worker.mjs +0 -14
  344. package/apps/storefront/test/pipeline/matrix-faults.ts +0 -366
  345. package/apps/storefront/test/pipeline/pipeline-host.ts +0 -418
  346. package/apps/storefront/test/pipeline/pool-config.cjs +0 -85
  347. package/apps/storefront/test/pipeline/publish-kinds.ts +0 -279
  348. package/apps/storefront/test/pipeline/synthetic-job.ts +0 -303
  349. package/apps/storefront/test/pipeline-faults/matrix-lib.ts +0 -696
  350. package/apps/storefront/vitest.config.cts +0 -44
  351. package/apps/storefront/vitest.faults.config.cts +0 -13
  352. package/apps/storefront/vitest.workers.config.cts +0 -7
  353. package/packages/feedback/fixtures/v1/expected-findings.json +0 -16
  354. package/packages/feedback/fixtures/v1/feedback-action/invalid/carries-transport-credential.json +0 -14
  355. package/packages/feedback/fixtures/v1/feedback-action/invalid/control-char-in-description.json +0 -13
  356. package/packages/feedback/fixtures/v1/feedback-action/invalid/legacy-schema-version.json +0 -13
  357. package/packages/feedback/fixtures/v1/feedback-action/invalid/page-path-with-query.json +0 -14
  358. package/packages/feedback/fixtures/v1/feedback-action/invalid/title-too-short.json +0 -13
  359. package/packages/feedback/fixtures/v1/feedback-action/valid/element-problem.json +0 -33
  360. package/packages/feedback/fixtures/v1/feedback-action/valid/page-comment.json +0 -20
  361. package/packages/feedback/fixtures/v1/feedback-action/valid/region-improvement.json +0 -24
  362. package/packages/feedback/fixtures/v1/feedback-action/valid/text-selection-feature.json +0 -30
  363. package/packages/feedback/fixtures/v1/submission-receipt/invalid/accepted-at-not-utc.json +0 -9
  364. package/packages/feedback/fixtures/v1/submission-receipt/invalid/bad-feedback-id.json +0 -9
  365. package/packages/feedback/fixtures/v1/submission-receipt/invalid/legacy-contract-version.json +0 -9
  366. package/packages/feedback/fixtures/v1/submission-receipt/invalid/missing-replayed.json +0 -8
  367. package/packages/feedback/fixtures/v1/submission-receipt/valid/accepted.json +0 -9
  368. package/packages/feedback/fixtures/v1/submission-receipt/valid/fractional-seconds.json +0 -9
  369. package/packages/feedback/fixtures/v1/submission-receipt/valid/replayed.json +0 -9
  370. package/packages/feedback/fixtures/v1/target-evidence/invalid/page-kind-claims-structure.json +0 -6
  371. package/packages/feedback/fixtures/v1/target-evidence/invalid/path-too-deep.json +0 -17
  372. package/packages/feedback/fixtures/v1/target-evidence/invalid/relative-region-out-of-range.json +0 -11
  373. package/packages/feedback/fixtures/v1/target-evidence/invalid/selector-uses-class.json +0 -7
  374. package/packages/feedback/fixtures/v1/target-evidence/invalid/source-precision-without-anchor.json +0 -6
  375. package/packages/feedback/fixtures/v1/target-evidence/valid/element-structure.json +0 -21
  376. package/packages/feedback/fixtures/v1/target-evidence/valid/host-iframe.json +0 -14
  377. package/packages/feedback/fixtures/v1/target-evidence/valid/source-anchor.json +0 -12
  378. package/packages/feedback/fixtures/v1/target-evidence/valid/text-selection.json +0 -26
  379. package/packages/feedback/package.json +0 -35
  380. package/packages/feedback/scripts/build-player.mjs +0 -28
  381. package/packages/feedback/src/index.ts +0 -1
  382. package/packages/feedback/src/primitives/composer.ts +0 -639
  383. package/packages/feedback/src/primitives/dialog.ts +0 -263
  384. package/packages/feedback/src/primitives/hostAdapter.ts +0 -116
  385. package/packages/feedback/src/primitives/index.ts +0 -10
  386. package/packages/feedback/src/primitives/launcher.ts +0 -200
  387. package/packages/feedback/src/primitives/picker.ts +0 -663
  388. package/packages/feedback/src/primitives/redaction.ts +0 -204
  389. package/packages/feedback/src/primitives/selection.ts +0 -49
  390. package/packages/feedback/src/primitives/shiftAccelerator.ts +0 -160
  391. package/packages/feedback/src/primitives/styles.ts +0 -77
  392. package/packages/feedback/src/primitives/surface.ts +0 -124
  393. package/packages/feedback/src/primitives/target.ts +0 -293
  394. package/packages/feedback/src/tour/canonical.ts +0 -27
  395. package/packages/feedback/src/tour/index.ts +0 -3
  396. package/packages/feedback/src/tour/player/browser.ts +0 -5
  397. package/packages/feedback/src/tour/player/host.ts +0 -12
  398. package/packages/feedback/src/tour/player/index.ts +0 -205
  399. package/packages/feedback/src/tour/player/manifest.ts +0 -76
  400. package/packages/feedback/src/tour/player/player.css +0 -130
  401. package/packages/feedback/src/tour/player/resolver.ts +0 -12
  402. package/packages/feedback/src/tour/player/surface.ts +0 -295
  403. package/packages/feedback/src/tour/player/types.ts +0 -8
  404. package/packages/feedback/src/tour/resolve/core.ts +0 -267
  405. package/packages/feedback/src/tour/resolve/dom.ts +0 -115
  406. package/packages/feedback/src/tour/resolve/index.ts +0 -29
  407. package/packages/feedback/src/tour/sanitize.ts +0 -76
  408. package/packages/feedback/src/tour/schema.ts +0 -362
  409. package/packages/feedback/src/v1/guards.ts +0 -335
  410. package/packages/feedback/src/v1/index.ts +0 -3
  411. package/packages/feedback/src/v1/protectedSurfaces.ts +0 -32
  412. package/packages/feedback/src/v1/types.ts +0 -177
  413. package/packages/feedback/tsconfig.json +0 -9
  414. package/packages/feedback/vitest.config.cts +0 -21
@@ -0,0 +1,447 @@
1
+ /**
2
+ * Review and confirm handlers for assistant cart proposals.
3
+ *
4
+ * Review resolves an assistant's lines against the routed tenant's own catalog into an offer the
5
+ * shopper can read. Confirm takes only the reviewed proposal id and digest, resolves the lines
6
+ * again, and hands them into the same server-owned signed cart pipeline an ordinary product page
7
+ * uses. Tenant, price, tax, shipping, destination and order source come from the request's
8
+ * trusted context and the catalog; an assistant or shopper payload can supply none of them, and
9
+ * no step here charges, submits an order or attests verification.
10
+ *
11
+ * Logs carry the tenant, stable reason codes and counts. They never carry list text, line text,
12
+ * ids a shopper typed, or buyer data.
13
+ */
14
+ import type { APIContext } from "astro";
15
+ import {
16
+ buildVariantCartPayload,
17
+ commerceTenantId,
18
+ enforceCartSubmission,
19
+ signCartLine,
20
+ tenantPublicOrigin,
21
+ CART_PROPOSAL_TTL_SECONDS,
22
+ CHECKOUT_NAVIGATION_REFERRER_POLICY,
23
+ SHIPPING_UNAVAILABLE_CART_MESSAGE,
24
+ type CartProposalLine,
25
+ type CartProposalReason,
26
+ type TenantConfig,
27
+ } from "@tot/public-runtime";
28
+ import { addProposalToBoundCart, CART_UNAVAILABLE_MESSAGE, withCartSession } from "@/lib/checkout/commerce/cartSession";
29
+ import { completeCartFields, ledgerSoldOut, trustedReturnUrl } from "@/lib/checkout/commerce/checkoutHandoffRoute";
30
+ import { resolveCartSigning, shopperCartDenialMessage, type CartSigningResolution } from "@/lib/checkout/shared/checkoutCommerce";
31
+ import {
32
+ catalogEntries,
33
+ decodeProposalId,
34
+ encodeProposalId,
35
+ proposalAge,
36
+ proposalIdKey,
37
+ proposalReplayKey,
38
+ resolveProposalLines,
39
+ validateConfirmRequest,
40
+ validateReviewRequest,
41
+ type ProposalCatalog,
42
+ type ProposalRequestLine,
43
+ } from "./cartProposal";
44
+ import { matchList } from "./listMatcher";
45
+ import { renderPasteForm, renderRefusal, renderReview, type ReviewView } from "./reviewHtml";
46
+
47
+ export const CART_PROPOSAL_REVIEW_PATH = "/api/cart-proposal/review";
48
+ export const CART_PROPOSAL_CONFIRM_PATH = "/api/cart-proposal/confirm";
49
+
50
+ const MAX_BODY_BYTES = 65_536;
51
+ const NO_COMMERCE_MESSAGE = "Checkout is unavailable because this store has no cart configured.";
52
+
53
+ export interface ProposalCompliance {
54
+ status: string;
55
+ blocks: Array<{ code: string; message: string }>;
56
+ }
57
+
58
+ export interface ProposalDeps {
59
+ /** Seconds since the epoch. */
60
+ now?: () => number;
61
+ /** The compliance preflight of the reviewed lines; null when it cannot be evaluated. */
62
+ preflight?: (context: APIContext, lines: readonly CartProposalLine[]) => Promise<ProposalCompliance | null>;
63
+ fetch?: typeof fetch;
64
+ }
65
+
66
+ export interface ConfirmDeps extends ProposalDeps {
67
+ /**
68
+ * The path of a product's own page in the tenant's declared URL form. Supplied by the route so
69
+ * the checkout capability does not import the content capability's URL rules. Confirm signs it as
70
+ * the cart line's return page, as an ordinary product page does.
71
+ */
72
+ productPagePath: (context: APIContext, handle: string) => string;
73
+ }
74
+
75
+ const SECURITY_HEADERS = {
76
+ "cache-control": "private, no-store",
77
+ "x-robots-tag": "noindex, nofollow",
78
+ "referrer-policy": "no-referrer",
79
+ "x-tot-payment-authorized": "false",
80
+ } as const;
81
+
82
+ function jsonReply(body: unknown, status: number, extra: Record<string, string> = {}): Response {
83
+ return new Response(JSON.stringify(body), {
84
+ status,
85
+ headers: { "content-type": "application/json; charset=utf-8", ...SECURITY_HEADERS, ...extra },
86
+ });
87
+ }
88
+
89
+ function htmlReply(html: string, status: number): Response {
90
+ return new Response(html, {
91
+ status,
92
+ headers: { "content-type": "text/html; charset=utf-8", ...SECURITY_HEADERS },
93
+ });
94
+ }
95
+
96
+ function wantsJson(request: Request): boolean {
97
+ const accept = request.headers.get("accept") ?? "";
98
+ if (accept.includes("application/json")) return true;
99
+ if (accept.includes("text/html")) return false;
100
+ return (request.headers.get("content-type") ?? "").includes("application/json");
101
+ }
102
+
103
+ function basePrefix(context: APIContext): string {
104
+ return (context.locals.apiBasePath ?? context.locals.basePath ?? "").replace(/\/+$/, "");
105
+ }
106
+
107
+ function logProposal(context: APIContext, event: string, detail: Record<string, string | number | boolean>): void {
108
+ console.info(`[storefront] cart-proposal ${event} ${JSON.stringify({
109
+ tenant: context.locals.tenant.tenant_id,
110
+ stage: context.locals.browserEnvironment?.environment ?? "unknown",
111
+ ...detail,
112
+ })}`);
113
+ }
114
+
115
+ interface Refusal {
116
+ status: number;
117
+ code: CartProposalReason;
118
+ message: string;
119
+ reasons?: Array<{ code: CartProposalReason; field?: string }>;
120
+ }
121
+
122
+ function refuse(context: APIContext, refusal: Refusal, event: string): Response {
123
+ logProposal(context, event, { code: refusal.code, reasons: refusal.reasons?.length ?? 1 });
124
+ if (wantsJson(context.request)) {
125
+ return jsonReply({
126
+ error: refusal.code,
127
+ ...(refusal.reasons ? { reasons: refusal.reasons } : {}),
128
+ message: refusal.message,
129
+ }, refusal.status);
130
+ }
131
+ return htmlReply(renderRefusal(refusal.code, refusal.message), refusal.status);
132
+ }
133
+
134
+ /** The parsed request body: JSON or a urlencoded form, bounded. `null` is an unreadable body. */
135
+ async function readBody(request: Request): Promise<Record<string, unknown> | unknown[] | null> {
136
+ const type = request.headers.get("content-type") ?? "";
137
+ const declared = Number(request.headers.get("content-length") ?? "0");
138
+ if (Number.isFinite(declared) && declared > MAX_BODY_BYTES) return null;
139
+ let text: string;
140
+ try {
141
+ text = await request.text();
142
+ } catch (error) {
143
+ // A body stream that fails mid-read (client abort, reset) is an unreadable body, not a defect.
144
+ if (error instanceof TypeError || error instanceof DOMException) return null;
145
+ throw error;
146
+ }
147
+ if (text.length > MAX_BODY_BYTES) return null;
148
+ if (type.includes("application/json")) {
149
+ try {
150
+ const parsed: unknown = JSON.parse(text);
151
+ return parsed && typeof parsed === "object" ? (parsed as Record<string, unknown> | unknown[]) : null;
152
+ } catch (error) {
153
+ if (error instanceof SyntaxError) return null;
154
+ throw error;
155
+ }
156
+ }
157
+ if (type.includes("application/x-www-form-urlencoded")) {
158
+ const body: Record<string, unknown> = {};
159
+ for (const [name, value] of new URLSearchParams(text)) body[name] = value;
160
+ return body;
161
+ }
162
+ return null;
163
+ }
164
+
165
+ /** A cart-changing request must come from this store's own pages. */
166
+ function sameOrigin(context: APIContext): boolean {
167
+ const { request } = context;
168
+ const site = request.headers.get("sec-fetch-site");
169
+ if (site && site !== "same-origin" && site !== "none") return false;
170
+ const origin = request.headers.get("origin");
171
+ if (!origin) return true;
172
+ // A page served with `referrer-policy: no-referrer` (the review page) submits its own forms with
173
+ // `Origin: null`. That is this store's own page only when the browser also says same-origin.
174
+ if (origin === "null") return site === "same-origin";
175
+ let host: string;
176
+ try {
177
+ host = new URL(origin).host.toLowerCase();
178
+ } catch {
179
+ return false;
180
+ }
181
+ const { tenant } = context.locals;
182
+ const domain = tenant.appDomain?.toLowerCase();
183
+ const allowed = [new URL(request.url).host.toLowerCase(), ...(domain ? [domain, `www.${domain}`] : [])];
184
+ if (context.locals.requestOrigin) {
185
+ try {
186
+ allowed.push(new URL(context.locals.requestOrigin).host.toLowerCase());
187
+ } catch { /* an unreadable declared origin allows nothing extra */ }
188
+ }
189
+ return allowed.includes(host);
190
+ }
191
+
192
+ async function proposalCatalog(context: APIContext, tenant: TenantConfig): Promise<ProposalCatalog> {
193
+ return {
194
+ tenantScope: tenant.tot_data_scope,
195
+ currency: tenant.currency,
196
+ products: await context.locals.tot.getAllActiveProducts(),
197
+ soldOut: (sku) => ledgerSoldOut(context, tenant, sku),
198
+ };
199
+ }
200
+
201
+ /** The cart-signing resolution, or the refusal to return when this store cannot sign carts. */
202
+ async function proposalSigning(
203
+ context: APIContext,
204
+ commerce: NonNullable<APIContext["locals"]["commerce"]>,
205
+ event: string,
206
+ ): Promise<CartSigningResolution | Response> {
207
+ let signing: CartSigningResolution;
208
+ try {
209
+ signing = await resolveCartSigning(commerce);
210
+ } catch {
211
+ return refuse(context, {
212
+ status: 503,
213
+ code: "commerce_unavailable",
214
+ message: shopperCartDenialMessage("signing-unavailable", ""),
215
+ }, event);
216
+ }
217
+ if (!signing.enabled) {
218
+ return refuse(context, {
219
+ status: 503,
220
+ code: "commerce_unavailable",
221
+ message: shopperCartDenialMessage("signing-unavailable", signing.operatorError ?? ""),
222
+ }, event);
223
+ }
224
+ return signing;
225
+ }
226
+
227
+ function total(lines: readonly CartProposalLine[]): number {
228
+ return lines.reduce((sum, line) => sum + Math.round(line.lineTotal * 100), 0) / 100;
229
+ }
230
+
231
+ /** GET: the paste form. */
232
+ export function cartProposalForm(context: APIContext): Response {
233
+ const prefix = basePrefix(context);
234
+ return htmlReply(renderPasteForm(`${prefix}${CART_PROPOSAL_REVIEW_PATH}`), 200);
235
+ }
236
+
237
+ /** POST: resolve an assistant's lines into a reviewable offer. Reads only; changes no cart. */
238
+ export async function cartProposalReview(context: APIContext, deps: ProposalDeps = {}): Promise<Response> {
239
+ const { tenant, commerce } = context.locals;
240
+ if (!commerce) {
241
+ return refuse(context, { status: 409, code: "commerce_unavailable", message: NO_COMMERCE_MESSAGE }, "review-refused");
242
+ }
243
+ const signing = await proposalSigning(context, commerce, "review-refused");
244
+ if (signing instanceof Response) return signing;
245
+ const body = await readBody(context.request);
246
+ const validated = validateReviewRequest(body);
247
+ if (!validated.ok) {
248
+ return refuse(context, {
249
+ status: 422,
250
+ code: validated.reasons[0]?.code ?? "invalid_request",
251
+ message: "This order request could not be read.",
252
+ reasons: validated.reasons,
253
+ }, "review-refused");
254
+ }
255
+
256
+ let catalog: ProposalCatalog;
257
+ try {
258
+ catalog = await proposalCatalog(context, tenant);
259
+ } catch {
260
+ return refuse(context, { status: 503, code: "cart_unavailable", message: CART_UNAVAILABLE_MESSAGE }, "review-refused");
261
+ }
262
+
263
+ let requested: ProposalRequestLine[];
264
+ let sourceText: string[] | null = null;
265
+ let unmatched: Array<{ reason: CartProposalReason; text: string }> = [];
266
+ if (validated.request.assistant === "list-text") {
267
+ const matched = matchList(validated.request.text, catalogEntries(catalog));
268
+ if (!matched.ok) {
269
+ return refuse(context, { status: 422, code: matched.reason, message: "This list could not be read." }, "review-refused");
270
+ }
271
+ requested = matched.matched.map((line) => ({ variantId: line.variantId, quantity: line.quantity }));
272
+ sourceText = matched.matched.map((line) => matched.lineTexts[line.source] ?? "");
273
+ unmatched = matched.unmatched.map((line) => ({ reason: line.reason, text: line.text }));
274
+ } else {
275
+ requested = validated.request.lines;
276
+ }
277
+
278
+ const resolved = await resolveProposalLines(requested, catalog);
279
+ const refused = resolved.refused.map((item) => ({
280
+ index: item.index,
281
+ reason: item.reason,
282
+ ...(sourceText ? { text: sourceText[item.index] ?? "" } : {}),
283
+ }));
284
+ const issuedAt = (deps.now ?? (() => Math.floor(Date.now() / 1000)))();
285
+ const proposal = resolved.lines.length > 0
286
+ ? {
287
+ id: await encodeProposalId({
288
+ tenant: tenant.tot_data_scope,
289
+ issuedAt,
290
+ lines: resolved.lines.map((line) => ({ variantId: line.variantId, quantity: line.quantity })),
291
+ }, proposalIdKey(signing.secret)),
292
+ digest: resolved.digest,
293
+ issuedAt,
294
+ expiresAt: issuedAt + CART_PROPOSAL_TTL_SECONDS,
295
+ currency: tenant.currency,
296
+ total: total(resolved.lines),
297
+ lines: resolved.lines,
298
+ }
299
+ : null;
300
+
301
+ let compliance: ProposalCompliance | null = null;
302
+ if (proposal && deps.preflight) {
303
+ try {
304
+ compliance = await deps.preflight(context, proposal.lines);
305
+ } catch {
306
+ compliance = null;
307
+ }
308
+ }
309
+
310
+ logProposal(context, "reviewed", {
311
+ assistant: validated.request.assistant,
312
+ lines: resolved.lines.length,
313
+ refused: resolved.refused.length,
314
+ unmatched: unmatched.length,
315
+ });
316
+
317
+ const status = proposal ? 200 : 422;
318
+ if (wantsJson(context.request)) {
319
+ return jsonReply({ proposal, refused, unmatched, compliance, confirmable: proposal !== null }, status);
320
+ }
321
+ const prefix = basePrefix(context);
322
+ const view: ReviewView = {
323
+ confirmAction: `${prefix}${CART_PROPOSAL_CONFIRM_PATH}`,
324
+ reviewAction: `${prefix}${CART_PROPOSAL_REVIEW_PATH}`,
325
+ proposal,
326
+ refused,
327
+ unmatched,
328
+ compliance,
329
+ };
330
+ return htmlReply(renderReview(view), status);
331
+ }
332
+
333
+ /** POST: hand a reviewed proposal into the signed cart. Takes only `{proposalId, digest}`. */
334
+ export async function cartProposalConfirm(context: APIContext, deps: ConfirmDeps): Promise<Response> {
335
+ const { tenant, commerce } = context.locals;
336
+ if (!sameOrigin(context)) {
337
+ return refuse(context, { status: 403, code: "cross_origin", message: "This request cannot be accepted." }, "confirm-refused");
338
+ }
339
+ if (!commerce) {
340
+ return refuse(context, { status: 409, code: "commerce_unavailable", message: NO_COMMERCE_MESSAGE }, "confirm-refused");
341
+ }
342
+ const signing = await proposalSigning(context, commerce, "confirm-refused");
343
+ if (signing instanceof Response) return signing;
344
+
345
+ const validated = validateConfirmRequest(await readBody(context.request));
346
+ if (!validated.ok) {
347
+ return refuse(context, {
348
+ status: 422,
349
+ code: validated.reasons[0]?.code ?? "invalid_request",
350
+ message: "This confirmation could not be read.",
351
+ reasons: validated.reasons,
352
+ }, "confirm-refused");
353
+ }
354
+ const token = await decodeProposalId(validated.proposalId, proposalIdKey(signing.secret));
355
+ if (!token) {
356
+ return refuse(context, { status: 422, code: "proposal_invalid", message: "This order review is not valid. Review your order again." }, "confirm-refused");
357
+ }
358
+ if (token.tenant !== tenant.tot_data_scope) {
359
+ return refuse(context, { status: 422, code: "proposal_tenant_mismatch", message: "This order review is not valid for this store. Review your order again." }, "confirm-refused");
360
+ }
361
+ const now = (deps.now ?? (() => Math.floor(Date.now() / 1000)))();
362
+ const age = proposalAge(token.issuedAt, now);
363
+ if (age === "invalid") {
364
+ return refuse(context, { status: 422, code: "proposal_invalid", message: "This order review is not valid. Review your order again." }, "confirm-refused");
365
+ }
366
+ if (age === "expired") {
367
+ return refuse(context, { status: 409, code: "offer_expired", message: "This order review has expired. Review your order again." }, "confirm-refused");
368
+ }
369
+
370
+ let catalog: ProposalCatalog;
371
+ try {
372
+ catalog = await proposalCatalog(context, tenant);
373
+ } catch {
374
+ return refuse(context, { status: 503, code: "cart_unavailable", message: CART_UNAVAILABLE_MESSAGE }, "confirm-refused");
375
+ }
376
+ const live = await resolveProposalLines(token.lines, catalog);
377
+ if (live.refused.length > 0 || live.lines.length !== token.lines.length || live.digest !== validated.digest) {
378
+ return refuse(context, { status: 409, code: "offer_stale", message: "Prices or availability changed. Review your order again." }, "confirm-refused");
379
+ }
380
+
381
+ const entries = new Map(catalogEntries(catalog).map((entry) => [entry.variant.id, entry]));
382
+ const publicOrigin = tenantPublicOrigin(tenant, {
383
+ requestOrigin: context.locals.requestOrigin || new URL(context.request.url).origin,
384
+ basePath: context.locals.imageBasePath || context.locals.apiBasePath || context.locals.basePath,
385
+ });
386
+ const lines: Array<Array<{ name: string; value: string }>> = [];
387
+ const codes: string[] = [];
388
+ for (const line of live.lines) {
389
+ const entry = entries.get(line.variantId);
390
+ if (!entry) {
391
+ return refuse(context, { status: 409, code: "offer_stale", message: "Prices or availability changed. Review your order again." }, "confirm-refused");
392
+ }
393
+ const payload = await buildVariantCartPayload(entry.product, entry.variant, {
394
+ mode: commerce.mode,
395
+ secret: signing.secret,
396
+ tenantId: commerceTenantId(tenant),
397
+ currency: tenant.currency,
398
+ publicOrigin,
399
+ });
400
+ const enforced = await enforceCartSubmission({
401
+ entries: [
402
+ ...payload.hidden.map((field): [string, string] => [field.name, field.value]),
403
+ [payload.quantityName, String(line.quantity)],
404
+ ],
405
+ mode: commerce.mode,
406
+ secret: signing.secret,
407
+ trustedTenantId: commerceTenantId(tenant),
408
+ });
409
+ if (!enforced.ok) {
410
+ return refuse(context, { status: 409, code: "offer_stale", message: "Prices or availability changed. Review your order again." }, "confirm-refused");
411
+ }
412
+ const productPage = new URL(deps.productPagePath(context, entry.product.handle), context.request.url).toString();
413
+ const completed = await completeCartFields(context, commerce, tenant, signing.secret, enforced.fields, {
414
+ ref: null,
415
+ returnUrl: trustedReturnUrl(context.request, tenant, productPage),
416
+ });
417
+ if (!completed) {
418
+ return refuse(context, { status: 409, code: "cart_unavailable", message: SHIPPING_UNAVAILABLE_CART_MESSAGE }, "confirm-refused");
419
+ }
420
+ const code = completed.find((field) => field.name.split("||")[0] === "code")?.value;
421
+ if (code) codes.push(code);
422
+ lines.push(completed.map((field) => ({ name: field.name, value: field.value })));
423
+ }
424
+
425
+ const added = await addProposalToBoundCart(
426
+ context,
427
+ commerce,
428
+ commerceTenantId(tenant),
429
+ { key: await proposalReplayKey(token, validated.digest), codes, lines },
430
+ (line) => signCartLine(line.fields, { mode: commerce.mode, secret: signing.secret, code: line.code }),
431
+ deps.fetch,
432
+ );
433
+ if (!added) {
434
+ return refuse(context, { status: 503, code: "cart_unavailable", message: CART_UNAVAILABLE_MESSAGE }, "confirm-refused");
435
+ }
436
+ const location = withCartSession(commerce.cartUrl, added.id);
437
+ logProposal(context, "confirmed", { lines: live.lines.length, replayed: added.replayed });
438
+ if (wantsJson(context.request)) {
439
+ return jsonReply({ location, replayed: added.replayed, lines: live.lines.length }, 200, {
440
+ "referrer-policy": CHECKOUT_NAVIGATION_REFERRER_POLICY,
441
+ });
442
+ }
443
+ return new Response(null, {
444
+ status: 303,
445
+ headers: { ...SECURITY_HEADERS, location, "referrer-policy": CHECKOUT_NAVIGATION_REFERRER_POLICY },
446
+ });
447
+ }
@@ -0,0 +1,100 @@
1
+ /**
2
+ * The review screen markup. A server-rendered page with no script: the shopper reads the
3
+ * resolved lines, the refused and unmatched lines, and the compliance status, and confirms with a
4
+ * plain form post of the proposal id and digest. Every dynamic value is escaped here.
5
+ */
6
+ import type { CartProposalLine, CartProposalReason } from "@tot/public-runtime";
7
+
8
+ export interface ReviewView {
9
+ /** Where the confirm form posts. */
10
+ confirmAction: string;
11
+ /** Where the paste form posts. */
12
+ reviewAction: string;
13
+ proposal: { id: string; digest: string; expiresAt: number; currency: string; total: number; lines: CartProposalLine[] } | null;
14
+ refused: Array<{ index: number; reason: CartProposalReason; text?: string }>;
15
+ unmatched: Array<{ reason: CartProposalReason; text: string }>;
16
+ compliance: { status: string; blocks: Array<{ code: string; message: string }> } | null;
17
+ }
18
+
19
+ export function escapeHtml(value: string): string {
20
+ return value.replace(/[&<>"']/g, (ch) => {
21
+ if (ch === "&") return "&amp;";
22
+ if (ch === "<") return "&lt;";
23
+ if (ch === ">") return "&gt;";
24
+ if (ch === '"') return "&quot;";
25
+ return "&#39;";
26
+ });
27
+ }
28
+
29
+ function money(amount: number, currency: string): string {
30
+ try {
31
+ return new Intl.NumberFormat("en-US", { style: "currency", currency }).format(amount);
32
+ } catch {
33
+ return `${amount.toFixed(2)} ${currency}`;
34
+ }
35
+ }
36
+
37
+ function page(body: string): string {
38
+ return `<!doctype html><html lang="en"><head><meta charset="utf-8">` +
39
+ `<meta name="viewport" content="width=device-width,initial-scale=1">` +
40
+ `<meta name="robots" content="noindex,nofollow"><title>Review your order</title></head>` +
41
+ `<body><main>${body}</main></body></html>`;
42
+ }
43
+
44
+ function pasteForm(action: string): string {
45
+ return `<form method="post" action="${escapeHtml(action)}" data-cart-proposal-paste>` +
46
+ `<input type="hidden" name="assistant" value="list-text">` +
47
+ `<label for="proposal-text">Paste your list, one item per line (for example: 10 x Product Flavor)</label>` +
48
+ `<textarea id="proposal-text" name="text" rows="6" maxlength="4000" required></textarea>` +
49
+ `<button type="submit">Review order</button></form>`;
50
+ }
51
+
52
+ /** The paste form alone. */
53
+ export function renderPasteForm(reviewAction: string): string {
54
+ return page(`<h1>Order from a list</h1>${pasteForm(reviewAction)}`);
55
+ }
56
+
57
+ export function renderReview(view: ReviewView): string {
58
+ const parts: string[] = ["<h1>Review your order</h1>",
59
+ `<p data-payment-authorized="false">Nothing is charged or submitted here. Confirming adds these items to your cart.</p>`];
60
+
61
+ if (view.proposal) {
62
+ const { proposal } = view;
63
+ const rows = proposal.lines.map((line) =>
64
+ `<tr data-variant-id="${escapeHtml(line.variantId)}"><td>${escapeHtml(line.productTitle)}` +
65
+ `${line.variantTitle && line.variantTitle !== line.productTitle ? ` — ${escapeHtml(line.variantTitle)}` : ""}</td>` +
66
+ `<td>${line.quantity}</td><td>${escapeHtml(money(line.unitPrice, line.currency))}</td>` +
67
+ `<td>${escapeHtml(money(line.lineTotal, line.currency))}</td><td>In stock</td></tr>`).join("");
68
+ parts.push(
69
+ `<table data-cart-proposal-lines><thead><tr><th>Item</th><th>Quantity</th><th>Price</th><th>Line total</th><th>Availability</th></tr></thead>` +
70
+ `<tbody>${rows}</tbody></table>`,
71
+ `<p data-cart-proposal-total>Total: ${escapeHtml(money(proposal.total, proposal.currency))}</p>`);
72
+ }
73
+
74
+ if (view.refused.length > 0) {
75
+ parts.push(`<section data-cart-proposal-refused><h2>Not added</h2><ul>${view.refused.map((item) =>
76
+ `<li data-reason="${escapeHtml(item.reason)}">${item.text ? `${escapeHtml(item.text)}: ` : ""}${escapeHtml(item.reason)}</li>`).join("")}</ul></section>`);
77
+ }
78
+ if (view.unmatched.length > 0) {
79
+ parts.push(`<section data-cart-proposal-unmatched><h2>Not matched</h2><ul>${view.unmatched.map((item) =>
80
+ `<li data-reason="${escapeHtml(item.reason)}">${escapeHtml(item.text)}: ${escapeHtml(item.reason)}</li>`).join("")}</ul></section>`);
81
+ }
82
+ if (view.compliance) {
83
+ parts.push(`<section data-cart-proposal-compliance data-status="${escapeHtml(view.compliance.status)}"><h2>Checkout requirements</h2>` +
84
+ `<p>${escapeHtml(view.compliance.status)}</p>` +
85
+ `${view.compliance.blocks.length ? `<ul>${view.compliance.blocks.map((block) =>
86
+ `<li data-code="${escapeHtml(block.code)}">${escapeHtml(block.message)}</li>`).join("")}</ul>` : ""}</section>`);
87
+ }
88
+ if (view.proposal) {
89
+ parts.push(`<form method="post" action="${escapeHtml(view.confirmAction)}" data-cart-proposal-confirm>` +
90
+ `<input type="hidden" name="proposalId" value="${escapeHtml(view.proposal.id)}">` +
91
+ `<input type="hidden" name="digest" value="${escapeHtml(view.proposal.digest)}">` +
92
+ `<button type="submit">Confirm and add to cart</button></form>`);
93
+ }
94
+ parts.push(pasteForm(view.reviewAction));
95
+ return page(parts.join(""));
96
+ }
97
+
98
+ export function renderRefusal(code: CartProposalReason, message: string): string {
99
+ return page(`<h1>Order review</h1><p data-cart-proposal-refusal="${escapeHtml(code)}" data-payment-authorized="false">${escapeHtml(message)}</p>`);
100
+ }
@@ -257,21 +257,38 @@ export function verifiedRefKey(preflightUrl: string): string {
257
257
  return `tot:verified-ref:${preflightUrl}`;
258
258
  }
259
259
 
260
- export function readStoredRef(key: string): string | null {
260
+ function isStoreWideVerifiedKey(key: string): boolean {
261
+ return key.startsWith("tot:verified-ref:");
262
+ }
263
+
264
+ function readFromStorage(get: () => Storage, key: string): string | null {
261
265
  try {
262
- const v = sessionStorage.getItem(key);
266
+ const v = get().getItem(key);
263
267
  return v && v.trim() ? v : null;
264
268
  } catch {
265
269
  return null;
266
270
  }
267
271
  }
268
272
 
273
+ export function readStoredRef(key: string): string | null {
274
+ const fromSession = readFromStorage(() => sessionStorage, key);
275
+ if (fromSession) return fromSession;
276
+ return isStoreWideVerifiedKey(key) ? readFromStorage(() => localStorage, key) : null;
277
+ }
278
+
269
279
  export function writeStoredRef(key: string, ref: string): void {
270
280
  try {
271
281
  sessionStorage.setItem(key, ref);
272
282
  } catch {
273
283
  /* storage disabled — the flow still works, it just can't survive a reload */
274
284
  }
285
+ if (isStoreWideVerifiedKey(key)) {
286
+ try {
287
+ localStorage.setItem(key, ref);
288
+ } catch {
289
+ /* storage disabled */
290
+ }
291
+ }
275
292
  }
276
293
 
277
294
  export function clearStoredRef(key: string): void {
@@ -280,4 +297,11 @@ export function clearStoredRef(key: string): void {
280
297
  } catch {
281
298
  /* storage disabled */
282
299
  }
300
+ if (isStoreWideVerifiedKey(key)) {
301
+ try {
302
+ localStorage.removeItem(key);
303
+ } catch {
304
+ /* storage disabled */
305
+ }
306
+ }
283
307
  }
@@ -1,11 +1,27 @@
1
- /** Content redirects for ordinary preview/local renders, bound to the page's selected provider. */
2
- import { buildRedirectSet, COLLECTION_REDIRECTS_PATH, declaredRedirectsFromContent, resolveRedirect } from "@tot/public-runtime/publication-redirects";
1
+ /**
2
+ * Content redirects for ordinary preview/local renders, bound to the page's selected provider.
3
+ * `exact` says an exact entry answered rather than a `<dir>/*` rule: a route the release generates
4
+ * wins over an exact entry for its own path, so the caller renders first and redirects only when
5
+ * nothing renders there.
6
+ */
7
+ import {
8
+ buildRedirectSet,
9
+ COLLECTION_REDIRECTS_PATH,
10
+ declaredRedirectsFromContent,
11
+ isRedirectRule,
12
+ resolveRedirect,
13
+ } from "@tot/public-runtime/publication-redirects";
3
14
  import type { ContentProvider } from "../storyblok/provider.js";
4
15
 
16
+ export interface ContentRedirectMatch {
17
+ location: string;
18
+ exact: boolean;
19
+ }
20
+
5
21
  export async function contentRedirectLocation(
6
22
  content: Pick<ContentProvider, "readArtifact" | "listArtifactPaths">,
7
23
  requestPath: string,
8
- ): Promise<string | null> {
24
+ ): Promise<ContentRedirectMatch | null> {
9
25
  try {
10
26
  const paths = await content.listArtifactPaths();
11
27
  const declarations = ["redirects.json", ...(paths ?? []).filter((path) => COLLECTION_REDIRECTS_PATH.test(`content/${path}`))];
@@ -14,7 +30,8 @@ export async function contentRedirectLocation(
14
30
  return raw === null ? null : { path: `content/${relative}`, json: JSON.parse(raw) as unknown };
15
31
  }));
16
32
  const set = buildRedirectSet(declaredRedirectsFromContent(entries.filter((entry) => entry !== null)));
17
- return set.ok ? resolveRedirect(set.redirects, requestPath)?.location ?? null : null;
33
+ const match = set.ok ? resolveRedirect(set.redirects, requestPath) : null;
34
+ return match ? { location: match.location, exact: !isRedirectRule(match.from) } : null;
18
35
  } catch {
19
36
  // An unreadable/invalid map must never produce an unsafe or partial redirect set.
20
37
  return null;
@@ -39,9 +39,12 @@ const DEFAULT_SWR = 86_400;
39
39
  export function isCacheablePath(pathname: string): boolean {
40
40
  if (pathname.startsWith("/api/")) return false;
41
41
  // Authenticated operator surfaces are per-viewer and MUST NOT be edge-cached —
42
- // the bare `/dashboard` index is a single-segment slug that would otherwise
43
- // match the editorial-page rule below and be served across viewers.
42
+ // the bare `/dashboard` and `/admin` indexes are single-segment slugs that would
43
+ // otherwise match the editorial-page rule below and be served across viewers.
44
44
  if (pathname === "/dashboard" || pathname.startsWith("/dashboard/")) return false;
45
+ if (pathname === "/admin" || pathname.startsWith("/admin/")) return false;
46
+ if (pathname === "/auth" || pathname.startsWith("/auth/")) return false;
47
+ if (pathname === "/preview" || pathname.startsWith("/preview/")) return false;
45
48
  // `/cockpit` (formerly `/dev`) is the authenticated developer surface — per-viewer
46
49
  // (it renders the signed-in developer's own store, email, and gated demo), so like
47
50
  // /dashboard it must never be shared across viewers. It's also the loudest failure