@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,265 +0,0 @@
1
- /**
2
- * Weekly-digest send orchestration (newsletter-send epic). A single callable
3
- * `sendWeeklyDigest` that the admin trigger endpoint invokes; this unit builds
4
- * NO HTTP route. Flow (docs/plans/2026-08-22-newsletter-send-spike.md §5–6):
5
- *
6
- * 1. Compute this period's `digestId` (`<collection>-<ISO-week>`) and short-
7
- * circuit if a `newsletter_sends` row already exists for it — the
8
- * idempotency guard that stops a re-triggered send from double-sending.
9
- * 2. Collect posts published SINCE the last send (all live posts on the first
10
- * ever send). Empty → skip, no ledger row burned.
11
- * 3. Query `confirmed` subscribers; none → skip.
12
- * 4. Build the digest ONCE, personalize the unsubscribe token per recipient,
13
- * batch-send via Resend (≤100/call), then record the ledger row and stamp
14
- * each recipient's `last_sent_at`.
15
- *
16
- * Idempotency design (the spike offered two; this is the simpler): scope is the
17
- * whole SEND, keyed by ISO-week `digestId` in `newsletter_sends` — NOT a
18
- * per-subscriber diff. "New since last send" is computed once from the previous
19
- * ledger row's `sent_at`, not per-subscriber.
20
- */
21
- import type { Queryable } from "../../catalog/d1/catalog.js";
22
- import type { BlogPostSummary } from "../../content/blog/types.js";
23
- import {
24
- sendBatch as realSendBatch,
25
- RESEND_BATCH_LIMIT,
26
- type ResendEmail,
27
- type SendBatchFn,
28
- } from "./resendClient.js";
29
- import {
30
- buildDigestHtml,
31
- unsubscribeUrl,
32
- UNSUBSCRIBE_TOKEN_PLACEHOLDER,
33
- type DigestConfig,
34
- } from "./digest.js";
35
-
36
- export interface SendDeps {
37
- db: Queryable;
38
- /** Live-visible post source (the engine's `listPosts`); drafts never leak. */
39
- listPosts: (tenantId: string, collection: string) => Promise<BlogPostSummary[]>;
40
- resendApiKey: string;
41
- config: DigestConfig & {
42
- /** Verified sending address, e.g. `the-build@mail.tokenoftrust.store`. */
43
- fromAddress: string;
44
- /** `Reply-To:`; falls back to `fromAddress`. */
45
- replyTo?: string;
46
- };
47
- /** Send seam — tests inject a fake; defaults to the real Resend client. */
48
- sendBatch?: SendBatchFn;
49
- /** Clock injection for deterministic digest ids + timestamps. */
50
- now?: () => Date;
51
- }
52
-
53
- export type SendResult =
54
- | { sent: number; digestId: string }
55
- | { skipped: true; reason: string };
56
-
57
- /** The reasons a send would perform NO work — shared by preview and send. */
58
- export type DigestSkipReason = "already-sent-this-period" | "no-new-posts" | "no-subscribers";
59
-
60
- /** The shared verified sending domain (SPF/DKIM/DMARC configured with Resend). */
61
- export const NEWSLETTER_SENDING_DOMAIN = "mail.tokenoftrust.store";
62
-
63
- /**
64
- * Resolve the digest's `From:` address. An explicit per-tenant `fromAddress`
65
- * wins; otherwise derive `<collection>@mail.tokenoftrust.store` on the shared
66
- * verified domain. Deliberately NEVER derives from the tenant's own store domain
67
- * — that domain is not a verified sending domain, so a send from it would fail
68
- * SPF/DKIM alignment at the ESP.
69
- */
70
- export function resolveFromAddress(collection: string, configured?: string): string {
71
- const explicit = configured?.trim();
72
- if (explicit) return explicit;
73
- const localPart =
74
- collection.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "newsletter";
75
- return `${localPart}@${NEWSLETTER_SENDING_DOMAIN}`;
76
- }
77
-
78
- interface SubscriberRow {
79
- email: string;
80
- token: string;
81
- }
82
-
83
- /** The read-only shape a dry-run preview needs (no send seam / api key). */
84
- export interface PreviewDeps {
85
- db: Queryable;
86
- listPosts: (tenantId: string, collection: string) => Promise<BlogPostSummary[]>;
87
- now?: () => Date;
88
- }
89
-
90
- /** What a send WOULD do this period, computed without sending anything. */
91
- export interface DigestPreview {
92
- digestId: string;
93
- /** Posts published since the last send (empty when nothing new). */
94
- postCount: number;
95
- postSlugs: string[];
96
- /** Confirmed recipients that would receive the digest. */
97
- recipientCount: number;
98
- /** Set when a real send would skip; absent when a send would go out. */
99
- skip?: DigestSkipReason;
100
- }
101
-
102
- async function countConfirmed(db: Queryable, tenantId: string, collection: string): Promise<number> {
103
- const row = await db.first<{ n: number }>(
104
- `SELECT COUNT(*) AS n FROM newsletter_subscribers
105
- WHERE tenant_id = ? AND collection = ? AND status = 'confirmed'`,
106
- tenantId, collection,
107
- );
108
- return Number(row?.n ?? 0);
109
- }
110
-
111
- /**
112
- * Steps (1)+(2) of the send flow, read-only: whether this period was already
113
- * sent, and the posts published since the last send. Shared verbatim by
114
- * {@link previewWeeklyDigest} and {@link sendWeeklyDigest} so the dry-run preview
115
- * can never diverge from what the real send computes.
116
- */
117
- async function selectNewPosts(
118
- deps: PreviewDeps,
119
- tenantId: string,
120
- collection: string,
121
- digestId: string,
122
- ): Promise<{ alreadySent: boolean; newPosts: BlogPostSummary[] }> {
123
- const existing = await deps.db.first<{ digest_id: string }>(
124
- `SELECT digest_id FROM newsletter_sends
125
- WHERE tenant_id = ? AND collection = ? AND digest_id = ?`,
126
- tenantId, collection, digestId,
127
- );
128
- if (existing) return { alreadySent: true, newPosts: [] };
129
-
130
- const lastSend = await deps.db.first<{ sent_at: string }>(
131
- `SELECT sent_at FROM newsletter_sends
132
- WHERE tenant_id = ? AND collection = ?
133
- ORDER BY sent_at DESC LIMIT 1`,
134
- tenantId, collection,
135
- );
136
- const sinceMs = lastSend ? new Date(lastSend.sent_at).getTime() : null;
137
- const posts = await deps.listPosts(tenantId, collection);
138
- const newPosts = posts.filter(
139
- (p) => sinceMs === null || new Date(p.publishedAt).getTime() > sinceMs,
140
- );
141
- return { alreadySent: false, newPosts };
142
- }
143
-
144
- /**
145
- * Compute what a weekly digest WOULD send this period — post count, post slugs,
146
- * and confirmed-recipient count — WITHOUT calling the ESP or writing any ledger
147
- * row. Backs the admin "Send digest" dry-run/confirm dialog.
148
- */
149
- export async function previewWeeklyDigest(
150
- tenantId: string,
151
- collection: string,
152
- deps: PreviewDeps,
153
- ): Promise<DigestPreview> {
154
- const now = deps.now?.() ?? new Date();
155
- const digestId = `${collection}-${isoWeekId(now)}`;
156
- const { alreadySent, newPosts } = await selectNewPosts(deps, tenantId, collection, digestId);
157
- const recipientCount = await countConfirmed(deps.db, tenantId, collection);
158
-
159
- let skip: DigestSkipReason | undefined;
160
- if (alreadySent) skip = "already-sent-this-period";
161
- else if (newPosts.length === 0) skip = "no-new-posts";
162
- else if (recipientCount === 0) skip = "no-subscribers";
163
-
164
- return {
165
- digestId,
166
- postCount: newPosts.length,
167
- postSlugs: newPosts.map((p) => p.slug),
168
- recipientCount,
169
- skip,
170
- };
171
- }
172
-
173
- /** ISO-8601 week-numbering id (`YYYY-Www`), Thursday-anchored. */
174
- export function isoWeekId(d: Date): string {
175
- const date = new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate()));
176
- const dayNum = (date.getUTCDay() + 6) % 7; // Mon=0 … Sun=6
177
- date.setUTCDate(date.getUTCDate() - dayNum + 3); // Thursday of this week
178
- const firstThursday = new Date(Date.UTC(date.getUTCFullYear(), 0, 4));
179
- const ftDayNum = (firstThursday.getUTCDay() + 6) % 7;
180
- firstThursday.setUTCDate(firstThursday.getUTCDate() - ftDayNum + 3);
181
- const week = 1 + Math.round((date.getTime() - firstThursday.getTime()) / (7 * 86400000));
182
- return `${date.getUTCFullYear()}-W${String(week).padStart(2, "0")}`;
183
- }
184
-
185
- function chunk<T>(items: T[], size: number): T[][] {
186
- const out: T[][] = [];
187
- for (let i = 0; i < items.length; i += size) out.push(items.slice(i, i + size));
188
- return out;
189
- }
190
-
191
- export async function sendWeeklyDigest(
192
- tenantId: string,
193
- collection: string,
194
- deps: SendDeps,
195
- ): Promise<SendResult> {
196
- const now = deps.now?.() ?? new Date();
197
- const nowIso = now.toISOString();
198
- const send = deps.sendBatch ?? realSendBatch;
199
- const digestId = `${collection}-${isoWeekId(now)}`;
200
-
201
- // (1)+(2) Idempotency + posts published since the last send (shared with the
202
- // dry-run preview so the two can never diverge).
203
- const { alreadySent, newPosts } = await selectNewPosts(deps, tenantId, collection, digestId);
204
- if (alreadySent) return { skipped: true, reason: "already-sent-this-period" };
205
- if (newPosts.length === 0) return { skipped: true, reason: "no-new-posts" };
206
-
207
- // (3) Confirmed recipients only.
208
- const subscribers = await deps.db.all<SubscriberRow>(
209
- `SELECT email, token FROM newsletter_subscribers
210
- WHERE tenant_id = ? AND collection = ? AND status = 'confirmed'`,
211
- tenantId, collection,
212
- );
213
- if (subscribers.length === 0) return { skipped: true, reason: "no-subscribers" };
214
-
215
- // (4) Build once, personalize the unsubscribe token per recipient, batch-send.
216
- const digestHtml = buildDigestHtml(tenantId, collection, newPosts, deps.config);
217
- const from = deps.config.fromName
218
- ? `${deps.config.fromName} <${deps.config.fromAddress}>`
219
- : deps.config.fromAddress;
220
- const subject = deps.config.fromName ? `${deps.config.fromName} — new this week` : "New this week";
221
-
222
- const emails: ResendEmail[] = subscribers.map((s) => {
223
- const unsubUrl = unsubscribeUrl(deps.config.canonicalBase, s.token);
224
- return {
225
- from,
226
- to: s.email,
227
- subject,
228
- html: digestHtml.split(UNSUBSCRIBE_TOKEN_PLACEHOLDER).join(s.token),
229
- reply_to: deps.config.replyTo ?? deps.config.fromAddress,
230
- headers: {
231
- // RFC 8058 one-click unsubscribe (Gmail/Yahoo bulk-sender requirement).
232
- "List-Unsubscribe": `<${unsubUrl}>`,
233
- "List-Unsubscribe-Post": "List-Unsubscribe=One-Click",
234
- },
235
- };
236
- });
237
-
238
- let sent = 0;
239
- const sentEmails: string[] = [];
240
- for (const batch of chunk(emails, RESEND_BATCH_LIMIT)) {
241
- const result = await send(deps.resendApiKey, batch);
242
- if (result.ok) {
243
- sent += batch.length;
244
- for (const e of batch) sentEmails.push(e.to as string);
245
- }
246
- }
247
-
248
- // (5) Record the ledger row (idempotency key) + stamp recipients.
249
- await deps.db.run(
250
- `INSERT OR IGNORE INTO newsletter_sends
251
- (tenant_id, collection, digest_id, post_slugs, recipient_count, sent_at)
252
- VALUES (?, ?, ?, ?, ?, ?)`,
253
- tenantId, collection, digestId,
254
- JSON.stringify(newPosts.map((p) => p.slug)), sent, nowIso,
255
- );
256
- for (const email of sentEmails) {
257
- await deps.db.run(
258
- `UPDATE newsletter_subscribers SET last_sent_at = ?
259
- WHERE tenant_id = ? AND collection = ? AND email = ?`,
260
- nowIso, tenantId, collection, email,
261
- );
262
- }
263
-
264
- return { sent, digestId };
265
- }
@@ -1,212 +0,0 @@
1
- /**
2
- * S1 — the social go-live hook + idempotency.
3
- *
4
- * WHERE IT FIRES: at the true go-live edge — after the tenant pipeline's publish job
5
- * flips a tenant's `live` channel to a freshly-shipped version and records the
6
- * release ledger. NOT on `POST /api/admin/blog`'s `publish` (which only opens a
7
- * candidate PR a human still promotes) and NOT on accept-to-preview
8
- * (`/api/changes/accept` → `integrate`, which only advances the `preview`
9
- * aggregate). Go-live is where a post's file actually becomes public, so it is the
10
- * only truthful "it went live" edge.
11
- *
12
- * WHAT IT DETECTS: a blog post that transitioned INTO a live-visible status — was
13
- * absent or not-live in the version live before this ship (`fromVersionId`), and
14
- * is live-visible in the version just promoted (`toVersionId`). Visibility is the
15
- * ONE chokepoint `isVisibleOnLive` (published / unlisted / due-scheduled), reused
16
- * so this never drifts from the render path.
17
- *
18
- * DISCIPLINE (mirrors `webhooks/emit.ts`): BEST-EFFORT and fire-and-forget — every
19
- * failure is logged and swallowed. A social outage must NEVER fail or roll back a
20
- * completed go-live.
21
- *
22
- * IDEMPOTENCY: a check-and-set posted-state key per `(tenant, collection, slug,
23
- * network)` fires each post AT MOST ONCE, so a re-ship / re-run never re-posts. The
24
- * transition guard also marks already-live posts as "primed" (key set, not fired)
25
- * so the first ship after this hook deploys does NOT retro-announce the tenant's
26
- * whole back-catalog.
27
- */
28
- import { isVisibleOnLive } from "../../content/blog/collection.js";
29
- import type { BlogPost, PostStatus } from "../../content/blog/types.js";
30
- import { notifyPostPublished } from "./notify.js";
31
-
32
- /**
33
- * The minimal version-read surface this hook needs — a structural subset of the
34
- * control-plane `SiteVersionStore`. Declared locally (not imported) so `lib/social`
35
- * stays inside the source-available renderer carve and never edges onto
36
- * `@tot/private-controlplane`; the caller (the control-plane-cluster orchestrator)
37
- * passes its real store in.
38
- */
39
- export interface VersionReadStore {
40
- getSiteVersion(
41
- tenantId: string,
42
- versionId: string,
43
- ): Promise<{ artifacts: Record<string, string> } | null>;
44
- getVersionContent(
45
- tenantId: string,
46
- path: string,
47
- versionId: string,
48
- ): Promise<string | Uint8Array | null>;
49
- }
50
-
51
- /**
52
- * The v1 idempotency network token — a single whole-post gate. S3/S4 replace this
53
- * with the real per-network id (`x` / `linkedin` / …) and iterate networks; the key
54
- * shape is ALREADY per-network so that extension needs no rework here.
55
- */
56
- export const SOCIAL_NETWORK = "social";
57
-
58
- /** The posted-once key for one post on one network. */
59
- export function socialPostedKey(
60
- tenantId: string,
61
- collection: string,
62
- slug: string,
63
- network: string,
64
- ): string {
65
- return `social:posted:${tenantId}:${collection}:${slug}:${network}`;
66
- }
67
-
68
- /** The minimal KV surface the idempotency store needs (TENANT_CACHE in prod). */
69
- export interface SocialIdempotencyKv {
70
- get(key: string): Promise<string | null>;
71
- put(key: string, value: string): Promise<void>;
72
- }
73
-
74
- // `.../content/<collection>/posts/<slug>.json` — capture collection + slug from a
75
- // version-manifest artifact path (robust to the leading `tenants/<id>/` prefix).
76
- const POST_PATH_RE = /(?:^|\/)content\/([a-z0-9][a-z0-9._-]*)\/posts\/([a-z0-9][a-z0-9-]*)\.json$/;
77
-
78
- function logDiag(fields: Record<string, unknown>): void {
79
- try {
80
- console.warn("[diag:social:golive]", JSON.stringify(fields));
81
- } catch {
82
- /* diagnostics must never break the caller */
83
- }
84
- }
85
-
86
- // Legacy/seeded post JSON may omit `status`; default it to "published" on load, the
87
- // same normalization `blog/collection.ts` applies so visibility matches the render path.
88
- function normalizeStatus(raw: unknown): PostStatus {
89
- return raw === "draft" || raw === "unlisted" || raw === "published" || raw === "scheduled"
90
- ? raw
91
- : "published";
92
- }
93
-
94
- // `contentVersionId` is the artifact's content hash (`manifest.artifacts[path]`) —
95
- // the version store keys blob content by that hash, not by the site version id.
96
- async function readPost(
97
- store: VersionReadStore,
98
- tenantId: string,
99
- artifactPath: string,
100
- contentVersionId: string,
101
- ): Promise<BlogPost | null> {
102
- const raw = await store.getVersionContent(tenantId, artifactPath, contentVersionId);
103
- if (typeof raw !== "string") return null;
104
- let parsed: unknown;
105
- try {
106
- parsed = JSON.parse(raw);
107
- } catch {
108
- return null;
109
- }
110
- if (parsed === null || typeof parsed !== "object") return null;
111
- const post = parsed as BlogPost;
112
- return { ...post, status: normalizeStatus((post as { status?: unknown }).status) };
113
- }
114
-
115
- export interface NotifyPostsWentLiveDeps {
116
- /** The version store the shipped tenant publishes to (a control-plane `SiteVersionStore`). */
117
- store: VersionReadStore;
118
- /** Idempotency store — TENANT_CACHE in prod. */
119
- kv: SocialIdempotencyKv;
120
- now?: () => string;
121
- /** Override the publish seam (tests + S3/S4 injection). Defaults to {@link notifyPostPublished}. */
122
- notify?: (tenantId: string, collection: string, slug: string, post: BlogPost) => Promise<void>;
123
- }
124
-
125
- export interface NotifyPostsWentLiveInput {
126
- tenantId: string;
127
- /** The version just promoted to `live`. */
128
- toVersionId: string;
129
- /** The version live immediately BEFORE this ship, or null on the first-ever ship. */
130
- fromVersionId: string | null;
131
- }
132
-
133
- /**
134
- * For each blog post that went live in `toVersionId`, fire {@link notifyPostPublished}
135
- * at most once. NEVER throws — the whole body is guarded so a completed go-live is
136
- * never failed or rolled back by this hook.
137
- */
138
- export async function notifyPostsWentLive(
139
- deps: NotifyPostsWentLiveDeps,
140
- input: NotifyPostsWentLiveInput,
141
- ): Promise<void> {
142
- try {
143
- const { store, kv } = deps;
144
- const now = (deps.now ?? (() => new Date().toISOString()))();
145
- const notify = deps.notify ?? notifyPostPublished;
146
-
147
- const toManifest = await store.getSiteVersion(input.tenantId, input.toVersionId);
148
- if (!toManifest) return;
149
- const fromManifest = input.fromVersionId
150
- ? await store.getSiteVersion(input.tenantId, input.fromVersionId)
151
- : null;
152
-
153
- for (const [artifactPath, contentHash] of Object.entries(toManifest.artifacts)) {
154
- const match = POST_PATH_RE.exec(artifactPath);
155
- if (!match) continue;
156
- const collection = match[1]!;
157
- const slug = match[2]!;
158
- const key = socialPostedKey(input.tenantId, collection, slug, SOCIAL_NETWORK);
159
-
160
- // Already posted (or primed) — skip before any content read (cheap steady state).
161
- let already: string | null = null;
162
- try {
163
- already = await kv.get(key);
164
- } catch {
165
- already = null;
166
- }
167
- if (already) continue;
168
-
169
- const post = await readPost(store, input.tenantId, artifactPath, contentHash);
170
- // Not live now (draft / not-yet-due scheduled) — do NOT set the key, so it is
171
- // re-checked on the ship that eventually takes it live.
172
- if (!post || !isVisibleOnLive(post, now)) continue;
173
-
174
- // Transition guard: if the post was ALREADY live in the prior version, this ship
175
- // did not take it live — PRIME the key (so we never re-read it) but do NOT notify.
176
- const prevHash = fromManifest?.artifacts[artifactPath];
177
- if (prevHash) {
178
- const prev = await readPost(store, input.tenantId, artifactPath, prevHash);
179
- if (prev && isVisibleOnLive(prev, now)) {
180
- try {
181
- await kv.put(key, now);
182
- } catch {
183
- /* best-effort prime */
184
- }
185
- continue;
186
- }
187
- }
188
-
189
- // Genuine went-live transition — fire once, THEN set the posted key. If notify
190
- // throws, the key is left unset so the next ship retries (at-least-check, at-most-post).
191
- try {
192
- await notify(input.tenantId, collection, slug, post);
193
- await kv.put(key, now);
194
- } catch (err) {
195
- logDiag({
196
- event: "notify_failed",
197
- tenantId: input.tenantId,
198
- collection,
199
- slug,
200
- error: (err as Error).message,
201
- });
202
- }
203
- }
204
- } catch (err) {
205
- logDiag({
206
- event: "hook_failed",
207
- tenantId: input.tenantId,
208
- toVersionId: input.toVersionId,
209
- error: (err as Error).message,
210
- });
211
- }
212
- }
@@ -1,32 +0,0 @@
1
- import type { BlogPost } from "../../content/blog/types.js";
2
-
3
- /** Swallow-and-log a soft failure — logging itself must never throw (mirrors `webhooks/emit.ts`). */
4
- function logDiag(fields: Record<string, unknown>): void {
5
- try {
6
- console.warn("[diag:social:notify]", JSON.stringify(fields));
7
- } catch {
8
- /* diagnostics must never break the caller */
9
- }
10
- }
11
-
12
- /**
13
- * The seam — the single call the go-live hook makes when a blog post
14
- * transitions INTO a live-visible state (see {@link notifyPostsWentLive}). This
15
- * ships the HOOK + the at-most-once idempotency key, NOT the network
16
- * last-mile: v1 is a no-op announcement (logs only).
17
- *
18
- * A `SocialPublisher` interface + X adapter, and per-`(tenant,network)`
19
- * config + encrypted token store, replace THIS body to compose a per-network
20
- * payload — title, canonical URL, excerpt, featured image, `categories[0]` →
21
- * hashtags — and POST it to each configured network's publish API. The signature
22
- * is deliberately per-POST; per-network fan-out and the per-network idempotency
23
- * key live one layer up in the hook, so extending to X + LinkedIn is additive.
24
- */
25
- export async function notifyPostPublished(
26
- tenantId: string,
27
- collection: string,
28
- slug: string,
29
- post: BlogPost,
30
- ): Promise<void> {
31
- logDiag({ event: "post_published", tenantId, collection, slug, title: post.title });
32
- }
@@ -1,171 +0,0 @@
1
- /**
2
- * Encrypted per-`(tenant, network)` outbound social OAuth token store
3
- * (social-autopost epic, S2). The one RETRIEVABLE secret store in the
4
- * storefront: unlike `app_credentials` (one-way `sha256Hex` for INBOUND auth),
5
- * these are access/refresh tokens we must REPLAY to X/LinkedIn, so they are
6
- * encrypted-at-rest and decrypted at post time — never hashed.
7
- *
8
- * Envelope encryption, Workers-native Web Crypto `AES-GCM` (no Node `crypto`):
9
- * - The data-encrypting step runs per write with a fresh random 96-bit IV.
10
- * - The key-encrypting key (KEK) is a Worker env binding (`SOCIAL_TOKEN_KEK`,
11
- * a base64-encoded 256-bit key), imported to a non-extractable `CryptoKey`.
12
- * It is NEVER a column — mirroring how every other real secret here is an
13
- * env binding, not row data (see the `social_tokens` note in schema-apps.ts).
14
- *
15
- * PURE over injected seams (a `Queryable` for D1, a `CryptoKey` for the KEK) so
16
- * the same code serves the real Worker bindings and an in-memory test — the
17
- * activity/store.ts convention. `resolveSocialTokenStore()` is the composition
18
- * root that wires the real bindings (mirrors `getDispatcher()`); it returns
19
- * `null` when either binding is absent so callers degrade rather than throw.
20
- */
21
- import type { Queryable } from "../../catalog/d1/catalog.js";
22
- import { readD1, readEnv } from "../../publication/shared/env.js";
23
-
24
- /** The decrypted token material we persist as one JSON blob under AES-GCM. */
25
- export interface SocialTokenPayload {
26
- accessToken: string;
27
- /** OAuth refresh token, when the network issues one (X app-passwords don't). */
28
- refreshToken?: string;
29
- /** Token expiry, ISO-8601. Absent for long-lived manual creds. */
30
- expiresAt?: string;
31
- }
32
-
33
- /** Injected seams a store operation runs over. */
34
- export interface SocialTokenStoreDeps {
35
- db: Queryable;
36
- /** AES-GCM key imported from the `SOCIAL_TOKEN_KEK` binding via {@link importKek}. */
37
- kek: CryptoKey;
38
- /** Clock seam (ISO-8601), overridable in tests. Defaults to `Date.now`. */
39
- now?: () => string;
40
- }
41
-
42
- const IV_BYTES = 12; // AES-GCM standard 96-bit nonce.
43
-
44
- function nowIso(deps: SocialTokenStoreDeps): string {
45
- return (deps.now ?? (() => new Date().toISOString()))();
46
- }
47
-
48
- function toBase64(bytes: Uint8Array): string {
49
- let s = "";
50
- for (const b of bytes) s += String.fromCharCode(b);
51
- return btoa(s);
52
- }
53
-
54
- function fromBase64(b64: string): Uint8Array<ArrayBuffer> {
55
- const s = atob(b64);
56
- const bytes = new Uint8Array(s.length);
57
- for (let i = 0; i < s.length; i++) bytes[i] = s.charCodeAt(i);
58
- return bytes;
59
- }
60
-
61
- /**
62
- * Import the raw `SOCIAL_TOKEN_KEK` secret (base64 of a 256-bit key) into a
63
- * non-extractable AES-GCM `CryptoKey`. Throws if the decoded key isn't 32 bytes
64
- * — a misprovisioned KEK must fail loudly at the composition root, not silently
65
- * produce unopenable ciphertext.
66
- */
67
- export async function importKek(rawBase64Key: string): Promise<CryptoKey> {
68
- const raw = fromBase64(rawBase64Key.trim());
69
- if (raw.length !== 32) {
70
- throw new Error(`SOCIAL_TOKEN_KEK must decode to 32 bytes (got ${raw.length})`);
71
- }
72
- return crypto.subtle.importKey("raw", raw, { name: "AES-GCM" }, false, ["encrypt", "decrypt"]);
73
- }
74
-
75
- /** Encrypt a token payload → `{ ciphertext, iv }` (both base64). Fresh IV each call. */
76
- export async function encryptTokenPayload(
77
- kek: CryptoKey,
78
- payload: SocialTokenPayload,
79
- ): Promise<{ ciphertext: string; iv: string }> {
80
- const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES));
81
- const plaintext = new TextEncoder().encode(JSON.stringify(payload));
82
- const ct = await crypto.subtle.encrypt({ name: "AES-GCM", iv }, kek, plaintext);
83
- return { ciphertext: toBase64(new Uint8Array(ct)), iv: toBase64(iv) };
84
- }
85
-
86
- /** Decrypt a stored `{ ciphertext, iv }` back to the token payload. */
87
- export async function decryptTokenPayload(
88
- kek: CryptoKey,
89
- ciphertext: string,
90
- iv: string,
91
- ): Promise<SocialTokenPayload> {
92
- const pt = await crypto.subtle.decrypt(
93
- { name: "AES-GCM", iv: fromBase64(iv) },
94
- kek,
95
- fromBase64(ciphertext),
96
- );
97
- return JSON.parse(new TextDecoder().decode(pt)) as SocialTokenPayload;
98
- }
99
-
100
- /**
101
- * Store (or overwrite) the token for `(tenantId, network)`. `INSERT OR REPLACE`
102
- * on the composite PK, so this is an idempotent upsert; `created_at` follows the
103
- * row's replacement (the natural key is the identity, not a birth timestamp).
104
- */
105
- export async function putSocialToken(
106
- deps: SocialTokenStoreDeps,
107
- tenantId: string,
108
- network: string,
109
- payload: SocialTokenPayload,
110
- ): Promise<void> {
111
- const { ciphertext, iv } = await encryptTokenPayload(deps.kek, payload);
112
- const at = nowIso(deps);
113
- await deps.db.run(
114
- `INSERT OR REPLACE INTO social_tokens
115
- (tenant_id, network, ciphertext, iv, expires_at, created_at, updated_at)
116
- VALUES (?,?,?,?,?,?,?)`,
117
- tenantId,
118
- network,
119
- ciphertext,
120
- iv,
121
- payload.expiresAt ?? null,
122
- at,
123
- at,
124
- );
125
- }
126
-
127
- /** Decrypt and return the token for `(tenantId, network)`, or `null` if none stored. */
128
- export async function getSocialToken(
129
- deps: SocialTokenStoreDeps,
130
- tenantId: string,
131
- network: string,
132
- ): Promise<SocialTokenPayload | null> {
133
- const row = await deps.db.first<{ ciphertext: string; iv: string }>(
134
- `SELECT ciphertext, iv FROM social_tokens WHERE tenant_id = ? AND network = ?`,
135
- tenantId,
136
- network,
137
- );
138
- if (!row) return null;
139
- return decryptTokenPayload(deps.kek, row.ciphertext, row.iv);
140
- }
141
-
142
- /**
143
- * Overwrite the token for `(tenantId, network)` with rotated material — the
144
- * explicit name for the refresh-token-rotation path. Same write as
145
- * {@link putSocialToken}; distinct export so a caller's intent reads at the seam.
146
- */
147
- export async function rotateSocialToken(
148
- deps: SocialTokenStoreDeps,
149
- tenantId: string,
150
- network: string,
151
- newPayload: SocialTokenPayload,
152
- ): Promise<void> {
153
- await putSocialToken(deps, tenantId, network, newPayload);
154
- }
155
-
156
- /**
157
- * Composition root: wire the real Worker bindings into a `SocialTokenStoreDeps`.
158
- * Returns `null` when the D1 binding or the `SOCIAL_TOKEN_KEK` secret is absent
159
- * (unprovisioned runtime / dev), so a caller degrades to "social posting
160
- * unavailable" rather than throwing — the KEK is a runtime secret that must be
161
- * provisioned out of band (`wrangler secret put SOCIAL_TOKEN_KEK`).
162
- */
163
- export async function resolveSocialTokenStore(): Promise<SocialTokenStoreDeps | null> {
164
- const [{ fromD1 }, d1, rawKek] = await Promise.all([
165
- import("../../catalog/d1/catalog.js"),
166
- readD1("STOREFRONT_APPS_DB"),
167
- readEnv("SOCIAL_TOKEN_KEK"),
168
- ]);
169
- if (!d1 || !rawKek) return null;
170
- return { db: fromD1(d1), kek: await importKek(rawKek) };
171
- }