@tokenoftrust/storefront-runner 7.3.2 → 7.5.1

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 (420) 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 +32 -8
  13. package/apps/storefront/src/lib/access/auth/brokerAssertion.ts +16 -2
  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/dashboard/staffAdmission.ts +5 -0
  17. package/apps/storefront/src/lib/access/dashboard/tenantSelection.ts +2 -0
  18. package/apps/storefront/src/lib/access/shared/capability.ts +14 -6
  19. package/apps/storefront/src/lib/access/shared/generated/capabilityCatalog.generated.ts +161 -0
  20. package/apps/storefront/src/lib/activity/activityScope.ts +36 -0
  21. package/apps/storefront/src/lib/activity/recordActivity.ts +23 -1
  22. package/apps/storefront/src/lib/activity/serverFanOut.ts +31 -0
  23. package/apps/storefront/src/lib/activity/store.ts +9 -3
  24. package/apps/storefront/src/lib/checkout/agent/checkoutProtocol.ts +196 -0
  25. package/apps/storefront/src/lib/checkout/agent/checkoutSession.ts +296 -0
  26. package/apps/storefront/src/lib/checkout/agent/webBotAuth.ts +347 -0
  27. package/apps/storefront/src/lib/checkout/commerce/cardCartForm.ts +2 -0
  28. package/apps/storefront/src/lib/checkout/commerce/cartSession.ts +109 -12
  29. package/apps/storefront/src/lib/checkout/commerce/checkoutHandoffRoute.ts +53 -25
  30. package/apps/storefront/src/lib/checkout/commerce/finalCartAuthorization.ts +48 -6
  31. package/apps/storefront/src/lib/checkout/proposal/cartProposal.ts +388 -0
  32. package/apps/storefront/src/lib/checkout/proposal/listMatcher.ts +149 -0
  33. package/apps/storefront/src/lib/checkout/proposal/proposalRoutes.ts +522 -0
  34. package/apps/storefront/src/lib/checkout/proposal/reviewHtml.ts +100 -0
  35. package/apps/storefront/src/lib/compliance/browser/checkoutVerificationFlow.ts +26 -2
  36. package/apps/storefront/src/lib/content/shared/redirects.ts +21 -4
  37. package/apps/storefront/src/lib/publication/shared/edgeCache.ts +5 -2
  38. package/apps/storefront/src/lib/publication/shared/previewAnnotations/renderDecorator.ts +15 -8
  39. package/apps/storefront/src/lib/publication/shared/runtimeEnv.ts +1 -1
  40. package/apps/storefront/src/middleware/controlPlane.ts +15 -1
  41. package/apps/storefront/src/middleware/index.ts +7 -3
  42. package/apps/storefront/src/middleware/renderChain.ts +46 -33
  43. package/apps/storefront/src/pages/api/cart-proposal/confirm.ts +12 -0
  44. package/apps/storefront/src/pages/api/cart-proposal/review.ts +26 -0
  45. package/apps/storefront/src/pages/api/commerce/checkout-sessions/[id].ts +9 -0
  46. package/apps/storefront/src/pages/api/commerce/checkout-sessions.ts +8 -0
  47. package/apps/storefront/src/pages/api/commerce/final-cart-authorization.ts +29 -6
  48. package/apps/storefront/src/pages/api/compliance/preflight.ts +25 -1
  49. package/apps/storefront/src/pages/products/[handle].astro +2 -15
  50. package/apps/storefront/tsconfig.astro.json +11 -0
  51. package/package.json +1 -1
  52. package/packages/public-runtime/src/activity/README.md +12 -0
  53. package/packages/public-runtime/src/activity/catalog.ts +7 -0
  54. package/packages/public-runtime/src/activity/event.ts +19 -0
  55. package/packages/public-runtime/src/activity/redaction.ts +31 -2
  56. package/packages/public-runtime/src/catalog-files.ts +3 -2
  57. package/packages/public-runtime/src/checkout-orders.ts +18 -19
  58. package/packages/public-runtime/src/checkout.ts +70 -0
  59. package/packages/public-runtime/src/compliance/evaluate.ts +60 -1
  60. package/packages/public-runtime/src/compliance/index.ts +1 -1
  61. package/packages/public-runtime/src/compliance/pact-report.ts +184 -3
  62. package/packages/public-runtime/src/compliance/profile.ts +268 -20
  63. package/packages/public-runtime/src/compliance/ruleset.ts +42 -0
  64. package/packages/public-runtime/src/customization-runtime.ts +1 -1
  65. package/packages/public-runtime/src/product.ts +9 -1
  66. package/packages/public-runtime/src/publication-content-redirects.ts +16 -3
  67. package/packages/public-runtime/tests/fixtures/compliance-decisions.golden.json +252 -52
  68. package/pnpm-lock.runner.yaml +0 -15
  69. package/scripts/tenant/materialize-tenant-content.mjs +3 -0
  70. package/scripts/tenant/validate.mjs +128 -0
  71. package/apps/storefront/dev-plugins/dev-publish.mjs +0 -55
  72. package/apps/storefront/drizzle.config.apps.ts +0 -13
  73. package/apps/storefront/integrations/preview-annotations-client-bundle.mjs +0 -80
  74. package/apps/storefront/migrations-apps/0000_fast_millenium_guard.sql +0 -129
  75. package/apps/storefront/migrations-apps/0001_woozy_lyja.sql +0 -22
  76. package/apps/storefront/migrations-apps/0002_good_switch.sql +0 -26
  77. package/apps/storefront/migrations-apps/0003_mute_marauders.sql +0 -12
  78. package/apps/storefront/migrations-apps/0004_deep_morph.sql +0 -36
  79. package/apps/storefront/migrations-apps/0005_common_mystique.sql +0 -23
  80. package/apps/storefront/migrations-apps/0006_broad_microchip.sql +0 -16
  81. package/apps/storefront/migrations-apps/0007_brave_outlaw_kid.sql +0 -15
  82. package/apps/storefront/migrations-apps/0008_blue_dazzler.sql +0 -11
  83. package/apps/storefront/migrations-apps/0009_bored_shinobi_shaw.sql +0 -15
  84. package/apps/storefront/migrations-apps/0010_ws4_verified_provider_measurement.sql +0 -35
  85. package/apps/storefront/migrations-apps/0011_dt_tracking_tenant_databases.sql +0 -23
  86. package/apps/storefront/migrations-apps/0012_test_destinations.sql +0 -29
  87. package/apps/storefront/migrations-apps/0013_publication_space_editorial.sql +0 -64
  88. package/apps/storefront/migrations-apps/0014_retire_candidate_ledger.sql +0 -12
  89. package/apps/storefront/migrations-apps/0015_merchant_calculation_settings.sql +0 -31
  90. package/apps/storefront/migrations-apps/0016_scrappy_commerce_contract.sql +0 -166
  91. package/apps/storefront/migrations-apps/0017_commerce_durable_projection.sql +0 -28
  92. package/apps/storefront/migrations-apps/0018_commerce_provider_cart_identity.sql +0 -13
  93. package/apps/storefront/migrations-apps/0019_commerce_source_authority.sql +0 -23
  94. package/apps/storefront/migrations-apps/0020_contact_messages.sql +0 -18
  95. package/apps/storefront/migrations-apps/0021_contact_vault.sql +0 -166
  96. package/apps/storefront/migrations-apps/0022_contact_vault_fields.sql +0 -342
  97. package/apps/storefront/migrations-apps/0023_principal_grant_contacts.sql +0 -15
  98. package/apps/storefront/migrations-apps/0024_order_contact_erasure_state.sql +0 -22
  99. package/apps/storefront/migrations-apps/0025_shipment_audit_order_lookup.sql +0 -2
  100. package/apps/storefront/migrations-apps/0026_fulfillment_assignment.sql +0 -44
  101. package/apps/storefront/migrations-apps/0027_app_contact_authority.sql +0 -70
  102. package/apps/storefront/migrations-apps/0028_app_jwk_and_candidates.sql +0 -133
  103. package/apps/storefront/migrations-apps/0029_inventory_locations_wms.sql +0 -38
  104. package/apps/storefront/migrations-apps/0030_assignment_split_shipments.sql +0 -149
  105. package/apps/storefront/migrations-apps/meta/0000_snapshot.json +0 -843
  106. package/apps/storefront/migrations-apps/meta/0001_snapshot.json +0 -990
  107. package/apps/storefront/migrations-apps/meta/0002_snapshot.json +0 -1160
  108. package/apps/storefront/migrations-apps/meta/0003_snapshot.json +0 -1235
  109. package/apps/storefront/migrations-apps/meta/0004_snapshot.json +0 -1474
  110. package/apps/storefront/migrations-apps/meta/0005_snapshot.json +0 -1617
  111. package/apps/storefront/migrations-apps/meta/0006_snapshot.json +0 -1716
  112. package/apps/storefront/migrations-apps/meta/0007_snapshot.json +0 -1812
  113. package/apps/storefront/migrations-apps/meta/0008_snapshot.json +0 -1881
  114. package/apps/storefront/migrations-apps/meta/0009_snapshot.json +0 -1979
  115. package/apps/storefront/migrations-apps/meta/_journal.json +0 -76
  116. package/apps/storefront/perf/README.md +0 -64
  117. package/apps/storefront/perf/assert-budgets.ts +0 -159
  118. package/apps/storefront/platform-reconcile-tenants.json +0 -3
  119. package/apps/storefront/playwright.config.ts +0 -23
  120. package/apps/storefront/public/js/dashboard-access-banner.js +0 -53
  121. package/apps/storefront/public/js/dashboard-apps.js +0 -183
  122. package/apps/storefront/public/js/dashboard-contact-capture.js +0 -52
  123. package/apps/storefront/public/js/dashboard-delegate.js +0 -167
  124. package/apps/storefront/public/js/dashboard-team.js +0 -356
  125. package/apps/storefront/public/js/dashboard-vendor-search.js +0 -115
  126. package/apps/storefront/src/components/content/storefront/AsyncStylesheet.astro +0 -26
  127. package/apps/storefront/src/components/integrations/storefront/WidgetFrame.astro +0 -34
  128. package/apps/storefront/src/config/adminTenantLookup.ts +0 -35
  129. package/apps/storefront/src/config/evidenceTenantRoster.ts +0 -25
  130. package/apps/storefront/src/config/staffProvisionProjection.ts +0 -24
  131. package/apps/storefront/src/config/storeName.ts +0 -34
  132. package/apps/storefront/src/lib/access/admin/README.md +0 -122
  133. package/apps/storefront/src/lib/access/admin/adminShell.ts +0 -281
  134. package/apps/storefront/src/lib/access/admin/envelope.ts +0 -9
  135. package/apps/storefront/src/lib/access/admin/viewmodels/settings.ts +0 -64
  136. package/apps/storefront/src/lib/access/auth/adminApiGuard.ts +0 -66
  137. package/apps/storefront/src/lib/access/auth/adminEntry.ts +0 -126
  138. package/apps/storefront/src/lib/access/auth/mcpClientAssertion.ts +0 -217
  139. package/apps/storefront/src/lib/access/auth/operatorSession.ts +0 -120
  140. package/apps/storefront/src/lib/access/dashboard/agentStoreEntry.ts +0 -253
  141. package/apps/storefront/src/lib/access/dashboard/delegateGate.ts +0 -130
  142. package/apps/storefront/src/lib/access/dashboard/staffStoreEntry.ts +0 -153
  143. package/apps/storefront/src/lib/access/dashboard/staffVendorAccess.ts +0 -474
  144. package/apps/storefront/src/lib/access/dashboard/vendorQuery.ts +0 -61
  145. package/apps/storefront/src/lib/access/fixtures/settings.ts +0 -67
  146. package/apps/storefront/src/lib/access/fixtures/tenants.ts +0 -29
  147. package/apps/storefront/src/lib/access/notifications/magicLinkInviteEmail.ts +0 -62
  148. package/apps/storefront/src/lib/access/shared/grantContactLookup.ts +0 -97
  149. package/apps/storefront/src/lib/access/shared/principalGrants.ts +0 -775
  150. package/apps/storefront/src/lib/activity/alerts.ts +0 -426
  151. package/apps/storefront/src/lib/activity/candidateSubmitLease.ts +0 -87
  152. package/apps/storefront/src/lib/activity/changeActorAttribution.ts +0 -181
  153. package/apps/storefront/src/lib/activity/evidence/evidenceReference.ts +0 -32
  154. package/apps/storefront/src/lib/activity/fixtures/evidence.ts +0 -99
  155. package/apps/storefront/src/lib/activity/query.ts +0 -403
  156. package/apps/storefront/src/lib/activity/uiActor.ts +0 -152
  157. package/apps/storefront/src/lib/admin/services/mock/index.ts +0 -12
  158. package/apps/storefront/src/lib/assets/addons/catalog.ts +0 -60
  159. package/apps/storefront/src/lib/assets/addons/storeEntitlements.ts +0 -260
  160. package/apps/storefront/src/lib/assets/durableAssetsRoute.ts +0 -65
  161. package/apps/storefront/src/lib/assets/durableR2.ts +0 -473
  162. package/apps/storefront/src/lib/assets/durableR2Bindings.ts +0 -33
  163. package/apps/storefront/src/lib/automation/admin/viewmodels/aiWorkflows.ts +0 -65
  164. package/apps/storefront/src/lib/automation/ai/approvalMode.ts +0 -20
  165. package/apps/storefront/src/lib/automation/ai/askEnvelope.ts +0 -47
  166. package/apps/storefront/src/lib/automation/ai/audit.ts +0 -12
  167. package/apps/storefront/src/lib/automation/ai/operationalRuns.ts +0 -155
  168. package/apps/storefront/src/lib/automation/ai/recommendation.ts +0 -20
  169. package/apps/storefront/src/lib/automation/fixtures/aiWorkflows.ts +0 -59
  170. package/apps/storefront/src/lib/catalog/admin/catalogSettingsClient.ts +0 -250
  171. package/apps/storefront/src/lib/catalog/admin/catalogSettingsFields.ts +0 -134
  172. package/apps/storefront/src/lib/catalog/admin/catalogSettingsPreview.ts +0 -37
  173. package/apps/storefront/src/lib/catalog/admin/catalogSettingsPricingView.ts +0 -39
  174. package/apps/storefront/src/lib/catalog/admin/catalogSettingsRuleView.ts +0 -44
  175. package/apps/storefront/src/lib/catalog/admin/catalogSettingsSkuView.ts +0 -21
  176. package/apps/storefront/src/lib/catalog/admin/catalogSettingsState.ts +0 -132
  177. package/apps/storefront/src/lib/catalog/admin/productSetupPhoto.ts +0 -23
  178. package/apps/storefront/src/lib/catalog/admin/productsTabClient.ts +0 -193
  179. package/apps/storefront/src/lib/catalog/admin/services/catalogProducts.ts +0 -32
  180. package/apps/storefront/src/lib/catalog/admin/viewmodels/catalogProducts.ts +0 -164
  181. package/apps/storefront/src/lib/catalog/admin/viewmodels/products.ts +0 -267
  182. package/apps/storefront/src/lib/catalog/fixtures/products.ts +0 -105
  183. package/apps/storefront/src/lib/catalog/tot/syncState.ts +0 -111
  184. package/apps/storefront/src/lib/checkout/admin/checkoutStyleInput.ts +0 -172
  185. package/apps/storefront/src/lib/checkout/admin/checkoutStyleTarget.ts +0 -65
  186. package/apps/storefront/src/lib/checkout/browser/checkoutExciseForm.ts +0 -152
  187. package/apps/storefront/src/lib/checkout/browser/checkoutRequirementsForm.ts +0 -72
  188. package/apps/storefront/src/lib/checkout/browser/checkoutStyleForm.ts +0 -110
  189. package/apps/storefront/src/lib/checkout/browser/settingDraftActions.ts +0 -367
  190. package/apps/storefront/src/lib/checkout/commerce/checkoutSettings.ts +0 -246
  191. package/apps/storefront/src/lib/checkout/fixtures/checkoutSettings.ts +0 -77
  192. package/apps/storefront/src/lib/content/blog/markdown.ts +0 -174
  193. package/apps/storefront/src/lib/content/chrome/examples/tokenoftrust.chrome-assignments.example.json +0 -6
  194. package/apps/storefront/src/lib/content/chrome/examples/tokenoftrust.chrome.example.json +0 -79
  195. package/apps/storefront/src/lib/content/index.ts +0 -27
  196. package/apps/storefront/src/lib/content/the-build/readingTime.ts +0 -35
  197. package/apps/storefront/src/lib/content/the-build/toc.ts +0 -95
  198. package/apps/storefront/src/lib/customers/admin/viewmodels/customers.ts +0 -56
  199. package/apps/storefront/src/lib/customers/contactVault/blindIndex.ts +0 -28
  200. package/apps/storefront/src/lib/customers/contactVault/contactAudit.ts +0 -149
  201. package/apps/storefront/src/lib/customers/contactVault/dataKeys.ts +0 -283
  202. package/apps/storefront/src/lib/customers/contactVault/fieldEnvelope.ts +0 -88
  203. package/apps/storefront/src/lib/customers/contactVault/isolateMetrics.ts +0 -37
  204. package/apps/storefront/src/lib/customers/contactVault/kms.ts +0 -292
  205. package/apps/storefront/src/lib/customers/contactVault/retention.ts +0 -302
  206. package/apps/storefront/src/lib/customers/contactVault/retentionPolicy.ts +0 -290
  207. package/apps/storefront/src/lib/customers/contactVault/zip3.ts +0 -24
  208. package/apps/storefront/src/lib/customers/fixtures/customers.ts +0 -86
  209. package/apps/storefront/src/lib/developer-experience/admin/memoizeByEnvelope.ts +0 -27
  210. package/apps/storefront/src/lib/developer-experience/admin/seed.ts +0 -54
  211. package/apps/storefront/src/lib/developer-experience/dev/activityIngestToken.ts +0 -85
  212. package/apps/storefront/src/lib/developer-experience/dev/activityStore.ts +0 -82
  213. package/apps/storefront/src/lib/developer-experience/dev/agentGrantAttestation.ts +0 -74
  214. package/apps/storefront/src/lib/developer-experience/dev/ai-widget-client.js +0 -308
  215. package/apps/storefront/src/lib/developer-experience/dev/apiBase.ts +0 -17
  216. package/apps/storefront/src/lib/developer-experience/dev/cliSignInCode.ts +0 -124
  217. package/apps/storefront/src/lib/developer-experience/dev/cockpit/ask.ts +0 -49
  218. package/apps/storefront/src/lib/developer-experience/dev/cockpit/clickToSource.ts +0 -71
  219. package/apps/storefront/src/lib/developer-experience/dev/cockpit/copyCommand.ts +0 -227
  220. package/apps/storefront/src/lib/developer-experience/dev/cockpit/files.ts +0 -249
  221. package/apps/storefront/src/lib/developer-experience/dev/cockpit/hostedActivity.ts +0 -500
  222. package/apps/storefront/src/lib/developer-experience/dev/cockpit/infoPopover.ts +0 -12
  223. package/apps/storefront/src/lib/developer-experience/dev/cockpit/mcpCopy.ts +0 -34
  224. package/apps/storefront/src/lib/developer-experience/dev/cockpit/monitor.ts +0 -107
  225. package/apps/storefront/src/lib/developer-experience/dev/cockpit/stepper.ts +0 -116
  226. package/apps/storefront/src/lib/developer-experience/dev/cockpit/themeToggle.ts +0 -23
  227. package/apps/storefront/src/lib/developer-experience/dev/livePreview.ts +0 -77
  228. package/apps/storefront/src/lib/developer-experience/dev/obstacleStore.ts +0 -214
  229. package/apps/storefront/src/lib/developer-experience/dev/previewStatus.ts +0 -87
  230. package/apps/storefront/src/lib/developer-experience/dev/rendezvousBroker.ts +0 -226
  231. package/apps/storefront/src/lib/developer-experience/dev/runtimeStore.ts +0 -291
  232. package/apps/storefront/src/lib/developer-experience/dev/storeStatus.ts +0 -142
  233. package/apps/storefront/src/lib/developer-experience/dev/subjectReissue.ts +0 -67
  234. package/apps/storefront/src/lib/developer-experience/fixtures/regulated-commerce-truth/index.ts +0 -540
  235. package/apps/storefront/src/lib/developer-experience/fixtures/ws3-readonly-clone-preflight/index.ts +0 -495
  236. package/apps/storefront/src/lib/engagement/contact/contactMessages.ts +0 -671
  237. package/apps/storefront/src/lib/engagement/contact/messagesTabClient.ts +0 -175
  238. package/apps/storefront/src/lib/engagement/contact/submission.ts +0 -112
  239. package/apps/storefront/src/lib/engagement/messaging/messagesClient.ts +0 -149
  240. package/apps/storefront/src/lib/engagement/newsletter/digest.ts +0 -117
  241. package/apps/storefront/src/lib/engagement/newsletter/resendClient.ts +0 -79
  242. package/apps/storefront/src/lib/engagement/newsletter/send.ts +0 -265
  243. package/apps/storefront/src/lib/engagement/social/golive.ts +0 -212
  244. package/apps/storefront/src/lib/engagement/social/notify.ts +0 -32
  245. package/apps/storefront/src/lib/engagement/social/tokenStore.ts +0 -171
  246. package/apps/storefront/src/lib/fulfillment/admin/commerceDesk.ts +0 -180
  247. package/apps/storefront/src/lib/fulfillment/admin/commerceDeskRouting.ts +0 -45
  248. package/apps/storefront/src/lib/fulfillment/admin/viewmodels/fulfillment.ts +0 -1071
  249. package/apps/storefront/src/lib/fulfillment/appShipmentEvidence.ts +0 -271
  250. package/apps/storefront/src/lib/fulfillment/carrierEvidence.ts +0 -105
  251. package/apps/storefront/src/lib/fulfillment/commerceProjection.ts +0 -157
  252. package/apps/storefront/src/lib/fulfillment/commerceReadback.ts +0 -60
  253. package/apps/storefront/src/lib/fulfillment/commerceRecovery.ts +0 -84
  254. package/apps/storefront/src/lib/fulfillment/commerceRuntime.ts +0 -41
  255. package/apps/storefront/src/lib/fulfillment/fulfillmentService.ts +0 -2842
  256. package/apps/storefront/src/lib/fulfillment/readiness.ts +0 -217
  257. package/apps/storefront/src/lib/fulfillment/splitShipments.ts +0 -388
  258. package/apps/storefront/src/lib/fulfillment/syntheticPreviewOrders.ts +0 -292
  259. package/apps/storefront/src/lib/integrations/apps/appContactAuthority.ts +0 -27
  260. package/apps/storefront/src/lib/integrations/apps/appContactConsents.ts +0 -118
  261. package/apps/storefront/src/lib/integrations/apps/appInstallEnv.ts +0 -28
  262. package/apps/storefront/src/lib/integrations/apps/gtmMigrationDraft.ts +0 -103
  263. package/apps/storefront/src/lib/integrations/apps/inventoryWrite.ts +0 -906
  264. package/apps/storefront/src/lib/integrations/apps/orders/customerHash.ts +0 -28
  265. package/apps/storefront/src/lib/integrations/apps/orders/idempotency.ts +0 -100
  266. package/apps/storefront/src/lib/integrations/apps/reports/salesVelocityReport.ts +0 -96
  267. package/apps/storefront/src/lib/integrations/apps/routeParams.ts +0 -45
  268. package/apps/storefront/src/lib/integrations/webhooks/cloudflareQueueDispatcher.ts +0 -82
  269. package/apps/storefront/src/lib/integrations/webhooks/commercePayloads.ts +0 -159
  270. package/apps/storefront/src/lib/integrations/webhooks/deliveryEngine.ts +0 -379
  271. package/apps/storefront/src/lib/integrations/webhooks/deliveryMapper.ts +0 -34
  272. package/apps/storefront/src/lib/integrations/webhooks/deliveryStore.ts +0 -903
  273. package/apps/storefront/src/lib/integrations/webhooks/dispatcher.ts +0 -168
  274. package/apps/storefront/src/lib/integrations/webhooks/emit.ts +0 -245
  275. package/apps/storefront/src/lib/integrations/webhooks/events.ts +0 -105
  276. package/apps/storefront/src/lib/integrations/webhooks/getDispatcher.ts +0 -77
  277. package/apps/storefront/src/lib/integrations/webhooks/orderFulfilledClaim.ts +0 -75
  278. package/apps/storefront/src/lib/measurement/admin/analyticsRegionPolicy.ts +0 -151
  279. package/apps/storefront/src/lib/measurement/admin/analyticsRegionsClient.ts +0 -84
  280. package/apps/storefront/src/lib/measurement/admin/consentSettingsClient.ts +0 -113
  281. package/apps/storefront/src/lib/measurement/analytics/index.ts +0 -44
  282. package/apps/storefront/src/lib/measurement/attribution/attributionService.ts +0 -206
  283. package/apps/storefront/src/lib/measurement/attribution/orderConversionD1.ts +0 -150
  284. package/apps/storefront/src/lib/measurement/attribution/verifiedProviderMeasurement.ts +0 -118
  285. package/apps/storefront/src/lib/measurement/tracking/interactionCollector.ts +0 -205
  286. package/apps/storefront/src/lib/measurement/tracking/pruneRollup.ts +0 -260
  287. package/apps/storefront/src/lib/measurement/tracking/tenantReadAccess.ts +0 -138
  288. package/apps/storefront/src/lib/measurement/tracking-writeback/rewriteTrackingIds.ts +0 -175
  289. package/apps/storefront/src/lib/measurement/tracking-writeback/writebackCandidate.ts +0 -110
  290. package/apps/storefront/src/lib/observability/diag/capture.ts +0 -162
  291. package/apps/storefront/src/lib/observability/diag/consoleLine.ts +0 -76
  292. package/apps/storefront/src/lib/observability/diag/debugConsole.ts +0 -118
  293. package/apps/storefront/src/lib/observability/diag/debugMode.ts +0 -163
  294. package/apps/storefront/src/lib/observability/diag/debugWindow.ts +0 -111
  295. package/apps/storefront/src/lib/observability/diag/redact.ts +0 -17
  296. package/apps/storefront/src/lib/observability/diag/reference.ts +0 -148
  297. package/apps/storefront/src/lib/observability/diag/referenceStore.ts +0 -113
  298. package/apps/storefront/src/lib/observability/diag/report.ts +0 -110
  299. package/apps/storefront/src/lib/observability/diag/serverResponseTime.ts +0 -91
  300. package/apps/storefront/src/lib/observability/diag/session.ts +0 -93
  301. package/apps/storefront/src/lib/observability/monitoring/manifest.ts +0 -301
  302. package/apps/storefront/src/lib/observability/performance/lighthouseReport.ts +0 -109
  303. package/apps/storefront/src/lib/observability/performance/rumAlert.ts +0 -179
  304. package/apps/storefront/src/lib/orders/admin/orderActions.ts +0 -556
  305. package/apps/storefront/src/lib/orders/admin/orderClient.ts +0 -248
  306. package/apps/storefront/src/lib/orders/admin/orderSource.ts +0 -410
  307. package/apps/storefront/src/lib/orders/admin/services/orders.ts +0 -922
  308. package/apps/storefront/src/lib/orders/admin/viewmodels/orders.ts +0 -135
  309. package/apps/storefront/src/lib/orders/data/commerceCallerConfig.ts +0 -37
  310. package/apps/storefront/src/lib/orders/data/ledgerContractOrders.ts +0 -148
  311. package/apps/storefront/src/lib/orders/data/orderForwardReceiver.ts +0 -532
  312. package/apps/storefront/src/lib/orders/data/orderMapper.ts +0 -454
  313. package/apps/storefront/src/lib/orders/data/ordersStore.ts +0 -623
  314. package/apps/storefront/src/lib/orders/data/sourceAuthorityContract.ts +0 -380
  315. package/apps/storefront/src/lib/orders/data/sourceAuthorityStore.ts +0 -830
  316. package/apps/storefront/src/lib/orders/fixtures/orders.ts +0 -186
  317. package/apps/storefront/src/lib/orders/providers/foxyOrderClient.ts +0 -207
  318. package/apps/storefront/src/lib/orders/vault/appRecipientRead.ts +0 -222
  319. package/apps/storefront/src/lib/orders/vault/contactIntake.ts +0 -63
  320. package/apps/storefront/src/lib/orders/vault/contactRoutes.ts +0 -110
  321. package/apps/storefront/src/lib/orders/vault/kmsEnv.ts +0 -11
  322. package/apps/storefront/src/lib/orders/vault/orderContact.ts +0 -96
  323. package/apps/storefront/src/lib/orders/vault/orderContactVault.ts +0 -1427
  324. package/apps/storefront/src/lib/orders/vault/vault-test-support.ts +0 -258
  325. package/apps/storefront/src/lib/publication/d1/schema-apps.ts +0 -808
  326. package/apps/storefront/src/lib/publication/notifications/candidateConflictEmail.ts +0 -80
  327. package/apps/storefront/src/lib/publication/servingMode.ts +0 -52
  328. package/apps/storefront/src/lib/publication/shared/previewAnnotations/moduleAsset.ts +0 -65
  329. package/apps/storefront/src/lib/publication/shared/routedApiParam.ts +0 -38
  330. package/apps/storefront/src/lib/reporting/admin/viewmodels/reporting.ts +0 -34
  331. package/apps/storefront/src/lib/reporting/fixtures/reporting.ts +0 -51
  332. package/apps/storefront/src/lib/subscriptions/admin/viewmodels/subscriptions.ts +0 -106
  333. package/apps/storefront/src/lib/subscriptions/fixtures/subscriptions.ts +0 -398
  334. package/apps/storefront/src/pages/api/admin/activity-alerts.ts +0 -58
  335. package/apps/storefront/src/pages/api/admin/commerce-readiness.ts +0 -172
  336. package/apps/storefront/src/pages/api/admin/fulfillment/batches.ts +0 -59
  337. package/apps/storefront/src/pages/api/admin/fulfillment/orders/[id]/address.ts +0 -66
  338. package/apps/storefront/src/pages/api/admin/fulfillment/orders/[id].ts +0 -118
  339. package/apps/storefront/src/pages/api/admin/fulfillment/orders/contact-search.ts +0 -26
  340. package/apps/storefront/src/pages/api/admin/fulfillment/orders/contacts.ts +0 -22
  341. package/apps/storefront/src/pages/api/admin/interaction-insights.ts +0 -101
  342. package/apps/storefront/src/pages/api/admin/orders/[id].ts +0 -63
  343. package/apps/storefront/src/pages/api/admin/orders.ts +0 -65
  344. package/apps/storefront/src/pages/api/contact.ts +0 -144
  345. package/apps/storefront/src/scheduled/contactVaultSweep.ts +0 -113
  346. package/apps/storefront/src/styles/admin.css +0 -1161
  347. package/apps/storefront/test/pipeline/fake-preview-services.ts +0 -288
  348. package/apps/storefront/test/pipeline/harness.ts +0 -209
  349. package/apps/storefront/test/pipeline/intake-worker.mjs +0 -14
  350. package/apps/storefront/test/pipeline/matrix-faults.ts +0 -366
  351. package/apps/storefront/test/pipeline/pipeline-host.ts +0 -418
  352. package/apps/storefront/test/pipeline/pool-config.cjs +0 -85
  353. package/apps/storefront/test/pipeline/publish-kinds.ts +0 -279
  354. package/apps/storefront/test/pipeline/synthetic-job.ts +0 -303
  355. package/apps/storefront/test/pipeline-faults/matrix-lib.ts +0 -696
  356. package/apps/storefront/vitest.config.cts +0 -44
  357. package/apps/storefront/vitest.faults.config.cts +0 -13
  358. package/apps/storefront/vitest.workers.config.cts +0 -7
  359. package/packages/feedback/fixtures/v1/expected-findings.json +0 -16
  360. package/packages/feedback/fixtures/v1/feedback-action/invalid/carries-transport-credential.json +0 -14
  361. package/packages/feedback/fixtures/v1/feedback-action/invalid/control-char-in-description.json +0 -13
  362. package/packages/feedback/fixtures/v1/feedback-action/invalid/legacy-schema-version.json +0 -13
  363. package/packages/feedback/fixtures/v1/feedback-action/invalid/page-path-with-query.json +0 -14
  364. package/packages/feedback/fixtures/v1/feedback-action/invalid/title-too-short.json +0 -13
  365. package/packages/feedback/fixtures/v1/feedback-action/valid/element-problem.json +0 -33
  366. package/packages/feedback/fixtures/v1/feedback-action/valid/page-comment.json +0 -20
  367. package/packages/feedback/fixtures/v1/feedback-action/valid/region-improvement.json +0 -24
  368. package/packages/feedback/fixtures/v1/feedback-action/valid/text-selection-feature.json +0 -30
  369. package/packages/feedback/fixtures/v1/submission-receipt/invalid/accepted-at-not-utc.json +0 -9
  370. package/packages/feedback/fixtures/v1/submission-receipt/invalid/bad-feedback-id.json +0 -9
  371. package/packages/feedback/fixtures/v1/submission-receipt/invalid/legacy-contract-version.json +0 -9
  372. package/packages/feedback/fixtures/v1/submission-receipt/invalid/missing-replayed.json +0 -8
  373. package/packages/feedback/fixtures/v1/submission-receipt/valid/accepted.json +0 -9
  374. package/packages/feedback/fixtures/v1/submission-receipt/valid/fractional-seconds.json +0 -9
  375. package/packages/feedback/fixtures/v1/submission-receipt/valid/replayed.json +0 -9
  376. package/packages/feedback/fixtures/v1/target-evidence/invalid/page-kind-claims-structure.json +0 -6
  377. package/packages/feedback/fixtures/v1/target-evidence/invalid/path-too-deep.json +0 -17
  378. package/packages/feedback/fixtures/v1/target-evidence/invalid/relative-region-out-of-range.json +0 -11
  379. package/packages/feedback/fixtures/v1/target-evidence/invalid/selector-uses-class.json +0 -7
  380. package/packages/feedback/fixtures/v1/target-evidence/invalid/source-precision-without-anchor.json +0 -6
  381. package/packages/feedback/fixtures/v1/target-evidence/valid/element-structure.json +0 -21
  382. package/packages/feedback/fixtures/v1/target-evidence/valid/host-iframe.json +0 -14
  383. package/packages/feedback/fixtures/v1/target-evidence/valid/source-anchor.json +0 -12
  384. package/packages/feedback/fixtures/v1/target-evidence/valid/text-selection.json +0 -26
  385. package/packages/feedback/package.json +0 -35
  386. package/packages/feedback/scripts/build-player.mjs +0 -28
  387. package/packages/feedback/src/index.ts +0 -1
  388. package/packages/feedback/src/primitives/composer.ts +0 -639
  389. package/packages/feedback/src/primitives/dialog.ts +0 -263
  390. package/packages/feedback/src/primitives/hostAdapter.ts +0 -116
  391. package/packages/feedback/src/primitives/index.ts +0 -10
  392. package/packages/feedback/src/primitives/launcher.ts +0 -200
  393. package/packages/feedback/src/primitives/picker.ts +0 -663
  394. package/packages/feedback/src/primitives/redaction.ts +0 -204
  395. package/packages/feedback/src/primitives/selection.ts +0 -49
  396. package/packages/feedback/src/primitives/shiftAccelerator.ts +0 -160
  397. package/packages/feedback/src/primitives/styles.ts +0 -77
  398. package/packages/feedback/src/primitives/surface.ts +0 -124
  399. package/packages/feedback/src/primitives/target.ts +0 -293
  400. package/packages/feedback/src/tour/canonical.ts +0 -27
  401. package/packages/feedback/src/tour/index.ts +0 -3
  402. package/packages/feedback/src/tour/player/browser.ts +0 -5
  403. package/packages/feedback/src/tour/player/host.ts +0 -12
  404. package/packages/feedback/src/tour/player/index.ts +0 -205
  405. package/packages/feedback/src/tour/player/manifest.ts +0 -76
  406. package/packages/feedback/src/tour/player/player.css +0 -130
  407. package/packages/feedback/src/tour/player/resolver.ts +0 -12
  408. package/packages/feedback/src/tour/player/surface.ts +0 -295
  409. package/packages/feedback/src/tour/player/types.ts +0 -8
  410. package/packages/feedback/src/tour/resolve/core.ts +0 -267
  411. package/packages/feedback/src/tour/resolve/dom.ts +0 -115
  412. package/packages/feedback/src/tour/resolve/index.ts +0 -29
  413. package/packages/feedback/src/tour/sanitize.ts +0 -76
  414. package/packages/feedback/src/tour/schema.ts +0 -362
  415. package/packages/feedback/src/v1/guards.ts +0 -335
  416. package/packages/feedback/src/v1/index.ts +0 -3
  417. package/packages/feedback/src/v1/protectedSurfaces.ts +0 -32
  418. package/packages/feedback/src/v1/types.ts +0 -177
  419. package/packages/feedback/tsconfig.json +0 -9
  420. package/packages/feedback/vitest.config.cts +0 -21
@@ -1,775 +0,0 @@
1
- /**
2
- * PrincipalGrantClient — the storefront's seam to tot20's principal-keyed grant
3
- * writer (ADR-0003, #8425): a scoped, revocable, expiring capability (`ship-on-behalf`
4
- * or `customer-contact-read`) issued to a HUMAN (by email), never a team role.
5
- *
6
- * This is the AUTHORIZATION (L2) surface — see docs/architecture/grant-surfaces.md
7
- * ("Let an operator app act on a store" row's owner-consent shape, generalized to
8
- * a human grantee). It is NOT the enrollment path (`@/lib/shared/developerInvites`,
9
- * which only ever emits `preview-access`/`blog-contribute` sign-in eligibility) —
10
- * the two revoke independently and must never be merged.
11
- *
12
- * POST /api/clients/principalGrants { tenant, principal:{type:'user',email}, capability, expiresAt }
13
- * → 200 { code:'operatorGrants:principalGrantCreated', tenant, principal, ref, capability, expiresAt }
14
- * → 422 operatorGrants:{expiresAtRequired|unknownCapability|invalidPrincipal|principalTypeNotSupported}
15
- * GET /api/clients/principalGrants?tenant=<t> → 200 { code:'operatorGrants:principalGrantsOk', grants:[...] }
16
- * DELETE /api/clients/principalGrants/{ref}?tenant=<t> → 200 { code:'operatorGrants:principalGrantRevoked', tenant }
17
- *
18
- * `expiresAt` (epoch-ms) is REQUIRED for a human grantee — tot20 fails closed
19
- * with `expiresAtRequired` if omitted (ADR-0003 D4: no standing authority for a
20
- * human/service principal). `ref` is opaque (never the raw email) and is what
21
- * `revoke`/list rows key on.
22
- *
23
- * GRANTOR MODES: BROKERED SESSION. Merchants hold no ToT API keys — they sign into
24
- * storefront's dashboard. tot20's `resolveGrantorContext` accepts three grantor
25
- * provenances, and this client drives the two brokered ones. The assertion's SUBJECT
26
- * decides which: the store owner gives `owner-brokered-session` (/api/grants/principal);
27
- * storefront-line ToT staff give `staff-consent-capture`, which tot20 audits with a
28
- * `staff:<hash>` actor and notifies the owner of (/api/grants/contact-capture). Other
29
- * staff roles are refused `staffScopeInsufficient`, and tot20 never lets staff list.
30
- *
31
- * - Naming a `tenant` on the request switches tot20 OFF the owner-key path (where
32
- * the grantor is the CALLER's own store — i.e. storefront itself) and onto the
33
- * brokered path.
34
- * - The brokered path requires a VERIFIED broker assertion whose signed `tenant`
35
- * claim matches the request's tenant EXACTLY (an unnormalized string compare, so
36
- * both are built from the same value here) and whose SUBJECT is the signed-in
37
- * person. tot20 then resolves ownership (`ownsTenant` →
38
- * `AccessCodeService.resolveEligibility`, strictly `capability === 'owner'`) or
39
- * staff role from its OWN state — the assertion proves WHO the subject is, never
40
- * WHAT they own or which role they hold.
41
- * - Transport auth stays storefront's OWN operator credential (`TOT_API_KEY` /
42
- * `TOT_SECRET_KEY`; the route is `requireSecretKey`), the same credential every
43
- * sibling client here presents. It authenticates the BROKER; it does not choose
44
- * the grantor. tot20 audits the result as `authorityPath:'owner-brokered-session'`
45
- * with actor `owner:<hash>` — distinct from the owner-key `self-service-direct`.
46
- *
47
- * The assertion is minted PER CALL by the route (the only layer holding the verified
48
- * session) and injected as {@link OwnerAssertionMinter}; this module never sees a
49
- * session and so cannot mint on a client-supplied email. tot20's verifier BURNS the
50
- * `jti` on first verify, so a minter that memoized would fail the second call as a
51
- * replay.
52
- *
53
- * AUTH WIRE: tot20's swagger `normalizeSecureUserRequest` accepts machine creds
54
- * three ways — request BODY fields `totApiKey`/`totSecretKey`, the same fields as
55
- * QUERY params, or an `Authorization` header carrying a base64 "license key"
56
- * (`base64("<apiKey>;<secretKey>")`, expanded by tot20's `expandLicenseKey`,
57
- * which takes PRECEDENCE over the body/query values). The broker assertion rides the
58
- * separate `X-ToT-Broker-Assertion` header ({@link BROKER_ASSERTION_HEADER}) — the
59
- * only place tot20's `readAssertion` looks. These are the integration-sensitive spots
60
- * ({@link credentialAuthHeader}, {@link HttpPrincipalGrantClient.brokeredHeaders}).
61
- *
62
- * ⚠ CREDENTIALS AND ASSERTIONS NEVER GO IN A URL. `POST` carries the credential in the
63
- * body; `GET`/`DELETE` have no body, so they use the `Authorization` license-key
64
- * header — NOT the query string, even though tot20 would accept it there. A query
65
- * string lands in access logs, proxy logs, browser history and error-tracking
66
- * payloads, so a credential there is a disclosure with a long tail. tot20 holds this
67
- * same line deliberately (its broker assertions are header-only "so the staff subject
68
- * never lands in URLs/access logs", and its revoke addresses a grant by an opaque
69
- * `ref` precisely so an email never becomes a path segment); this client must not be
70
- * the thing that breaks it. `?tenant=` on GET/DELETE is the ONE permitted query param
71
- * — an appDomain is public routing data, not a credential, and tot20 reads the tenant
72
- * from `req.query` on exactly those two verbs. `principalGrants.test.ts` asserts that
73
- * `tenant` is the only param present and that no credential or assertion value ever
74
- * reaches a URL, for any method — keep that guard.
75
- *
76
- * TIER: host + credentials are per-DEPLOY env, same `TOT_CORE_URL` the sibling
77
- * developerInvites/forge clients read (qa tier is what's live today for this route).
78
- *
79
- * Built like `@/lib/shared/developerInvites` (interface + Http impl + Mock + env
80
- * factory) so the route develops/tests against `MockPrincipalGrantClient` and
81
- * swaps in the Http client with no call-site change.
82
- */
83
- import { readEnv } from "@/lib/publication/shared/env";
84
- import { BROKER_ASSERTION_HEADER, BROKER_PRIVATE_KEY_ENV } from "@/lib/access/auth/brokerAssertion";
85
- import { resolveContactReadGrant } from "@/lib/access/auth/contactReaderAuthority";
86
- import { resolveViewerShipCapability } from "@/lib/access/shared/viewerGrant";
87
-
88
- /** The live principal grant a person holds on a store, as far as the grant reads can tell. */
89
- export type HeldPrincipalGrant = "customer-contact-read" | "ship-on-behalf" | null;
90
-
91
- /**
92
- * The live principal grant `email` already holds on `tenant`, read through the per-person
93
- * subject-capability seam (keyed by email). tot20 keeps ONE principal grant per person per store
94
- * (`addPrincipalGrant` writes `principalGrants[principalKey]`, capability included), so a new grant
95
- * to someone who holds one REPLACES it; callers refuse instead. tot20's grant LIST cannot answer
96
- * this: its rows name the principal by an opaque id, never the email. Both reads fail closed to
97
- * "none" on a seam fault, so a fault lets the grant through rather than blocking it.
98
- */
99
- export async function heldPrincipalGrant(email: string, tenant: string): Promise<HeldPrincipalGrant> {
100
- if (await resolveContactReadGrant(email, tenant)) return "customer-contact-read";
101
- if ((await resolveViewerShipCapability(email, tenant)) === "ship-on-behalf") return "ship-on-behalf";
102
- return null;
103
- }
104
-
105
- /** A human grantee — the only principal type this HTTP surface accepts. */
106
- export interface UserPrincipal {
107
- type: "user";
108
- email: string;
109
- }
110
-
111
- /** Kept as a string so a future tot20 vocabulary addition (see
112
- * `grantCapabilities.CAPABILITIES` in tot20) doesn't need a type change here. */
113
- export type PrincipalGrantCapability = "ship-on-behalf" | "customer-contact-read" | (string & {});
114
-
115
- // --- Route guards shared by the grant routes ---------------------------------
116
-
117
- /** The capabilities storefront's grant routes may issue. Anything else is refused before tot20. */
118
- export const GRANTABLE_CAPABILITIES = ["ship-on-behalf", "customer-contact-read"] as const;
119
- export type GrantableCapability = (typeof GRANTABLE_CAPABILITIES)[number];
120
-
121
- export function isGrantableCapability(value: unknown): value is GrantableCapability {
122
- return typeof value === "string" && (GRANTABLE_CAPABILITIES as readonly string[]).includes(value);
123
- }
124
-
125
- const HOUR_MS = 60 * 60 * 1000;
126
- const DAY_MS = 24 * HOUR_MS;
127
-
128
- /**
129
- * Expiry bounds per capability. Customer contact data is order and customer PII, so its grants are
130
- * short (at most 7 days); ship-on-behalf keeps its longer delegation window.
131
- */
132
- export const GRANT_TTL_BOUNDS: Record<GrantableCapability, { minMs: number; maxMs: number; label: string }> = {
133
- "ship-on-behalf": { minMs: HOUR_MS, maxMs: 90 * DAY_MS, label: "between 1 hour and 90 days" },
134
- "customer-contact-read": { minMs: HOUR_MS, maxMs: 7 * DAY_MS, label: "between 1 hour and 7 days" },
135
- };
136
-
137
- /**
138
- * The expiry for a grant request: `expiresAt` (epoch-ms) wins, else `ttlMs` from now. Refused when
139
- * absent, not finite, or outside the capability's bounds.
140
- */
141
- export function grantExpiry(
142
- capability: GrantableCapability,
143
- body: { expiresAt?: unknown; ttlMs?: unknown },
144
- now: number,
145
- ): { ok: true; expiresAt: number } | { ok: false; error: string } {
146
- let expiresAt: number;
147
- if (typeof body.expiresAt === "number" && Number.isFinite(body.expiresAt)) expiresAt = body.expiresAt;
148
- else if (typeof body.ttlMs === "number" && Number.isFinite(body.ttlMs)) expiresAt = now + body.ttlMs;
149
- else return { ok: false, error: "expiresAt (epoch-ms) or ttlMs is required — a human grant is never standing authority" };
150
- const { minMs, maxMs, label } = GRANT_TTL_BOUNDS[capability];
151
- const ttl = expiresAt - now;
152
- if (ttl < minMs || ttl > maxMs) return { ok: false, error: `expiry must be ${label} from now` };
153
- return { ok: true, expiresAt };
154
- }
155
-
156
- /**
157
- * Cross-site request refusal for the cookie-authenticated grant mutations. The session cookie is
158
- * SameSite=Lax and the admin entry checks do not look at Origin, so a sibling host under the shared
159
- * store domain could otherwise post here. Requires `Origin` equal to the request URL's origin and,
160
- * for a body-carrying method, a JSON content type. Returns a 403 response to send, or null to proceed.
161
- */
162
- export function crossOriginRefusal(request: Request): Response | null {
163
- const origin = request.headers.get("origin");
164
- let expected: string;
165
- try {
166
- expected = new URL(request.url).origin;
167
- } catch {
168
- expected = "";
169
- }
170
- const sameOrigin = !!origin && !!expected && origin === expected;
171
- const contentType = (request.headers.get("content-type") ?? "").toLowerCase();
172
- const jsonBody = request.method === "GET" || request.method === "HEAD" || contentType.startsWith("application/json");
173
- if (sameOrigin && jsonBody) return null;
174
- return new Response(JSON.stringify({ error: "cross-origin" }), {
175
- status: 403,
176
- headers: { "content-type": "application/json" },
177
- });
178
- }
179
-
180
- /** How a staff member heard the owner consent. A fixed list, so no free text reaches a grant. */
181
- export const CONSENT_CHANNELS = ["phone", "email", "chat", "meeting"] as const;
182
- export type ConsentChannel = (typeof CONSENT_CHANNELS)[number];
183
-
184
- /** The support-ticket reference shape the contact support-read already accepts. */
185
- export const CONSENT_TICKET_REF = /^[A-Za-z0-9._-]{1,64}$/;
186
-
187
- /**
188
- * The grant purpose recorded for a staff consent capture, from validated fields only, so a purpose
189
- * can never carry customer detail.
190
- */
191
- export function consentCapturePurpose(
192
- body: { channel?: unknown; ticket?: unknown },
193
- ): { ok: true; purpose: string; channel: ConsentChannel; ticket: string } | { ok: false; error: string } {
194
- const channel = body.channel;
195
- if (typeof channel !== "string" || !(CONSENT_CHANNELS as readonly string[]).includes(channel)) {
196
- return { ok: false, error: `channel must be one of ${CONSENT_CHANNELS.join(", ")}` };
197
- }
198
- const ticket = typeof body.ticket === "string" ? body.ticket.trim() : "";
199
- if (!CONSENT_TICKET_REF.test(ticket)) return { ok: false, error: "ticket must be a support ticket reference" };
200
- return {
201
- ok: true,
202
- purpose: `staff-consent-capture channel=${channel} ticket=${ticket}`,
203
- channel: channel as ConsentChannel,
204
- ticket,
205
- };
206
- }
207
-
208
- export interface CreatePrincipalGrantInput {
209
- /** Target tenant this grant is issued on (session-derived; never trust a body field). */
210
- tenant: string;
211
- principal: UserPrincipal;
212
- capability: PrincipalGrantCapability;
213
- /** Epoch-ms; REQUIRED (ADR-0003 D4 — a human grant is never standing authority). */
214
- expiresAt: number;
215
- scope?: string;
216
- purpose?: string;
217
- }
218
-
219
- export interface PrincipalGrantCreated {
220
- ok: true;
221
- tenant: string;
222
- principal: UserPrincipal;
223
- /** Opaque revoke handle — never the raw email. */
224
- ref: string;
225
- capability: string;
226
- expiresAt: number;
227
- }
228
-
229
- export type PrincipalGrantFailureReason =
230
- | "notAuthenticated" // 403/422 — storefront's own operator credential missing/rejected
231
- | "expiresAtRequired" // 422 — ADR-0003 D4
232
- | "unknownCapability" // 422
233
- | "invalidPrincipal" // 422
234
- | "principalTypeNotSupported" // 422 — non-'user' principal at this HTTP layer
235
- // --- owner-brokered grantor path (tot20 `resolveGrantorContext`) ---
236
- | "brokerAssertionRequired" // 422 — named a tenant with no assertion (client bug)
237
- | "brokerAssertionInvalid" // 401 — bad signature / expired / replayed jti
238
- | "assertionTenantMismatch" // 422 — assertion names a different tenant than the request
239
- | "tenantNotRegistered" // 422 — the named appDomain is not a ToT client
240
- | "subjectNotTenantOwner" // 403 — the signed-in subject does not OWN this tenant
241
- | "staffScopeInsufficient" // 403 — a staff subject whose role may not capture consent here
242
- | "brokerNotConfigured" // LOCAL 503 — this deploy holds no broker signing key
243
- | "error"; // transport / unexpected upstream fault
244
-
245
- export interface PrincipalGrantFailed {
246
- ok: false;
247
- status: number;
248
- reason: PrincipalGrantFailureReason;
249
- message: string;
250
- code?: string;
251
- }
252
-
253
- export type PrincipalGrantResult = PrincipalGrantCreated | PrincipalGrantFailed;
254
-
255
- export interface PrincipalGrantSummary {
256
- principal: UserPrincipal;
257
- capability: string;
258
- expiresAt: number;
259
- ref: string;
260
- }
261
-
262
- export type PrincipalGrantListResult =
263
- | { ok: true; tenant: string; grants: PrincipalGrantSummary[] }
264
- | { ok: false; status: number; reason: PrincipalGrantFailureReason; message: string; code?: string };
265
-
266
- export type PrincipalGrantRevokeResult =
267
- | { ok: true; tenant: string; ref: string }
268
- | { ok: false; status: number; reason: PrincipalGrantFailureReason; message: string; code?: string };
269
-
270
- export interface PrincipalGrantClient {
271
- createGrant(input: CreatePrincipalGrantInput): Promise<PrincipalGrantResult>;
272
- listGrants(tenant: string): Promise<PrincipalGrantListResult>;
273
- revokeGrant(tenant: string, ref: string): Promise<PrincipalGrantRevokeResult>;
274
- }
275
-
276
- // --- HTTP transport seam (injected by tests) --------------------------------
277
-
278
- export interface HttpResponseLike {
279
- status: number;
280
- json(): Promise<unknown>;
281
- }
282
- export interface HttpTransport {
283
- post(url: string, headers: Record<string, string>, body: unknown): Promise<HttpResponseLike>;
284
- get(url: string, headers: Record<string, string>): Promise<HttpResponseLike>;
285
- delete(url: string, headers: Record<string, string>): Promise<HttpResponseLike>;
286
- }
287
-
288
- export class FetchHttpTransport implements HttpTransport {
289
- async post(url: string, headers: Record<string, string>, body: unknown) {
290
- const res = await fetch(url, {
291
- method: "POST",
292
- redirect: "manual",
293
- headers: { "content-type": "application/json", accept: "application/json", ...headers },
294
- body: JSON.stringify(body),
295
- });
296
- if (res.status >= 300 && res.status < 400) throw new Error("authenticated transport refused redirect");
297
- return res;
298
- }
299
- async get(url: string, headers: Record<string, string>) {
300
- const res = await fetch(url, { method: "GET", headers: { accept: "application/json", ...headers }, redirect: "manual" });
301
- if (res.status >= 300 && res.status < 400) throw new Error("authenticated transport refused redirect");
302
- return res;
303
- }
304
- async delete(url: string, headers: Record<string, string>) {
305
- const res = await fetch(url, { method: "DELETE", headers: { accept: "application/json", ...headers }, redirect: "manual" });
306
- if (res.status >= 300 && res.status < 400) throw new Error("authenticated transport refused redirect");
307
- return res;
308
- }
309
- }
310
-
311
- export class PrincipalGrantClientError extends Error {}
312
-
313
- /**
314
- * Mints a FRESH broker assertion naming `tenant`, whose subject is the signed-in
315
- * OWNER. Supplied by the route, which is the only layer holding a verified session
316
- * — keeping this an injected function is what makes it structurally impossible for
317
- * this module to assert an email that came off a request.
318
- *
319
- * Returns `null` when this deploy cannot sign at all (no broker key) — the caller
320
- * fails closed with `brokerNotConfigured` rather than sending an unbrokered request
321
- * that tot20 would silently resolve to storefront's OWN store as grantor.
322
- *
323
- * Called once per request: tot20 burns the `jti`, so a cached assertion replays.
324
- */
325
- export type OwnerAssertionMinter = (tenant: string) => Promise<string | null>;
326
-
327
- /**
328
- * Build the `Authorization` header tot20 accepts for a body-less request (GET /
329
- * DELETE), so the credential never reaches the URL. tot20's `expandLicenseKey`
330
- * base64-decodes this value and splits it on `;` into `apiKey;secretKey[;appDomain]`,
331
- * and `normalizeSecureUserRequest` prefers it over any body/query credential.
332
- *
333
- * Note the encoding is not optional: `expandLicenseKey` returns `undefined` for a
334
- * PLAIN `a;b` string (it only decodes values that don't already split into 2-3
335
- * fields), so the base64 wrapper is what makes tot20 read it at all. Base64's
336
- * alphabet contains no `;`, so the wrapper can never be mistaken for the plain form.
337
- */
338
- export function credentialAuthHeader(cred: {
339
- totApiKey: string;
340
- totSecretKey?: string;
341
- }): { authorization: string } {
342
- const licenseKey = `${cred.totApiKey};${cred.totSecretKey ?? ""}`;
343
- return { authorization: Buffer.from(licenseKey, "utf8").toString("base64") };
344
- }
345
-
346
- export interface HttpPrincipalGrantClientConfig {
347
- /** tot20 core API base (no trailing slash), e.g. https://qa.tokenoftrust.com */
348
- baseUrl: string;
349
- /** Storefront's OWN operator credential — authenticates the broker, not the grantor. */
350
- apiKey: string;
351
- secretKey?: string;
352
- mintOwnerAssertion: OwnerAssertionMinter;
353
- transport?: HttpTransport;
354
- }
355
-
356
- export class HttpPrincipalGrantClient implements PrincipalGrantClient {
357
- private readonly baseUrl: string;
358
- private readonly apiKey: string;
359
- private readonly secretKey: string | undefined;
360
- private readonly mintOwnerAssertion: OwnerAssertionMinter;
361
- private readonly transport: HttpTransport;
362
-
363
- constructor(config: HttpPrincipalGrantClientConfig) {
364
- if (!config.baseUrl) {
365
- throw new PrincipalGrantClientError("principalGrants: TOT_CORE_URL is not configured");
366
- }
367
- if (!config.apiKey) {
368
- throw new PrincipalGrantClientError("principalGrants: TOT_API_KEY is not configured");
369
- }
370
- this.baseUrl = config.baseUrl.replace(/\/+$/, "");
371
- this.apiKey = config.apiKey;
372
- this.secretKey = config.secretKey;
373
- this.mintOwnerAssertion = config.mintOwnerAssertion;
374
- this.transport = config.transport ?? new FetchHttpTransport();
375
- }
376
-
377
- /** Storefront's own operator credential, as tot20's documented body fields. */
378
- private credential(): { totApiKey: string; totSecretKey?: string } {
379
- return { totApiKey: this.apiKey, ...(this.secretKey ? { totSecretKey: this.secretKey } : {}) };
380
- }
381
-
382
- /**
383
- * Headers for a brokered call. `assertion` is header-only; the license-key
384
- * `Authorization` is added for the body-less verbs, which have nowhere else to
385
- * carry the credential that isn't the URL.
386
- */
387
- private brokeredHeaders(assertion: string, withCredential: boolean): Record<string, string> {
388
- return {
389
- [BROKER_ASSERTION_HEADER]: assertion,
390
- ...(withCredential ? credentialAuthHeader(this.credential()) : {}),
391
- };
392
- }
393
-
394
- async createGrant(input: CreatePrincipalGrantInput): Promise<PrincipalGrantResult> {
395
- const assertion = await this.mintOwnerAssertion(input.tenant);
396
- if (!assertion) return brokerNotConfigured();
397
-
398
- // `tenant` in the BODY is what puts tot20 on the owner-brokered branch for POST
399
- // (createPrincipalGrant reads `body.tenant`); GET/DELETE read `req.query.tenant`.
400
- const body: Record<string, unknown> = {
401
- tenant: input.tenant,
402
- principal: { type: "user", email: input.principal.email.toLowerCase() },
403
- capability: input.capability,
404
- expiresAt: input.expiresAt,
405
- ...this.credential(),
406
- };
407
- if (input.scope) body.scope = input.scope;
408
- if (input.purpose) body.purpose = input.purpose;
409
-
410
- logGrantDiag("request", {
411
- endpoint: `${this.baseUrl}/api/clients/principalGrants`,
412
- capability: input.capability,
413
- expiresAt: input.expiresAt,
414
- });
415
-
416
- let res: HttpResponseLike;
417
- try {
418
- res = await this.transport.post(
419
- `${this.baseUrl}/api/clients/principalGrants`,
420
- this.brokeredHeaders(assertion, false),
421
- body,
422
- );
423
- } catch {
424
- return transportFailure("creating principal grant");
425
- }
426
- const parsed = await safeJson(res, "creating principal grant");
427
- if ("failed" in parsed) return parsed.failed;
428
- const result = normalizeCreateResponse(res.status, parsed.body);
429
- logGrantDiag("response", {
430
- httpStatus: res.status,
431
- ok: result.ok,
432
- ...(result.ok
433
- ? { hasRef: !!result.ref }
434
- : { reason: result.reason, hasCode: !!result.code }),
435
- });
436
- return result;
437
- }
438
-
439
- async listGrants(tenant: string): Promise<PrincipalGrantListResult> {
440
- const assertion = await this.mintOwnerAssertion(tenant);
441
- if (!assertion) return brokerNotConfigured();
442
- let res: HttpResponseLike;
443
- try {
444
- // `tenant` is the ONLY query param — public routing data, and the only place
445
- // tot20's listPrincipalGrants reads it. The credential stays in a header.
446
- res = await this.transport.get(
447
- `${this.baseUrl}/api/clients/principalGrants?tenant=${encodeURIComponent(tenant)}`,
448
- this.brokeredHeaders(assertion, true),
449
- );
450
- } catch {
451
- return transportFailure("listing principal grants");
452
- }
453
- const parsed = await safeJson(res, "listing principal grants");
454
- if ("failed" in parsed) return parsed.failed;
455
- return normalizeListResponse(res.status, tenant, parsed.body);
456
- }
457
-
458
- async revokeGrant(tenant: string, ref: string): Promise<PrincipalGrantRevokeResult> {
459
- const assertion = await this.mintOwnerAssertion(tenant);
460
- if (!assertion) return brokerNotConfigured();
461
- let res: HttpResponseLike;
462
- try {
463
- // `ref` is tot20's opaque grant handle (never a raw email), so it is safe as a
464
- // path segment — that is exactly why tot20 addresses revoke by ref. `tenant` is
465
- // the only query param; the credential stays in the Authorization header.
466
- res = await this.transport.delete(
467
- `${this.baseUrl}/api/clients/principalGrants/${encodeURIComponent(ref)}` +
468
- `?tenant=${encodeURIComponent(tenant)}`,
469
- this.brokeredHeaders(assertion, true),
470
- );
471
- } catch {
472
- return transportFailure("revoking principal grant");
473
- }
474
- const parsed = await safeJson(res, "revoking principal grant");
475
- if ("failed" in parsed) return parsed.failed;
476
- return normalizeRevokeResponse(res.status, tenant, parsed.body);
477
- }
478
- }
479
-
480
- function brokerNotConfigured(): PrincipalGrantFailed {
481
- return {
482
- ok: false,
483
- status: 503,
484
- reason: "brokerNotConfigured",
485
- message:
486
- "this storefront deploy cannot sign an owner assertion " +
487
- `(${BROKER_PRIVATE_KEY_ENV} is not configured), so the request was not sent`,
488
- };
489
- }
490
-
491
- async function transportFailure(action: string): Promise<PrincipalGrantFailed> {
492
- return {
493
- ok: false,
494
- status: 0,
495
- reason: "error",
496
- message: `principalGrants: transport failure ${action}`,
497
- };
498
- }
499
-
500
- async function safeJson(
501
- res: HttpResponseLike,
502
- action: string,
503
- ): Promise<{ body: unknown } | { failed: PrincipalGrantFailed }> {
504
- try {
505
- return { body: await res.json() };
506
- } catch {
507
- return {
508
- failed: {
509
- ok: false,
510
- status: res.status,
511
- reason: "error",
512
- message: `principalGrants: tot20 returned a non-JSON body ${action} (status ${res.status})`,
513
- },
514
- };
515
- }
516
- }
517
-
518
- function logGrantDiag(phase: "request" | "response", fields: Record<string, unknown>): void {
519
- try {
520
- console.info(`[diag:principalGrants:${phase}]`, JSON.stringify(fields));
521
- } catch {
522
- /* diagnostics must never break the call */
523
- }
524
- }
525
-
526
- function unwrapEnvelope(body: unknown): Record<string, unknown> {
527
- const raw = (body ?? {}) as Record<string, unknown>;
528
- return (raw.content && typeof raw.content === "object" ? raw.content : raw) as Record<string, unknown>;
529
- }
530
-
531
- function reasonFor(code: string | undefined, status: number): PrincipalGrantFailureReason {
532
- switch (code) {
533
- case "operatorGrants:notAuthenticated":
534
- return "notAuthenticated";
535
- case "operatorGrants:expiresAtRequired":
536
- case "operatorGrants:invalidExpiresAt":
537
- return "expiresAtRequired";
538
- case "operatorGrants:unknownCapability":
539
- return "unknownCapability";
540
- case "operatorGrants:invalidPrincipal":
541
- case "operatorGrants:principalNotFound":
542
- return "invalidPrincipal";
543
- case "operatorGrants:principalTypeNotSupported":
544
- return "principalTypeNotSupported";
545
- // --- owner-brokered grantor path ---
546
- case "operatorGrants:brokerAssertionRequired":
547
- return "brokerAssertionRequired";
548
- case "operatorGrants:brokerAssertionInvalid":
549
- return "brokerAssertionInvalid";
550
- // All three are the same class of storefront bug: the signed `tenant` claim and
551
- // the tenant on the request did not line up. Collapsed so the UI has one story.
552
- case "operatorGrants:assertionTenantRequired":
553
- case "operatorGrants:tenantAssertionMismatch":
554
- case "operatorGrants:tenantRequired":
555
- return "assertionTenantMismatch";
556
- case "operatorGrants:tenantNotRegistered":
557
- return "tenantNotRegistered";
558
- case "operatorGrants:subjectNotTenantOwner":
559
- return "subjectNotTenantOwner";
560
- // The staff-consent-capture branch (POST /api/grants/contact-capture): tot20 decided this
561
- // staff role may not capture consent on the tenant.
562
- case "operatorGrants:staffScopeInsufficient":
563
- return "staffScopeInsufficient";
564
- default:
565
- if (status === 403 || status === 401) return "notAuthenticated";
566
- return "error";
567
- }
568
- }
569
-
570
- /**
571
- * Turn a tot20 refusal into a typed failure. When we RECOGNISE the code we prefer
572
- * our own operator-facing wording over tot20's — tot20's messages are written for
573
- * an API integrator ("The broker assertion names a different tenant than the
574
- * request."), which is noise to a merchant clicking Delegate. An unrecognised code
575
- * keeps tot20's message, since that is the only signal we have.
576
- */
577
- function failureFrom(
578
- status: number,
579
- c: Record<string, unknown>,
580
- ): { status: number; reason: PrincipalGrantFailureReason; message: string; code?: string } {
581
- const code = typeof c.code === "string" ? c.code : undefined;
582
- const reason = reasonFor(code, status);
583
- const upstream = typeof c.message === "string" ? c.message : undefined;
584
- const message = reason === "error" && upstream ? upstream : principalGrantFailureMessage(reason);
585
- return { status, reason, message, ...(code ? { code } : {}) };
586
- }
587
-
588
- /** Finite operator-facing copy for a principal-grant refusal — the only text a route returns. */
589
- export function principalGrantFailureMessage(reason: PrincipalGrantFailureReason): string {
590
- switch (reason) {
591
- case "notAuthenticated":
592
- return "storefront isn't authorized to grant on this tenant";
593
- case "expiresAtRequired":
594
- return "a future expiresAt is required for a human grant";
595
- case "unknownCapability":
596
- return "unknown capability";
597
- case "invalidPrincipal":
598
- return "a valid grantee email is required";
599
- case "principalTypeNotSupported":
600
- return "this endpoint grants a human (email) principal only";
601
- case "subjectNotTenantOwner":
602
- return "only an owner of this store can grant access";
603
- case "staffScopeInsufficient":
604
- return "your Token of Trust staff role can't capture owner consent on this store";
605
- case "tenantNotRegistered":
606
- return "this store isn't registered with Token of Trust";
607
- case "brokerAssertionInvalid":
608
- return "your session proof was rejected — sign in again and retry";
609
- case "brokerAssertionRequired":
610
- case "assertionTenantMismatch":
611
- return "storefront sent a malformed delegation request — please report this";
612
- case "brokerNotConfigured":
613
- return "delegation isn't available on this deployment";
614
- default:
615
- return "Token of Trust couldn't complete the delegation; try again shortly";
616
- }
617
- }
618
-
619
- export function normalizeCreateResponse(status: number, body: unknown): PrincipalGrantResult {
620
- const c = unwrapEnvelope(body);
621
- const code = typeof c.code === "string" ? c.code : undefined;
622
- const isCreated = code === "operatorGrants:principalGrantCreated" || (status >= 200 && status < 300 && typeof c.ref === "string");
623
- if (isCreated) {
624
- return {
625
- ok: true,
626
- tenant: String(c.tenant ?? ""),
627
- principal: (c.principal as UserPrincipal) ?? { type: "user", email: "" },
628
- ref: String(c.ref ?? ""),
629
- capability: String(c.capability ?? ""),
630
- expiresAt: Number(c.expiresAt ?? 0),
631
- };
632
- }
633
- return { ok: false, ...failureFrom(status, c) };
634
- }
635
-
636
- export function normalizeListResponse(status: number, tenant: string, body: unknown): PrincipalGrantListResult {
637
- const c = unwrapEnvelope(body);
638
- const code = typeof c.code === "string" ? c.code : undefined;
639
- const isOk = code === "operatorGrants:principalGrantsOk" || (status >= 200 && status < 300 && Array.isArray(c.grants));
640
- if (isOk) {
641
- const grants: PrincipalGrantSummary[] = (Array.isArray(c.grants) ? c.grants : []).map((raw) => {
642
- const g = (raw ?? {}) as Record<string, unknown>;
643
- return {
644
- principal: (g.principal as UserPrincipal) ?? { type: "user", email: "" },
645
- capability: String(g.capability ?? ""),
646
- expiresAt: Number(g.expiresAt ?? 0),
647
- ref: String(g.ref ?? ""),
648
- };
649
- });
650
- return { ok: true, tenant, grants };
651
- }
652
- return { ok: false, ...failureFrom(status, c) };
653
- }
654
-
655
- export function normalizeRevokeResponse(status: number, tenant: string, body: unknown): PrincipalGrantRevokeResult {
656
- const c = unwrapEnvelope(body);
657
- const code = typeof c.code === "string" ? c.code : undefined;
658
- const isOk = code === "operatorGrants:principalGrantRevoked" || (status >= 200 && status < 300);
659
- if (isOk) {
660
- return { ok: true, tenant: String(c.tenant ?? tenant), ref: "" };
661
- }
662
- return { ok: false, ...failureFrom(status, c) };
663
- }
664
-
665
- /** Map a typed failure onto the HTTP status a storefront route should return. */
666
- export function principalGrantHttpStatus(reason: PrincipalGrantFailureReason, upstreamStatus: number): number {
667
- switch (reason) {
668
- case "notAuthenticated":
669
- return 403;
670
- case "expiresAtRequired":
671
- case "unknownCapability":
672
- case "invalidPrincipal":
673
- case "principalTypeNotSupported":
674
- case "brokerAssertionRequired":
675
- case "assertionTenantMismatch":
676
- case "tenantNotRegistered":
677
- return 422;
678
- case "brokerAssertionInvalid":
679
- return 401;
680
- case "subjectNotTenantOwner":
681
- case "staffScopeInsufficient":
682
- return 403;
683
- case "brokerNotConfigured":
684
- return 503;
685
- default:
686
- return upstreamStatus >= 400 ? upstreamStatus : 502;
687
- }
688
- }
689
-
690
- // --- Mock (tests + local dev) -----------------------------------------------
691
-
692
- /** In-memory PrincipalGrantClient — deterministic for route/UI tests. */
693
- export class MockPrincipalGrantClient implements PrincipalGrantClient {
694
- private grants = new Map<string, { principal: UserPrincipal; capability: string; expiresAt: number }>();
695
- private seq = 0;
696
- /** Tenants the signed-in subject does NOT own (tot20's `subjectNotTenantOwner`). */
697
- private readonly notOwned: Set<string>;
698
-
699
- constructor(notOwnedTenants: string[] = []) {
700
- this.notOwned = new Set(notOwnedTenants.map((t) => t.toLowerCase()));
701
- }
702
-
703
- private refuseNotOwner(): PrincipalGrantFailed {
704
- return {
705
- ok: false,
706
- status: 403,
707
- reason: "subjectNotTenantOwner",
708
- message: principalGrantFailureMessage("subjectNotTenantOwner"),
709
- code: "operatorGrants:subjectNotTenantOwner",
710
- };
711
- }
712
-
713
- async createGrant(input: CreatePrincipalGrantInput): Promise<PrincipalGrantResult> {
714
- const tenant = input.tenant.toLowerCase();
715
- if (this.notOwned.has(tenant)) return this.refuseNotOwner();
716
- if (!input.expiresAt || input.expiresAt <= Date.now()) {
717
- return { ok: false, status: 422, reason: "expiresAtRequired", message: "a future expiresAt is required", code: "operatorGrants:expiresAtRequired" };
718
- }
719
- const email = input.principal.email.trim().toLowerCase();
720
- if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
721
- return { ok: false, status: 422, reason: "invalidPrincipal", message: "a valid grantee email is required", code: "operatorGrants:invalidPrincipal" };
722
- }
723
- const ref = `mock-ref-${tenant}-${++this.seq}`;
724
- this.grants.set(ref, { principal: { type: "user", email }, capability: input.capability, expiresAt: input.expiresAt });
725
- return { ok: true, tenant, principal: { type: "user", email }, ref, capability: input.capability, expiresAt: input.expiresAt };
726
- }
727
-
728
- async listGrants(tenant: string): Promise<PrincipalGrantListResult> {
729
- const t = tenant.toLowerCase();
730
- if (this.notOwned.has(t)) return this.refuseNotOwner();
731
- const grants = [...this.grants.entries()]
732
- .filter(([ref]) => ref.startsWith(`mock-ref-${t}-`))
733
- .map(([ref, g]) => ({ ...g, ref }));
734
- return { ok: true, tenant: t, grants };
735
- }
736
-
737
- async revokeGrant(tenant: string, ref: string): Promise<PrincipalGrantRevokeResult> {
738
- const t = tenant.toLowerCase();
739
- if (this.notOwned.has(t)) return this.refuseNotOwner();
740
- if (!ref.startsWith(`mock-ref-${t}-`) || !this.grants.has(ref)) {
741
- return { ok: false, status: 404, reason: "error", message: "no such grant" };
742
- }
743
- this.grants.delete(ref);
744
- return { ok: true, tenant: t, ref };
745
- }
746
- }
747
-
748
- // --- Factory ----------------------------------------------------------------
749
-
750
- /**
751
- * Build the env-configured client:
752
- * - `TOT_CORE_URL` — tot20 core API base (tier-matching per deploy).
753
- * - `TOT_API_KEY` (+ optional `TOT_SECRET_KEY`) — storefront's own operator creds.
754
- *
755
- * `mintOwnerAssertion` is a REQUIRED positional argument, not an override with a
756
- * default: there is no safe default. A client built without it would send an
757
- * unbrokered request that tot20 resolves to storefront's OWN store as grantor —
758
- * silently granting on the wrong tenant. Making it structural means the caller must
759
- * hold a verified owner session to build a client at all.
760
- */
761
- export async function createPrincipalGrantClient(
762
- mintOwnerAssertion: OwnerAssertionMinter,
763
- overrides: Partial<Omit<HttpPrincipalGrantClientConfig, "mintOwnerAssertion">> = {},
764
- ): Promise<HttpPrincipalGrantClient> {
765
- const baseUrl = overrides.baseUrl ?? (await readEnv("TOT_CORE_URL")) ?? "";
766
- const apiKey = overrides.apiKey ?? (await readEnv("TOT_API_KEY")) ?? "";
767
- const secretKey = overrides.secretKey ?? (await readEnv("TOT_SECRET_KEY"));
768
- return new HttpPrincipalGrantClient({
769
- baseUrl,
770
- apiKey,
771
- mintOwnerAssertion,
772
- ...(secretKey ? { secretKey } : {}),
773
- ...(overrides.transport ? { transport: overrides.transport } : {}),
774
- });
775
- }