@tokenoftrust/storefront-runner 7.3.1 → 7.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (414) hide show
  1. package/agency-kit/tools/lib/catalog-model/files.mjs +11 -4
  2. package/agency-kit/tools/lib/catalog-model/model.mjs +5 -1
  3. package/agency-kit/tools/lib/redirect-shadows.mjs +261 -0
  4. package/apps/storefront/astro.config.mjs +8 -2
  5. package/apps/storefront/package.json +1 -2
  6. package/apps/storefront/src/components/catalog/storefront/ProductCard.astro +20 -6
  7. package/apps/storefront/src/components/catalog/storefront/islands/ImageGallery.tsx +17 -6
  8. package/apps/storefront/src/components/compliance/storefront/islands/CheckoutComplianceGate.tsx +1 -32
  9. package/apps/storefront/src/config/compliance/rulesets.ts +1 -1
  10. package/apps/storefront/src/layouts/Layout.astro +17 -0
  11. package/apps/storefront/src/lib/access/auth/agentRoles.ts +20 -0
  12. package/apps/storefront/src/lib/access/auth/agentSessionGate.ts +147 -0
  13. package/apps/storefront/src/lib/access/auth/brokerAssertion.ts +67 -1
  14. package/apps/storefront/src/lib/access/auth/contactReaderAuthority.ts +39 -0
  15. package/apps/storefront/src/lib/access/auth/loginGate.ts +15 -17
  16. package/apps/storefront/src/lib/access/auth/session.ts +79 -0
  17. package/apps/storefront/src/lib/access/dashboard/staffAdmission.ts +5 -0
  18. package/apps/storefront/src/lib/access/dashboard/tenantSelection.ts +2 -0
  19. package/apps/storefront/src/lib/access/shared/capability.ts +14 -6
  20. package/apps/storefront/src/lib/access/shared/generated/capabilityCatalog.generated.ts +161 -0
  21. package/apps/storefront/src/lib/activity/activityScope.ts +36 -0
  22. package/apps/storefront/src/lib/activity/recordActivity.ts +23 -1
  23. package/apps/storefront/src/lib/activity/serverFanOut.ts +31 -0
  24. package/apps/storefront/src/lib/activity/store.ts +9 -3
  25. package/apps/storefront/src/lib/checkout/commerce/cardCartForm.ts +2 -0
  26. package/apps/storefront/src/lib/checkout/commerce/cartSession.ts +109 -12
  27. package/apps/storefront/src/lib/checkout/commerce/checkoutHandoffRoute.ts +53 -25
  28. package/apps/storefront/src/lib/checkout/commerce/finalCartAuthorization.ts +48 -6
  29. package/apps/storefront/src/lib/checkout/proposal/cartProposal.ts +388 -0
  30. package/apps/storefront/src/lib/checkout/proposal/listMatcher.ts +149 -0
  31. package/apps/storefront/src/lib/checkout/proposal/proposalRoutes.ts +447 -0
  32. package/apps/storefront/src/lib/checkout/proposal/reviewHtml.ts +100 -0
  33. package/apps/storefront/src/lib/compliance/browser/checkoutVerificationFlow.ts +26 -2
  34. package/apps/storefront/src/lib/content/shared/redirects.ts +21 -4
  35. package/apps/storefront/src/lib/publication/shared/edgeCache.ts +5 -2
  36. package/apps/storefront/src/lib/publication/shared/previewAnnotations/renderDecorator.ts +15 -8
  37. package/apps/storefront/src/lib/publication/shared/runtimeEnv.ts +1 -1
  38. package/apps/storefront/src/middleware/controlPlane.ts +15 -1
  39. package/apps/storefront/src/middleware/index.ts +40 -1
  40. package/apps/storefront/src/middleware/renderChain.ts +46 -33
  41. package/apps/storefront/src/pages/api/cart-proposal/confirm.ts +12 -0
  42. package/apps/storefront/src/pages/api/cart-proposal/review.ts +26 -0
  43. package/apps/storefront/src/pages/api/commerce/final-cart-authorization.ts +29 -6
  44. package/apps/storefront/src/pages/api/compliance/preflight.ts +25 -1
  45. package/apps/storefront/src/pages/products/[handle].astro +2 -15
  46. package/apps/storefront/tsconfig.astro.json +11 -0
  47. package/package.json +1 -1
  48. package/packages/public-runtime/src/activity/README.md +12 -0
  49. package/packages/public-runtime/src/activity/catalog.ts +7 -0
  50. package/packages/public-runtime/src/activity/event.ts +19 -0
  51. package/packages/public-runtime/src/activity/redaction.ts +31 -2
  52. package/packages/public-runtime/src/catalog-files.ts +3 -2
  53. package/packages/public-runtime/src/checkout-orders.ts +18 -19
  54. package/packages/public-runtime/src/checkout.ts +70 -0
  55. package/packages/public-runtime/src/compliance/evaluate.ts +60 -1
  56. package/packages/public-runtime/src/compliance/index.ts +1 -1
  57. package/packages/public-runtime/src/compliance/pact-report.ts +184 -3
  58. package/packages/public-runtime/src/compliance/profile.ts +268 -20
  59. package/packages/public-runtime/src/compliance/ruleset.ts +42 -0
  60. package/packages/public-runtime/src/customization-runtime.ts +1 -1
  61. package/packages/public-runtime/src/product.ts +9 -1
  62. package/packages/public-runtime/src/publication-content-redirects.ts +16 -3
  63. package/packages/public-runtime/tests/fixtures/compliance-decisions.golden.json +252 -52
  64. package/pnpm-lock.runner.yaml +0 -15
  65. package/scripts/tenant/materialize-tenant-content.mjs +3 -0
  66. package/scripts/tenant/validate.mjs +128 -0
  67. package/apps/storefront/dev-plugins/dev-publish.mjs +0 -55
  68. package/apps/storefront/drizzle.config.apps.ts +0 -13
  69. package/apps/storefront/integrations/preview-annotations-client-bundle.mjs +0 -80
  70. package/apps/storefront/migrations-apps/0000_fast_millenium_guard.sql +0 -129
  71. package/apps/storefront/migrations-apps/0001_woozy_lyja.sql +0 -22
  72. package/apps/storefront/migrations-apps/0002_good_switch.sql +0 -26
  73. package/apps/storefront/migrations-apps/0003_mute_marauders.sql +0 -12
  74. package/apps/storefront/migrations-apps/0004_deep_morph.sql +0 -36
  75. package/apps/storefront/migrations-apps/0005_common_mystique.sql +0 -23
  76. package/apps/storefront/migrations-apps/0006_broad_microchip.sql +0 -16
  77. package/apps/storefront/migrations-apps/0007_brave_outlaw_kid.sql +0 -15
  78. package/apps/storefront/migrations-apps/0008_blue_dazzler.sql +0 -11
  79. package/apps/storefront/migrations-apps/0009_bored_shinobi_shaw.sql +0 -15
  80. package/apps/storefront/migrations-apps/0010_ws4_verified_provider_measurement.sql +0 -35
  81. package/apps/storefront/migrations-apps/0011_dt_tracking_tenant_databases.sql +0 -23
  82. package/apps/storefront/migrations-apps/0012_test_destinations.sql +0 -29
  83. package/apps/storefront/migrations-apps/0013_publication_space_editorial.sql +0 -64
  84. package/apps/storefront/migrations-apps/0014_retire_candidate_ledger.sql +0 -12
  85. package/apps/storefront/migrations-apps/0015_merchant_calculation_settings.sql +0 -31
  86. package/apps/storefront/migrations-apps/0016_scrappy_commerce_contract.sql +0 -166
  87. package/apps/storefront/migrations-apps/0017_commerce_durable_projection.sql +0 -28
  88. package/apps/storefront/migrations-apps/0018_commerce_provider_cart_identity.sql +0 -13
  89. package/apps/storefront/migrations-apps/0019_commerce_source_authority.sql +0 -23
  90. package/apps/storefront/migrations-apps/0020_contact_messages.sql +0 -18
  91. package/apps/storefront/migrations-apps/0021_contact_vault.sql +0 -166
  92. package/apps/storefront/migrations-apps/0022_contact_vault_fields.sql +0 -342
  93. package/apps/storefront/migrations-apps/0023_principal_grant_contacts.sql +0 -15
  94. package/apps/storefront/migrations-apps/0024_order_contact_erasure_state.sql +0 -22
  95. package/apps/storefront/migrations-apps/0025_shipment_audit_order_lookup.sql +0 -2
  96. package/apps/storefront/migrations-apps/0026_fulfillment_assignment.sql +0 -44
  97. package/apps/storefront/migrations-apps/0027_app_contact_authority.sql +0 -70
  98. package/apps/storefront/migrations-apps/0028_app_jwk_and_candidates.sql +0 -133
  99. package/apps/storefront/migrations-apps/0029_inventory_locations_wms.sql +0 -38
  100. package/apps/storefront/migrations-apps/0030_assignment_split_shipments.sql +0 -149
  101. package/apps/storefront/migrations-apps/meta/0000_snapshot.json +0 -843
  102. package/apps/storefront/migrations-apps/meta/0001_snapshot.json +0 -990
  103. package/apps/storefront/migrations-apps/meta/0002_snapshot.json +0 -1160
  104. package/apps/storefront/migrations-apps/meta/0003_snapshot.json +0 -1235
  105. package/apps/storefront/migrations-apps/meta/0004_snapshot.json +0 -1474
  106. package/apps/storefront/migrations-apps/meta/0005_snapshot.json +0 -1617
  107. package/apps/storefront/migrations-apps/meta/0006_snapshot.json +0 -1716
  108. package/apps/storefront/migrations-apps/meta/0007_snapshot.json +0 -1812
  109. package/apps/storefront/migrations-apps/meta/0008_snapshot.json +0 -1881
  110. package/apps/storefront/migrations-apps/meta/0009_snapshot.json +0 -1979
  111. package/apps/storefront/migrations-apps/meta/_journal.json +0 -76
  112. package/apps/storefront/perf/README.md +0 -64
  113. package/apps/storefront/perf/assert-budgets.ts +0 -159
  114. package/apps/storefront/platform-reconcile-tenants.json +0 -3
  115. package/apps/storefront/playwright.config.ts +0 -23
  116. package/apps/storefront/public/js/dashboard-access-banner.js +0 -53
  117. package/apps/storefront/public/js/dashboard-apps.js +0 -183
  118. package/apps/storefront/public/js/dashboard-contact-capture.js +0 -52
  119. package/apps/storefront/public/js/dashboard-delegate.js +0 -167
  120. package/apps/storefront/public/js/dashboard-team.js +0 -356
  121. package/apps/storefront/public/js/dashboard-vendor-search.js +0 -115
  122. package/apps/storefront/src/components/content/storefront/AsyncStylesheet.astro +0 -26
  123. package/apps/storefront/src/components/integrations/storefront/WidgetFrame.astro +0 -34
  124. package/apps/storefront/src/config/adminTenantLookup.ts +0 -35
  125. package/apps/storefront/src/config/evidenceTenantRoster.ts +0 -25
  126. package/apps/storefront/src/config/staffProvisionProjection.ts +0 -24
  127. package/apps/storefront/src/config/storeName.ts +0 -34
  128. package/apps/storefront/src/lib/access/admin/README.md +0 -122
  129. package/apps/storefront/src/lib/access/admin/adminShell.ts +0 -281
  130. package/apps/storefront/src/lib/access/admin/envelope.ts +0 -9
  131. package/apps/storefront/src/lib/access/admin/viewmodels/settings.ts +0 -64
  132. package/apps/storefront/src/lib/access/auth/adminApiGuard.ts +0 -66
  133. package/apps/storefront/src/lib/access/auth/adminEntry.ts +0 -126
  134. package/apps/storefront/src/lib/access/auth/mcpClientAssertion.ts +0 -217
  135. package/apps/storefront/src/lib/access/auth/operatorSession.ts +0 -120
  136. package/apps/storefront/src/lib/access/dashboard/delegateGate.ts +0 -130
  137. package/apps/storefront/src/lib/access/dashboard/staffStoreEntry.ts +0 -150
  138. package/apps/storefront/src/lib/access/dashboard/staffVendorAccess.ts +0 -452
  139. package/apps/storefront/src/lib/access/dashboard/vendorQuery.ts +0 -61
  140. package/apps/storefront/src/lib/access/fixtures/settings.ts +0 -67
  141. package/apps/storefront/src/lib/access/fixtures/tenants.ts +0 -29
  142. package/apps/storefront/src/lib/access/notifications/magicLinkInviteEmail.ts +0 -62
  143. package/apps/storefront/src/lib/access/shared/grantContactLookup.ts +0 -97
  144. package/apps/storefront/src/lib/access/shared/principalGrants.ts +0 -775
  145. package/apps/storefront/src/lib/activity/alerts.ts +0 -426
  146. package/apps/storefront/src/lib/activity/candidateSubmitLease.ts +0 -87
  147. package/apps/storefront/src/lib/activity/changeActorAttribution.ts +0 -181
  148. package/apps/storefront/src/lib/activity/evidence/evidenceReference.ts +0 -32
  149. package/apps/storefront/src/lib/activity/fixtures/evidence.ts +0 -99
  150. package/apps/storefront/src/lib/activity/query.ts +0 -403
  151. package/apps/storefront/src/lib/activity/uiActor.ts +0 -152
  152. package/apps/storefront/src/lib/admin/services/mock/index.ts +0 -12
  153. package/apps/storefront/src/lib/assets/addons/catalog.ts +0 -60
  154. package/apps/storefront/src/lib/assets/addons/storeEntitlements.ts +0 -260
  155. package/apps/storefront/src/lib/assets/durableAssetsRoute.ts +0 -65
  156. package/apps/storefront/src/lib/assets/durableR2.ts +0 -473
  157. package/apps/storefront/src/lib/assets/durableR2Bindings.ts +0 -33
  158. package/apps/storefront/src/lib/automation/admin/viewmodels/aiWorkflows.ts +0 -65
  159. package/apps/storefront/src/lib/automation/ai/approvalMode.ts +0 -20
  160. package/apps/storefront/src/lib/automation/ai/askEnvelope.ts +0 -47
  161. package/apps/storefront/src/lib/automation/ai/audit.ts +0 -12
  162. package/apps/storefront/src/lib/automation/ai/operationalRuns.ts +0 -155
  163. package/apps/storefront/src/lib/automation/ai/recommendation.ts +0 -20
  164. package/apps/storefront/src/lib/automation/fixtures/aiWorkflows.ts +0 -59
  165. package/apps/storefront/src/lib/catalog/admin/catalogSettingsClient.ts +0 -250
  166. package/apps/storefront/src/lib/catalog/admin/catalogSettingsFields.ts +0 -134
  167. package/apps/storefront/src/lib/catalog/admin/catalogSettingsPreview.ts +0 -37
  168. package/apps/storefront/src/lib/catalog/admin/catalogSettingsPricingView.ts +0 -39
  169. package/apps/storefront/src/lib/catalog/admin/catalogSettingsRuleView.ts +0 -44
  170. package/apps/storefront/src/lib/catalog/admin/catalogSettingsSkuView.ts +0 -21
  171. package/apps/storefront/src/lib/catalog/admin/catalogSettingsState.ts +0 -132
  172. package/apps/storefront/src/lib/catalog/admin/productSetupPhoto.ts +0 -23
  173. package/apps/storefront/src/lib/catalog/admin/productsTabClient.ts +0 -193
  174. package/apps/storefront/src/lib/catalog/admin/services/catalogProducts.ts +0 -32
  175. package/apps/storefront/src/lib/catalog/admin/viewmodels/catalogProducts.ts +0 -164
  176. package/apps/storefront/src/lib/catalog/admin/viewmodels/products.ts +0 -267
  177. package/apps/storefront/src/lib/catalog/fixtures/products.ts +0 -105
  178. package/apps/storefront/src/lib/catalog/tot/syncState.ts +0 -111
  179. package/apps/storefront/src/lib/checkout/admin/checkoutStyleInput.ts +0 -172
  180. package/apps/storefront/src/lib/checkout/admin/checkoutStyleTarget.ts +0 -65
  181. package/apps/storefront/src/lib/checkout/browser/checkoutExciseForm.ts +0 -152
  182. package/apps/storefront/src/lib/checkout/browser/checkoutRequirementsForm.ts +0 -72
  183. package/apps/storefront/src/lib/checkout/browser/checkoutStyleForm.ts +0 -110
  184. package/apps/storefront/src/lib/checkout/browser/settingDraftActions.ts +0 -367
  185. package/apps/storefront/src/lib/checkout/commerce/checkoutSettings.ts +0 -246
  186. package/apps/storefront/src/lib/checkout/fixtures/checkoutSettings.ts +0 -77
  187. package/apps/storefront/src/lib/content/blog/markdown.ts +0 -174
  188. package/apps/storefront/src/lib/content/chrome/examples/tokenoftrust.chrome-assignments.example.json +0 -6
  189. package/apps/storefront/src/lib/content/chrome/examples/tokenoftrust.chrome.example.json +0 -79
  190. package/apps/storefront/src/lib/content/index.ts +0 -27
  191. package/apps/storefront/src/lib/content/the-build/readingTime.ts +0 -35
  192. package/apps/storefront/src/lib/content/the-build/toc.ts +0 -95
  193. package/apps/storefront/src/lib/customers/admin/viewmodels/customers.ts +0 -56
  194. package/apps/storefront/src/lib/customers/contactVault/blindIndex.ts +0 -28
  195. package/apps/storefront/src/lib/customers/contactVault/contactAudit.ts +0 -149
  196. package/apps/storefront/src/lib/customers/contactVault/dataKeys.ts +0 -283
  197. package/apps/storefront/src/lib/customers/contactVault/fieldEnvelope.ts +0 -88
  198. package/apps/storefront/src/lib/customers/contactVault/isolateMetrics.ts +0 -37
  199. package/apps/storefront/src/lib/customers/contactVault/kms.ts +0 -292
  200. package/apps/storefront/src/lib/customers/contactVault/retention.ts +0 -302
  201. package/apps/storefront/src/lib/customers/contactVault/retentionPolicy.ts +0 -290
  202. package/apps/storefront/src/lib/customers/contactVault/zip3.ts +0 -24
  203. package/apps/storefront/src/lib/customers/fixtures/customers.ts +0 -86
  204. package/apps/storefront/src/lib/developer-experience/admin/memoizeByEnvelope.ts +0 -27
  205. package/apps/storefront/src/lib/developer-experience/admin/seed.ts +0 -54
  206. package/apps/storefront/src/lib/developer-experience/dev/activityIngestToken.ts +0 -85
  207. package/apps/storefront/src/lib/developer-experience/dev/activityStore.ts +0 -82
  208. package/apps/storefront/src/lib/developer-experience/dev/ai-widget-client.js +0 -308
  209. package/apps/storefront/src/lib/developer-experience/dev/apiBase.ts +0 -17
  210. package/apps/storefront/src/lib/developer-experience/dev/cliSignInCode.ts +0 -124
  211. package/apps/storefront/src/lib/developer-experience/dev/cockpit/ask.ts +0 -49
  212. package/apps/storefront/src/lib/developer-experience/dev/cockpit/clickToSource.ts +0 -71
  213. package/apps/storefront/src/lib/developer-experience/dev/cockpit/copyCommand.ts +0 -227
  214. package/apps/storefront/src/lib/developer-experience/dev/cockpit/files.ts +0 -249
  215. package/apps/storefront/src/lib/developer-experience/dev/cockpit/hostedActivity.ts +0 -500
  216. package/apps/storefront/src/lib/developer-experience/dev/cockpit/infoPopover.ts +0 -12
  217. package/apps/storefront/src/lib/developer-experience/dev/cockpit/mcpCopy.ts +0 -34
  218. package/apps/storefront/src/lib/developer-experience/dev/cockpit/monitor.ts +0 -107
  219. package/apps/storefront/src/lib/developer-experience/dev/cockpit/stepper.ts +0 -116
  220. package/apps/storefront/src/lib/developer-experience/dev/cockpit/themeToggle.ts +0 -23
  221. package/apps/storefront/src/lib/developer-experience/dev/livePreview.ts +0 -77
  222. package/apps/storefront/src/lib/developer-experience/dev/obstacleStore.ts +0 -214
  223. package/apps/storefront/src/lib/developer-experience/dev/previewStatus.ts +0 -87
  224. package/apps/storefront/src/lib/developer-experience/dev/rendezvousBroker.ts +0 -226
  225. package/apps/storefront/src/lib/developer-experience/dev/runtimeStore.ts +0 -291
  226. package/apps/storefront/src/lib/developer-experience/dev/storeStatus.ts +0 -142
  227. package/apps/storefront/src/lib/developer-experience/dev/subjectReissue.ts +0 -67
  228. package/apps/storefront/src/lib/developer-experience/fixtures/regulated-commerce-truth/index.ts +0 -540
  229. package/apps/storefront/src/lib/developer-experience/fixtures/ws3-readonly-clone-preflight/index.ts +0 -495
  230. package/apps/storefront/src/lib/engagement/contact/contactMessages.ts +0 -671
  231. package/apps/storefront/src/lib/engagement/contact/messagesTabClient.ts +0 -175
  232. package/apps/storefront/src/lib/engagement/contact/submission.ts +0 -112
  233. package/apps/storefront/src/lib/engagement/messaging/messagesClient.ts +0 -149
  234. package/apps/storefront/src/lib/engagement/newsletter/digest.ts +0 -117
  235. package/apps/storefront/src/lib/engagement/newsletter/resendClient.ts +0 -79
  236. package/apps/storefront/src/lib/engagement/newsletter/send.ts +0 -265
  237. package/apps/storefront/src/lib/engagement/social/golive.ts +0 -212
  238. package/apps/storefront/src/lib/engagement/social/notify.ts +0 -32
  239. package/apps/storefront/src/lib/engagement/social/tokenStore.ts +0 -171
  240. package/apps/storefront/src/lib/fulfillment/admin/commerceDesk.ts +0 -180
  241. package/apps/storefront/src/lib/fulfillment/admin/commerceDeskRouting.ts +0 -45
  242. package/apps/storefront/src/lib/fulfillment/admin/viewmodels/fulfillment.ts +0 -1071
  243. package/apps/storefront/src/lib/fulfillment/appShipmentEvidence.ts +0 -271
  244. package/apps/storefront/src/lib/fulfillment/carrierEvidence.ts +0 -105
  245. package/apps/storefront/src/lib/fulfillment/commerceProjection.ts +0 -157
  246. package/apps/storefront/src/lib/fulfillment/commerceReadback.ts +0 -60
  247. package/apps/storefront/src/lib/fulfillment/commerceRecovery.ts +0 -84
  248. package/apps/storefront/src/lib/fulfillment/commerceRuntime.ts +0 -41
  249. package/apps/storefront/src/lib/fulfillment/fulfillmentService.ts +0 -2842
  250. package/apps/storefront/src/lib/fulfillment/readiness.ts +0 -217
  251. package/apps/storefront/src/lib/fulfillment/splitShipments.ts +0 -388
  252. package/apps/storefront/src/lib/fulfillment/syntheticPreviewOrders.ts +0 -292
  253. package/apps/storefront/src/lib/integrations/apps/appContactAuthority.ts +0 -27
  254. package/apps/storefront/src/lib/integrations/apps/appContactConsents.ts +0 -118
  255. package/apps/storefront/src/lib/integrations/apps/appInstallEnv.ts +0 -28
  256. package/apps/storefront/src/lib/integrations/apps/gtmMigrationDraft.ts +0 -103
  257. package/apps/storefront/src/lib/integrations/apps/inventoryWrite.ts +0 -906
  258. package/apps/storefront/src/lib/integrations/apps/orders/customerHash.ts +0 -28
  259. package/apps/storefront/src/lib/integrations/apps/orders/idempotency.ts +0 -100
  260. package/apps/storefront/src/lib/integrations/apps/reports/salesVelocityReport.ts +0 -96
  261. package/apps/storefront/src/lib/integrations/apps/routeParams.ts +0 -45
  262. package/apps/storefront/src/lib/integrations/webhooks/cloudflareQueueDispatcher.ts +0 -82
  263. package/apps/storefront/src/lib/integrations/webhooks/commercePayloads.ts +0 -159
  264. package/apps/storefront/src/lib/integrations/webhooks/deliveryEngine.ts +0 -379
  265. package/apps/storefront/src/lib/integrations/webhooks/deliveryMapper.ts +0 -34
  266. package/apps/storefront/src/lib/integrations/webhooks/deliveryStore.ts +0 -903
  267. package/apps/storefront/src/lib/integrations/webhooks/dispatcher.ts +0 -168
  268. package/apps/storefront/src/lib/integrations/webhooks/emit.ts +0 -245
  269. package/apps/storefront/src/lib/integrations/webhooks/events.ts +0 -105
  270. package/apps/storefront/src/lib/integrations/webhooks/getDispatcher.ts +0 -77
  271. package/apps/storefront/src/lib/integrations/webhooks/orderFulfilledClaim.ts +0 -75
  272. package/apps/storefront/src/lib/measurement/admin/analyticsRegionPolicy.ts +0 -151
  273. package/apps/storefront/src/lib/measurement/admin/analyticsRegionsClient.ts +0 -84
  274. package/apps/storefront/src/lib/measurement/admin/consentSettingsClient.ts +0 -113
  275. package/apps/storefront/src/lib/measurement/analytics/index.ts +0 -44
  276. package/apps/storefront/src/lib/measurement/attribution/attributionService.ts +0 -206
  277. package/apps/storefront/src/lib/measurement/attribution/orderConversionD1.ts +0 -150
  278. package/apps/storefront/src/lib/measurement/attribution/verifiedProviderMeasurement.ts +0 -118
  279. package/apps/storefront/src/lib/measurement/tracking/interactionCollector.ts +0 -205
  280. package/apps/storefront/src/lib/measurement/tracking/pruneRollup.ts +0 -260
  281. package/apps/storefront/src/lib/measurement/tracking/tenantReadAccess.ts +0 -138
  282. package/apps/storefront/src/lib/measurement/tracking-writeback/rewriteTrackingIds.ts +0 -175
  283. package/apps/storefront/src/lib/measurement/tracking-writeback/writebackCandidate.ts +0 -110
  284. package/apps/storefront/src/lib/observability/diag/capture.ts +0 -162
  285. package/apps/storefront/src/lib/observability/diag/consoleLine.ts +0 -76
  286. package/apps/storefront/src/lib/observability/diag/debugConsole.ts +0 -118
  287. package/apps/storefront/src/lib/observability/diag/debugMode.ts +0 -163
  288. package/apps/storefront/src/lib/observability/diag/debugWindow.ts +0 -111
  289. package/apps/storefront/src/lib/observability/diag/redact.ts +0 -17
  290. package/apps/storefront/src/lib/observability/diag/reference.ts +0 -148
  291. package/apps/storefront/src/lib/observability/diag/referenceStore.ts +0 -113
  292. package/apps/storefront/src/lib/observability/diag/report.ts +0 -110
  293. package/apps/storefront/src/lib/observability/diag/serverResponseTime.ts +0 -91
  294. package/apps/storefront/src/lib/observability/diag/session.ts +0 -93
  295. package/apps/storefront/src/lib/observability/monitoring/manifest.ts +0 -301
  296. package/apps/storefront/src/lib/observability/performance/lighthouseReport.ts +0 -109
  297. package/apps/storefront/src/lib/observability/performance/rumAlert.ts +0 -179
  298. package/apps/storefront/src/lib/orders/admin/orderActions.ts +0 -556
  299. package/apps/storefront/src/lib/orders/admin/orderClient.ts +0 -248
  300. package/apps/storefront/src/lib/orders/admin/orderSource.ts +0 -410
  301. package/apps/storefront/src/lib/orders/admin/services/orders.ts +0 -922
  302. package/apps/storefront/src/lib/orders/admin/viewmodels/orders.ts +0 -135
  303. package/apps/storefront/src/lib/orders/data/commerceCallerConfig.ts +0 -37
  304. package/apps/storefront/src/lib/orders/data/ledgerContractOrders.ts +0 -148
  305. package/apps/storefront/src/lib/orders/data/orderForwardReceiver.ts +0 -532
  306. package/apps/storefront/src/lib/orders/data/orderMapper.ts +0 -454
  307. package/apps/storefront/src/lib/orders/data/ordersStore.ts +0 -623
  308. package/apps/storefront/src/lib/orders/data/sourceAuthorityContract.ts +0 -380
  309. package/apps/storefront/src/lib/orders/data/sourceAuthorityStore.ts +0 -830
  310. package/apps/storefront/src/lib/orders/fixtures/orders.ts +0 -186
  311. package/apps/storefront/src/lib/orders/providers/foxyOrderClient.ts +0 -207
  312. package/apps/storefront/src/lib/orders/vault/appRecipientRead.ts +0 -222
  313. package/apps/storefront/src/lib/orders/vault/contactIntake.ts +0 -63
  314. package/apps/storefront/src/lib/orders/vault/contactRoutes.ts +0 -110
  315. package/apps/storefront/src/lib/orders/vault/kmsEnv.ts +0 -11
  316. package/apps/storefront/src/lib/orders/vault/orderContact.ts +0 -96
  317. package/apps/storefront/src/lib/orders/vault/orderContactVault.ts +0 -1427
  318. package/apps/storefront/src/lib/orders/vault/vault-test-support.ts +0 -258
  319. package/apps/storefront/src/lib/publication/d1/schema-apps.ts +0 -808
  320. package/apps/storefront/src/lib/publication/notifications/candidateConflictEmail.ts +0 -80
  321. package/apps/storefront/src/lib/publication/servingMode.ts +0 -52
  322. package/apps/storefront/src/lib/publication/shared/previewAnnotations/moduleAsset.ts +0 -65
  323. package/apps/storefront/src/lib/publication/shared/routedApiParam.ts +0 -38
  324. package/apps/storefront/src/lib/reporting/admin/viewmodels/reporting.ts +0 -34
  325. package/apps/storefront/src/lib/reporting/fixtures/reporting.ts +0 -51
  326. package/apps/storefront/src/lib/subscriptions/admin/viewmodels/subscriptions.ts +0 -106
  327. package/apps/storefront/src/lib/subscriptions/fixtures/subscriptions.ts +0 -398
  328. package/apps/storefront/src/pages/api/admin/activity-alerts.ts +0 -58
  329. package/apps/storefront/src/pages/api/admin/commerce-readiness.ts +0 -172
  330. package/apps/storefront/src/pages/api/admin/fulfillment/batches.ts +0 -59
  331. package/apps/storefront/src/pages/api/admin/fulfillment/orders/[id]/address.ts +0 -66
  332. package/apps/storefront/src/pages/api/admin/fulfillment/orders/[id].ts +0 -118
  333. package/apps/storefront/src/pages/api/admin/fulfillment/orders/contact-search.ts +0 -26
  334. package/apps/storefront/src/pages/api/admin/fulfillment/orders/contacts.ts +0 -22
  335. package/apps/storefront/src/pages/api/admin/interaction-insights.ts +0 -101
  336. package/apps/storefront/src/pages/api/admin/orders/[id].ts +0 -63
  337. package/apps/storefront/src/pages/api/admin/orders.ts +0 -65
  338. package/apps/storefront/src/pages/api/contact.ts +0 -144
  339. package/apps/storefront/src/scheduled/contactVaultSweep.ts +0 -113
  340. package/apps/storefront/src/styles/admin.css +0 -1161
  341. package/apps/storefront/test/pipeline/fake-preview-services.ts +0 -288
  342. package/apps/storefront/test/pipeline/harness.ts +0 -209
  343. package/apps/storefront/test/pipeline/intake-worker.mjs +0 -14
  344. package/apps/storefront/test/pipeline/matrix-faults.ts +0 -366
  345. package/apps/storefront/test/pipeline/pipeline-host.ts +0 -418
  346. package/apps/storefront/test/pipeline/pool-config.cjs +0 -85
  347. package/apps/storefront/test/pipeline/publish-kinds.ts +0 -279
  348. package/apps/storefront/test/pipeline/synthetic-job.ts +0 -303
  349. package/apps/storefront/test/pipeline-faults/matrix-lib.ts +0 -696
  350. package/apps/storefront/vitest.config.cts +0 -44
  351. package/apps/storefront/vitest.faults.config.cts +0 -13
  352. package/apps/storefront/vitest.workers.config.cts +0 -7
  353. package/packages/feedback/fixtures/v1/expected-findings.json +0 -16
  354. package/packages/feedback/fixtures/v1/feedback-action/invalid/carries-transport-credential.json +0 -14
  355. package/packages/feedback/fixtures/v1/feedback-action/invalid/control-char-in-description.json +0 -13
  356. package/packages/feedback/fixtures/v1/feedback-action/invalid/legacy-schema-version.json +0 -13
  357. package/packages/feedback/fixtures/v1/feedback-action/invalid/page-path-with-query.json +0 -14
  358. package/packages/feedback/fixtures/v1/feedback-action/invalid/title-too-short.json +0 -13
  359. package/packages/feedback/fixtures/v1/feedback-action/valid/element-problem.json +0 -33
  360. package/packages/feedback/fixtures/v1/feedback-action/valid/page-comment.json +0 -20
  361. package/packages/feedback/fixtures/v1/feedback-action/valid/region-improvement.json +0 -24
  362. package/packages/feedback/fixtures/v1/feedback-action/valid/text-selection-feature.json +0 -30
  363. package/packages/feedback/fixtures/v1/submission-receipt/invalid/accepted-at-not-utc.json +0 -9
  364. package/packages/feedback/fixtures/v1/submission-receipt/invalid/bad-feedback-id.json +0 -9
  365. package/packages/feedback/fixtures/v1/submission-receipt/invalid/legacy-contract-version.json +0 -9
  366. package/packages/feedback/fixtures/v1/submission-receipt/invalid/missing-replayed.json +0 -8
  367. package/packages/feedback/fixtures/v1/submission-receipt/valid/accepted.json +0 -9
  368. package/packages/feedback/fixtures/v1/submission-receipt/valid/fractional-seconds.json +0 -9
  369. package/packages/feedback/fixtures/v1/submission-receipt/valid/replayed.json +0 -9
  370. package/packages/feedback/fixtures/v1/target-evidence/invalid/page-kind-claims-structure.json +0 -6
  371. package/packages/feedback/fixtures/v1/target-evidence/invalid/path-too-deep.json +0 -17
  372. package/packages/feedback/fixtures/v1/target-evidence/invalid/relative-region-out-of-range.json +0 -11
  373. package/packages/feedback/fixtures/v1/target-evidence/invalid/selector-uses-class.json +0 -7
  374. package/packages/feedback/fixtures/v1/target-evidence/invalid/source-precision-without-anchor.json +0 -6
  375. package/packages/feedback/fixtures/v1/target-evidence/valid/element-structure.json +0 -21
  376. package/packages/feedback/fixtures/v1/target-evidence/valid/host-iframe.json +0 -14
  377. package/packages/feedback/fixtures/v1/target-evidence/valid/source-anchor.json +0 -12
  378. package/packages/feedback/fixtures/v1/target-evidence/valid/text-selection.json +0 -26
  379. package/packages/feedback/package.json +0 -35
  380. package/packages/feedback/scripts/build-player.mjs +0 -28
  381. package/packages/feedback/src/index.ts +0 -1
  382. package/packages/feedback/src/primitives/composer.ts +0 -639
  383. package/packages/feedback/src/primitives/dialog.ts +0 -263
  384. package/packages/feedback/src/primitives/hostAdapter.ts +0 -116
  385. package/packages/feedback/src/primitives/index.ts +0 -10
  386. package/packages/feedback/src/primitives/launcher.ts +0 -200
  387. package/packages/feedback/src/primitives/picker.ts +0 -663
  388. package/packages/feedback/src/primitives/redaction.ts +0 -204
  389. package/packages/feedback/src/primitives/selection.ts +0 -49
  390. package/packages/feedback/src/primitives/shiftAccelerator.ts +0 -160
  391. package/packages/feedback/src/primitives/styles.ts +0 -77
  392. package/packages/feedback/src/primitives/surface.ts +0 -124
  393. package/packages/feedback/src/primitives/target.ts +0 -293
  394. package/packages/feedback/src/tour/canonical.ts +0 -27
  395. package/packages/feedback/src/tour/index.ts +0 -3
  396. package/packages/feedback/src/tour/player/browser.ts +0 -5
  397. package/packages/feedback/src/tour/player/host.ts +0 -12
  398. package/packages/feedback/src/tour/player/index.ts +0 -205
  399. package/packages/feedback/src/tour/player/manifest.ts +0 -76
  400. package/packages/feedback/src/tour/player/player.css +0 -130
  401. package/packages/feedback/src/tour/player/resolver.ts +0 -12
  402. package/packages/feedback/src/tour/player/surface.ts +0 -295
  403. package/packages/feedback/src/tour/player/types.ts +0 -8
  404. package/packages/feedback/src/tour/resolve/core.ts +0 -267
  405. package/packages/feedback/src/tour/resolve/dom.ts +0 -115
  406. package/packages/feedback/src/tour/resolve/index.ts +0 -29
  407. package/packages/feedback/src/tour/sanitize.ts +0 -76
  408. package/packages/feedback/src/tour/schema.ts +0 -362
  409. package/packages/feedback/src/v1/guards.ts +0 -335
  410. package/packages/feedback/src/v1/index.ts +0 -3
  411. package/packages/feedback/src/v1/protectedSurfaces.ts +0 -32
  412. package/packages/feedback/src/v1/types.ts +0 -177
  413. package/packages/feedback/tsconfig.json +0 -9
  414. package/packages/feedback/vitest.config.cts +0 -21
@@ -1,1427 +0,0 @@
1
- /**
2
- * The order contact vault (migrations-apps/0022): every personal field of an order's contact is its
3
- * own AES-256-GCM ciphertext under the tenant's KMS-wrapped order-contact data key, held per field
4
- * group (identity, email, phone, ship, bill) by the declared retention rules. The row keyed by a
5
- * random fact_id is also the long-lived facts row: once its last group is cleared it is detached
6
- * from the order and keeps only month, zip3, region, country and totals.
7
- *
8
- * Every effect is one statement or one D1 batch, so a check and its write can never be split:
9
- * - seal: [new data-key rows] + conditional vault insert + marker + replay (both conditioned on the
10
- * vault row this command sealed) + key cleanup. Every refused or racing outcome commits nothing.
11
- * - read / list: the audit row commits (staff quota in the same statement) before any decrypt.
12
- * - app recipient read: the app-access audit row commits before contact state is read or anything
13
- * is decrypted, and only the ship group is opened.
14
- * - erase: audit, group clearing and detach commit together.
15
- * - purge: one clock reading; each page is one batch.
16
- *
17
- * - rotation: retire and replace due keys, recompute blind indexes under a retired kid (one
18
- * conditioned update per row), then delete unreferenced retired keys.
19
- *
20
- * Nothing here logs. Errors and outcomes carry fixed codes only; fact_id never leaves this module.
21
- */
22
- import type { Queryable, QueryStatement } from "../../catalog/d1/catalog.js";
23
- import type { OrderContactAvailability, OrderContactState } from "@tot/public-runtime";
24
- import { VaultKeyUnavailableError, type DataKeyPurpose, type EncryptionContext, type KmsClient } from "@/lib/customers/contactVault/kms.js";
25
- import {
26
- activeKey,
27
- cleanupStatement,
28
- deleteUnreferencedRetiredKeys,
29
- keyForKid,
30
- keyRowRestore,
31
- rotateDueKeys,
32
- type ActiveDataKey,
33
- } from "@/lib/customers/contactVault/dataKeys.js";
34
- import { openField, sealField, type FieldBinding } from "@/lib/customers/contactVault/fieldEnvelope.js";
35
- import { blindIndex, normalizeEmail, normalizePhone } from "@/lib/customers/contactVault/blindIndex.js";
36
- import {
37
- TERMINAL_AT_SQL,
38
- isGroupReadable,
39
- previewDeleteAt,
40
- readInstant,
41
- readStampInstant,
42
- rederiveGroup,
43
- sealRetention,
44
- } from "@/lib/customers/contactVault/retention.js";
45
- import { GROUPS, RETENTION_POLICY, applicableRules, rulesForTenant, type Group, type RetentionPolicy } from "@/lib/customers/contactVault/retentionPolicy.js";
46
- import { zip3 } from "@/lib/customers/contactVault/zip3.js";
47
- import {
48
- AUDIT_RECORD_IDS_MAX,
49
- admitAudit,
50
- auditRecordIds,
51
- auditStatement,
52
- batchAuditStatement,
53
- type AuditStatement,
54
- type ContactActor,
55
- type VaultStage,
56
- } from "@/lib/customers/contactVault/contactAudit.js";
57
- import { orderContactPlaintext, sameOrderContact, type ContactAddress, type OrderContactCommand } from "./orderContact.js";
58
-
59
- export type { Group } from "@/lib/customers/contactVault/retentionPolicy.js";
60
-
61
- // ---------------------------------------------------------------------------------------------
62
- // Layout
63
- // ---------------------------------------------------------------------------------------------
64
-
65
- interface GroupLayout {
66
- sealed: readonly string[];
67
- bidx: string | null;
68
- plain: readonly string[];
69
- }
70
-
71
- const LAYOUT: Readonly<Record<Group, GroupLayout>> = {
72
- identity: { sealed: ["name_ct", "company_ct"], bidx: null, plain: [] },
73
- email: { sealed: ["email_ct"], bidx: "email_bidx", plain: [] },
74
- phone: { sealed: ["phone_ct"], bidx: "phone_bidx", plain: [] },
75
- ship: { sealed: ["ship_name_ct", "ship_company_ct", "ship_line1_ct", "ship_line2_ct"], bidx: null, plain: ["ship_city", "ship_postal_code"] },
76
- bill: { sealed: ["bill_name_ct", "bill_company_ct", "bill_line1_ct", "bill_line2_ct"], bidx: null, plain: ["bill_city", "bill_postal_code"] },
77
- };
78
-
79
- const ERASURE_BITS: Readonly<Record<Group, number>> = { identity: 1, email: 2, phone: 4, ship: 8, bill: 16 };
80
-
81
- function groupColumns(group: Group): string[] {
82
- const layout = LAYOUT[group];
83
- return [...layout.sealed, ...(layout.bidx ? [layout.bidx] : []), ...layout.plain];
84
- }
85
-
86
- /** SQL: the group still holds any personal value. */
87
- function hasDataSql(group: Group, alias = ""): string {
88
- return `(${groupColumns(group).map((column) => `${alias}${column} IS NOT NULL`).join(" OR ")})`;
89
- }
90
-
91
- /** SQL SET list nulling every personal column of the groups. */
92
- function clearSql(groups: readonly Group[]): string {
93
- return groups.flatMap(groupColumns).map((column) => `${column} = NULL`).join(", ");
94
- }
95
-
96
- const ALL_EMPTY_SQL = GROUPS.map((group) => `NOT ${hasDataSql(group)}`).join(" AND ");
97
-
98
- /** Detach: only the unlinked facts remain (fact_id, tenant, stage, month, totals, zip3, region, country). */
99
- const DETACH_SET_SQL = [
100
- "order_id", "ship_city", "ship_postal_code", "bill_city", "bill_postal_code", "order_kid", "bidx_kid",
101
- "sealed_jti", "sealed_at", "erased_at", "time_scale", "rule_version",
102
- ...GROUPS.flatMap((group) => [`${group}_ceiling`, `${group}_expires_at`, `${group}_floor_until`, `${group}_rule`]),
103
- ].map((column) => `${column} = NULL`).join(", ");
104
-
105
- /**
106
- * Normalization statements over `scopeSql` (with `scopeParams`): clear bidx_kid once both indexes
107
- * are gone, then detach a publication row whose last group is gone. Preview rows stay linked until
108
- * the purge deletes them whole with their marker at placed_at + the cutoff.
109
- */
110
- function normalizeStatements(scopeSql: string, scopeParams: readonly unknown[]): QueryStatement[] {
111
- return [
112
- {
113
- sql: `UPDATE order_contact_vault SET bidx_kid = NULL
114
- WHERE ${scopeSql} AND bidx_kid IS NOT NULL AND email_bidx IS NULL AND phone_bidx IS NULL`,
115
- params: [...scopeParams],
116
- },
117
- {
118
- sql: `UPDATE order_contact_vault SET ${DETACH_SET_SQL}
119
- WHERE ${scopeSql} AND stage = 'publication' AND order_id IS NOT NULL AND ${ALL_EMPTY_SQL}`,
120
- params: [...scopeParams],
121
- },
122
- ];
123
- }
124
-
125
- type VaultRow = Record<string, unknown>;
126
-
127
- function text(row: VaultRow, column: string): string | null {
128
- const value = row[column];
129
- return typeof value === "string" ? value : null;
130
- }
131
-
132
- function rowHasData(row: VaultRow, group: Group): boolean {
133
- return groupColumns(group).some((column) => row[column] !== null && row[column] !== undefined);
134
- }
135
-
136
- const ORDER_KEY = "order-contact" as const;
137
- const BIDX_KEY = "blind-index" as const;
138
-
139
- function keyContext(tenantId: string, stage: VaultStage, purpose: DataKeyPurpose): EncryptionContext {
140
- return { tenantId, stage, purpose };
141
- }
142
-
143
- function fieldBinding(tenantId: string, stage: VaultStage, factId: string, kid: string, column: string, ceiling: string): FieldBinding {
144
- return { purpose: ORDER_KEY, field: column.replace(/_ct$/, ""), tenantId, stage, recordId: factId, kid, notAfter: ceiling };
145
- }
146
-
147
- function requireBatch(db: Queryable): NonNullable<Queryable["batch"]> {
148
- if (!db.batch) throw new Error("D1 batch is unavailable");
149
- return db.batch.bind(db);
150
- }
151
-
152
- function randomHex128(): string {
153
- return [...crypto.getRandomValues(new Uint8Array(16))].map((byte) => byte.toString(16).padStart(2, "0")).join("");
154
- }
155
-
156
- function sqlLiteral(value: string): string {
157
- return `'${value.replace(/'/g, "''")}'`;
158
- }
159
-
160
- // ---------------------------------------------------------------------------------------------
161
- // Order snapshot and effective expiry
162
- // ---------------------------------------------------------------------------------------------
163
-
164
- interface OrderSnapshot {
165
- placedAtRaw: unknown;
166
- fulfillmentState: unknown;
167
- terminalAtRaw: string | null;
168
- placedAt: Date;
169
- terminalAt: Date | null;
170
- }
171
-
172
- function isTerminalState(state: unknown): boolean {
173
- return state === "handed_off" || state === "cancelled";
174
- }
175
-
176
- /** Read placed_at and the stamp-tolerant terminal time; refusal codes when either is unreadable. */
177
- function orderTimes(placedAtRaw: unknown, fulfillmentState: unknown, terminalAtRaw: unknown): OrderSnapshot | "order-time-unreadable" {
178
- const placedAt = readInstant(placedAtRaw);
179
- if (!placedAt) return "order-time-unreadable";
180
- const terminal = isTerminalState(fulfillmentState) ? readStampInstant(terminalAtRaw) : null;
181
- if (isTerminalState(fulfillmentState) && !terminal) return "order-time-unreadable";
182
- return {
183
- placedAtRaw,
184
- fulfillmentState,
185
- terminalAtRaw: typeof terminalAtRaw === "string" ? terminalAtRaw : null,
186
- placedAt,
187
- terminalAt: terminal,
188
- };
189
- }
190
-
191
- /**
192
- * Re-derivation applies only non-floor rules (floors come from the row's immutable floor_until), so
193
- * the tenant's regulated class is taken as true: any regulated non-floor rule then counts, which can
194
- * only lengthen the derived expiry, never shorten it below what the rules require.
195
- */
196
- function rederivationRules(tenantId: string, shipCountry: string | null, shipRegion: string | null, policy: RetentionPolicy) {
197
- return applicableRules(tenantId, { shipCountry, shipRegion, regulated: true }, policy);
198
- }
199
-
200
- /** Each group's effective expiry now (shrink-only re-derivation of the row's values), or null. */
201
- function effectiveExpiries(
202
- row: VaultRow,
203
- tenantId: string,
204
- stage: VaultStage,
205
- order: { placedAt: Date; terminalAt: Date | null },
206
- policy: RetentionPolicy,
207
- ): Record<Group, string | null> {
208
- const rules = rederivationRules(tenantId, text(row, "ship_country"), text(row, "ship_region"), policy);
209
- const timeScale = Number(row.time_scale);
210
- const out = {} as Record<Group, string | null>;
211
- for (const group of GROUPS) {
212
- const ceiling = text(row, `${group}_ceiling`);
213
- const expiresAt = text(row, `${group}_expires_at`);
214
- out[group] = ceiling && expiresAt
215
- ? rederiveGroup({
216
- group, ceiling, expiresAt, floorUntil: text(row, `${group}_floor_until`), timeScale, stage,
217
- placedAt: order.placedAt, terminalAt: order.terminalAt, rules, policy,
218
- })
219
- : null;
220
- }
221
- return out;
222
- }
223
-
224
- interface GroupState {
225
- sealed: boolean;
226
- readable: boolean;
227
- expiresAt: string | null;
228
- }
229
-
230
- function groupStates(
231
- row: VaultRow,
232
- tenantId: string,
233
- stage: VaultStage,
234
- order: { placedAt: Date; terminalAt: Date | null },
235
- now: Date,
236
- policy: RetentionPolicy,
237
- ): Record<Group, GroupState> {
238
- const effective = effectiveExpiries(row, tenantId, stage, order, policy);
239
- const pastCutoff = stage === "preview" && now.getTime() >= Date.parse(previewDeleteAt(order.placedAt, policy));
240
- const out = {} as Record<Group, GroupState>;
241
- for (const group of GROUPS) {
242
- const sealed = rowHasData(row, group);
243
- const expiresAt = effective[group];
244
- out[group] = {
245
- sealed,
246
- expiresAt,
247
- readable: sealed && !pastCutoff && isGroupReadable(now, expiresAt, text(row, `${group}_ceiling`)),
248
- };
249
- }
250
- return out;
251
- }
252
-
253
- // ---------------------------------------------------------------------------------------------
254
- // Opening
255
- // ---------------------------------------------------------------------------------------------
256
-
257
- export interface ReadableContact {
258
- customer?: { name?: string; email?: string; phone?: string };
259
- shipTo?: ContactAddress;
260
- billTo?: ContactAddress;
261
- }
262
-
263
- export interface GroupView {
264
- expiresAt: string;
265
- rule: string | null;
266
- }
267
-
268
- /**
269
- * Open every sealed field of the given groups. Null when any field fails to authenticate (moved,
270
- * swapped or tampered) or a required value is missing: the record then reads as not found.
271
- */
272
- async function openGroups(
273
- key: CryptoKey,
274
- row: VaultRow,
275
- tenantId: string,
276
- stage: VaultStage,
277
- groups: readonly Group[],
278
- ): Promise<ReadableContact | null> {
279
- const factId = text(row, "fact_id");
280
- const kid = text(row, "order_kid");
281
- if (!factId || !kid) return null;
282
- const opened = new Map<string, string>();
283
- for (const group of groups) {
284
- const ceiling = text(row, `${group}_ceiling`);
285
- if (!ceiling) return null;
286
- for (const column of LAYOUT[group].sealed) {
287
- const sealed = text(row, column);
288
- if (sealed === null) continue;
289
- const value = await openField(key, fieldBinding(tenantId, stage, factId, kid, column, ceiling), sealed);
290
- if (value === null) return null;
291
- opened.set(column, value);
292
- }
293
- }
294
- const contact: ReadableContact = {};
295
- const customer: { name?: string; email?: string; phone?: string } = {};
296
- if (groups.includes("identity")) {
297
- const name = opened.get("name_ct");
298
- if (name === undefined) return null;
299
- customer.name = name;
300
- }
301
- if (groups.includes("email")) {
302
- const email = opened.get("email_ct");
303
- if (email === undefined) return null;
304
- customer.email = email;
305
- }
306
- if (groups.includes("phone")) {
307
- const phone = opened.get("phone_ct");
308
- if (phone === undefined) return null;
309
- customer.phone = phone;
310
- }
311
- if (Object.keys(customer).length > 0) contact.customer = customer;
312
- for (const [group, prefix, member] of [["ship", "ship", "shipTo"], ["bill", "bill", "billTo"]] as const) {
313
- if (!groups.includes(group)) continue;
314
- const line1 = opened.get(`${prefix}_line1_ct`);
315
- const city = text(row, `${prefix}_city`);
316
- const country = text(row, `${prefix}_country`);
317
- if (line1 === undefined || city === null || country === null) return null;
318
- const address: Record<string, string> = { line1, city, country };
319
- const name = opened.get(`${prefix}_name_ct`);
320
- const company = opened.get(`${prefix}_company_ct`);
321
- const line2 = opened.get(`${prefix}_line2_ct`);
322
- const region = text(row, `${prefix}_region`);
323
- const postalCode = text(row, `${prefix}_postal_code`);
324
- if (name !== undefined) address.name = name;
325
- if (company !== undefined) address.company = company;
326
- if (line2 !== undefined) address.line2 = line2;
327
- if (region !== null) address.region = region;
328
- if (postalCode !== null) address.postalCode = postalCode;
329
- contact[member] = address as unknown as ContactAddress;
330
- }
331
- return contact;
332
- }
333
-
334
- // ---------------------------------------------------------------------------------------------
335
- // Seal
336
- // ---------------------------------------------------------------------------------------------
337
-
338
- export type SealOutcome =
339
- | { ok: true; status: 200; duplicate: boolean }
340
- | {
341
- ok: false;
342
- status: 401 | 409 | 410 | 503;
343
- reason: "replay" | "order-unknown" | "order-time-unreadable" | "contact-conflict" | "contact-expired" | "contact-erased" | "vault-key-unavailable";
344
- };
345
-
346
- export interface SealInput {
347
- tenantId: string;
348
- stage: VaultStage;
349
- command: OrderContactCommand;
350
- issuer: string;
351
- jti: string;
352
- /** isRegulatedTenant for the routed tenant. */
353
- regulated: boolean;
354
- now: Date;
355
- policy?: RetentionPolicy;
356
- /** Key material from {@link prepareOrderContactKeys}; every attempt seals under it without reading the active key. */
357
- keys?: PreparedOrderContactKeys;
358
- }
359
-
360
- interface SealSnapshot extends OrderSnapshot {
361
- marked: boolean;
362
- }
363
-
364
- async function sealSnapshot(db: Queryable, tenantId: string, stage: VaultStage, orderId: string): Promise<SealSnapshot | "order-unknown" | "order-time-unreadable"> {
365
- const order = await db.first<{ placed_at: unknown; fulfillment_state: unknown; terminal_at: unknown; marked: number }>(
366
- `SELECT o.placed_at, o.fulfillment_state, (${TERMINAL_AT_SQL}) AS terminal_at,
367
- EXISTS (SELECT 1 FROM order_contact_markers m WHERE m.tenant_id = o.tenant_id AND m.stage = o.stage AND m.order_id = o.order_id) AS marked
368
- FROM scrappy_commerce_orders o WHERE o.tenant_id = ? AND o.stage = ? AND o.order_id = ?`,
369
- tenantId, stage, orderId, tenantId, stage, orderId,
370
- );
371
- if (!order) return "order-unknown";
372
- const times = orderTimes(order.placed_at, order.fulfillment_state, order.terminal_at);
373
- if (times === "order-time-unreadable") return times;
374
- return { ...times, marked: Number(order.marked) === 1 };
375
- }
376
-
377
- const SEALED_VALUES: ReadonlyArray<[string, (command: OrderContactCommand) => string | undefined]> = [
378
- ["name_ct", (c) => c.customer.name],
379
- ["company_ct", () => undefined],
380
- ["email_ct", (c) => c.customer.email],
381
- ["phone_ct", (c) => c.customer.phone],
382
- ["ship_name_ct", (c) => c.shipTo.name],
383
- ["ship_company_ct", (c) => c.shipTo.company],
384
- ["ship_line1_ct", (c) => c.shipTo.line1],
385
- ["ship_line2_ct", (c) => c.shipTo.line2],
386
- ["bill_name_ct", (c) => c.billTo.name],
387
- ["bill_company_ct", (c) => c.billTo.company],
388
- ["bill_line1_ct", (c) => c.billTo.line1],
389
- ["bill_line2_ct", (c) => c.billTo.line2],
390
- ];
391
-
392
- function groupOfColumn(column: string): Group {
393
- for (const group of GROUPS) if (LAYOUT[group].sealed.includes(column)) return group;
394
- throw new Error("vault layout");
395
- }
396
-
397
- function placedMonth(placedAt: Date): string {
398
- return `${placedAt.getUTCFullYear()}${String(placedAt.getUTCMonth() + 1).padStart(2, "0")}`;
399
- }
400
-
401
- /** Order-contact key material opened before a caller's own writes; see {@link prepareOrderContactKeys}. */
402
- export interface PreparedOrderContactKeys {
403
- readonly order: ActiveDataKey;
404
- readonly bidx: ActiveDataKey;
405
- /** Puts each key's row back, retired, if rotation swept it before the seal; first in the seal batch. */
406
- readonly restore: readonly QueryStatement[];
407
- }
408
-
409
- /**
410
- * Open both order-contact keys for this tenant and stage and make them durable, for a caller that must
411
- * refuse before its own writes when the vault cannot seal. Returns null when a key cannot be opened or
412
- * generated, leaving no key row of its own behind. Otherwise any newly generated key is stored (the
413
- * insert yields to an active key another writer stored first, which is opened instead) and the
414
- * returned material goes to {@link sealOrderContact} as `keys`: every seal attempt uses it without
415
- * reading the active key or calling KMS, and its batch first restores a key row rotation retired and
416
- * swept in between, so neither a KMS outage nor a rotation after the caller's writes stops the seal.
417
- */
418
- export async function prepareOrderContactKeys(
419
- db: Queryable, kms: KmsClient, tenantId: string, stage: VaultStage, now: Date,
420
- ): Promise<PreparedOrderContactKeys | null> {
421
- const orderCtx = keyContext(tenantId, stage, ORDER_KEY);
422
- const bidxCtx = keyContext(tenantId, stage, BIDX_KEY);
423
- let order: ActiveDataKey;
424
- let bidx: ActiveDataKey;
425
- try {
426
- order = await activeKey(db, kms, orderCtx, now);
427
- bidx = await activeKey(db, kms, bidxCtx, now);
428
- } catch (error) {
429
- if (error instanceof VaultKeyUnavailableError) return null;
430
- throw error;
431
- }
432
- const generated = ([[orderCtx, order], [bidxCtx, bidx]] as const).filter(([, key]) => key.pending.length > 0);
433
- const refuse = async (): Promise<null> => {
434
- if (generated.length > 0) await requireBatch(db)(generated.map(([ctx, key]) => unreferencedKeyCleanup(ctx, key.kid)));
435
- return null;
436
- };
437
- if (generated.length > 0) {
438
- await requireBatch(db)(generated.flatMap(([, key]) => key.pending));
439
- try {
440
- order = await storedKey(db, kms, orderCtx, order, now);
441
- bidx = await storedKey(db, kms, bidxCtx, bidx, now);
442
- } catch (error) {
443
- if (!(error instanceof VaultKeyUnavailableError)) throw error;
444
- return refuse();
445
- }
446
- }
447
- const orderRestore = await keyRowRestore(db, orderCtx, order.kid, now);
448
- const bidxRestore = await keyRowRestore(db, bidxCtx, bidx.kid, now);
449
- if (!orderRestore || !bidxRestore) return refuse();
450
- return { order, bidx, restore: [orderRestore, bidxRestore] };
451
- }
452
-
453
- /** The key to seal under after storing `mine`: itself when its insert landed, else the active winner. */
454
- async function storedKey(db: Queryable, kms: KmsClient, ctx: EncryptionContext, mine: ActiveDataKey, now: Date): Promise<ActiveDataKey> {
455
- if (mine.pending.length === 0) return mine;
456
- const active = await db.first<{ kid: string }>(
457
- `SELECT kid FROM contact_vault_data_keys WHERE tenant_id = ? AND stage = ? AND purpose = ? AND retired_at IS NULL`,
458
- ctx.tenantId, ctx.stage, ctx.purpose,
459
- );
460
- if (active?.kid === mine.kid) return { kid: mine.kid, key: mine.key, pending: [] };
461
- return activeKey(db, kms, ctx, now);
462
- }
463
-
464
- /** Removes `kid` when no order-contact record (or, for the blind-index key, contact message) names it. */
465
- function unreferencedKeyCleanup(ctx: EncryptionContext, kid: string): QueryStatement {
466
- const { tenantId, stage } = ctx;
467
- return ctx.purpose === ORDER_KEY
468
- ? cleanupStatement(ctx, kid,
469
- `SELECT 1 FROM order_contact_vault WHERE tenant_id = ? AND stage = ? AND order_kid = ?`, [tenantId, stage, kid])
470
- : cleanupStatement(ctx, kid,
471
- `SELECT 1 FROM order_contact_vault WHERE tenant_id = ? AND stage = ? AND bidx_kid = ?
472
- UNION ALL SELECT 1 FROM contact_messages WHERE tenant_id = ? AND stage = ? AND bidx_kid = ?`,
473
- [tenantId, stage, kid, tenantId, stage, kid]);
474
- }
475
-
476
- /** Seal one order's contact from a verified contact command. */
477
- export async function sealOrderContact(db: Queryable, kms: KmsClient, input: SealInput): Promise<SealOutcome> {
478
- try {
479
- return await sealAttempt(db, kms, input, 3);
480
- } catch (error) {
481
- if (error instanceof VaultKeyUnavailableError) return { ok: false, status: 503, reason: "vault-key-unavailable" };
482
- throw error;
483
- }
484
- }
485
-
486
- async function replayed(db: Queryable, tenantId: string, stage: VaultStage, issuer: string, jti: string): Promise<boolean> {
487
- return (await db.first(
488
- `SELECT 1 AS seen FROM scrappy_caller_replay WHERE tenant_id = ? AND stage = ? AND issuer = ? AND jti = ?`,
489
- tenantId, stage, issuer, jti,
490
- )) !== null;
491
- }
492
-
493
- async function sealAttempt(db: Queryable, kms: KmsClient, input: SealInput, attempts: number): Promise<SealOutcome> {
494
- const { tenantId, stage, command, issuer, jti, now } = input;
495
- const policy = input.policy ?? RETENTION_POLICY;
496
- const orderId = command.orderId;
497
- const nowIso = now.toISOString();
498
- const sealedJti = `${issuer}:${jti}`;
499
- if (await replayed(db, tenantId, stage, issuer, jti)) return { ok: false, status: 401, reason: "replay" };
500
- const snapshot = await sealSnapshot(db, tenantId, stage, orderId);
501
- if (snapshot === "order-unknown") return { ok: false, status: 409, reason: "order-unknown" };
502
- if (snapshot === "order-time-unreadable") return { ok: false, status: 409, reason: "order-time-unreadable" };
503
- const existing = await classifyExisting(db, kms, input, snapshot, sealedJti, policy);
504
- if (existing) return existing;
505
-
506
- const retention = await sealRetention({
507
- stage, placedAt: snapshot.placedAt, terminalAt: snapshot.terminalAt,
508
- shipCountry: command.shipTo.country, shipRegion: command.shipTo.region ?? null,
509
- regulated: input.regulated, tenantId, now, policy,
510
- });
511
- if (retention.kind === "refused") {
512
- return retention.reason === "order-time-unreadable"
513
- ? { ok: false, status: 409, reason: "order-time-unreadable" }
514
- : { ok: false, status: 410, reason: "contact-expired" };
515
- }
516
-
517
- const orderCtx = keyContext(tenantId, stage, ORDER_KEY);
518
- const bidxCtx = keyContext(tenantId, stage, BIDX_KEY);
519
- const orderKey = input.keys?.order ?? await activeKey(db, kms, orderCtx, now);
520
- const bidxKey = input.keys?.bidx ?? await activeKey(db, kms, bidxCtx, now);
521
-
522
- const factId = randomHex128();
523
- // A group whose expiry has already passed is never written: only live groups are sealed.
524
- const live = (group: Group): boolean => retention.groups[group].expiresAt > nowIso;
525
- const ifLive = <T>(group: Group, value: T): T | null => (live(group) ? value : null);
526
- const columns: Array<[string, unknown]> = [
527
- ["fact_id", factId], ["tenant_id", tenantId], ["stage", stage], ["order_id", orderId],
528
- ["placed_month", placedMonth(snapshot.placedAt)],
529
- ["ship_region", command.shipTo.region ?? null], ["ship_country", command.shipTo.country],
530
- ["ship_zip3", zip3(command.shipTo.postalCode, command.shipTo.country)],
531
- ["bill_region", command.billTo.region ?? null], ["bill_country", command.billTo.country],
532
- ["bill_zip3", zip3(command.billTo.postalCode, command.billTo.country)],
533
- ["time_scale", retention.timeScale], ["rule_version", retention.ruleVersion],
534
- ["order_kid", orderKey.kid], ["bidx_kid", bidxKey.kid], ["sealed_at", nowIso], ["sealed_jti", sealedJti],
535
- ["ship_city", ifLive("ship", command.shipTo.city)], ["ship_postal_code", ifLive("ship", command.shipTo.postalCode ?? null)],
536
- ["bill_city", ifLive("bill", command.billTo.city)], ["bill_postal_code", ifLive("bill", command.billTo.postalCode ?? null)],
537
- ];
538
- for (const [column, pick] of SEALED_VALUES) {
539
- const value = pick(command);
540
- const group = groupOfColumn(column);
541
- columns.push([
542
- column,
543
- value === undefined || !live(group)
544
- ? null
545
- : await sealField(orderKey.key, fieldBinding(tenantId, stage, factId, orderKey.kid, column, retention.groups[group].ceiling), value),
546
- ]);
547
- }
548
- const email = live("email") ? normalizeEmail(command.customer.email) : null;
549
- const phone = live("phone") ? normalizePhone(command.customer.phone) : null;
550
- columns.push(["email_bidx", email === null ? null : await blindIndex(bidxKey.key, email)]);
551
- columns.push(["phone_bidx", phone === null ? null : await blindIndex(bidxKey.key, phone)]);
552
- if (email === null && phone === null) columns.find(([column]) => column === "bidx_kid")![1] = null;
553
- let latest = "";
554
- for (const group of GROUPS) {
555
- const held = retention.groups[group];
556
- columns.push([`${group}_ceiling`, held.ceiling], [`${group}_expires_at`, held.expiresAt], [`${group}_floor_until`, held.floorUntil], [`${group}_rule`, held.rule]);
557
- if (held.expiresAt > latest) latest = held.expiresAt;
558
- }
559
-
560
- const vaultRowSql = `SELECT 1 FROM order_contact_vault WHERE tenant_id = ? AND stage = ? AND order_id = ? AND sealed_jti = ?`;
561
- const vaultRowParams = [tenantId, stage, orderId, sealedJti];
562
- const statements: QueryStatement[] = [
563
- ...(input.keys?.restore ?? []),
564
- ...orderKey.pending,
565
- ...bidxKey.pending,
566
- {
567
- sql: `INSERT INTO order_contact_vault (${columns.map(([column]) => column).join(", ")}, currency, order_total_minor, item_count)
568
- SELECT ${columns.map(() => "?").join(", ")}, o.currency, o.amount_minor,
569
- (SELECT SUM(a.quantity) FROM scrappy_allocations a WHERE a.tenant_id = o.tenant_id AND a.stage = o.stage AND a.order_id = o.order_id)
570
- FROM scrappy_commerce_orders o
571
- WHERE o.tenant_id = ? AND o.stage = ? AND o.order_id = ? AND o.placed_at IS ? AND o.fulfillment_state IS ?
572
- AND (${TERMINAL_AT_SQL}) IS ?
573
- AND NOT EXISTS (SELECT 1 FROM order_contact_markers m WHERE m.tenant_id = ? AND m.stage = ? AND m.order_id = ?)
574
- AND NOT EXISTS (SELECT 1 FROM order_contact_vault v WHERE v.tenant_id = ? AND v.stage = ? AND v.order_id = ?)
575
- AND EXISTS (SELECT 1 FROM contact_vault_data_keys k WHERE k.tenant_id = ? AND k.stage = ? AND k.purpose = ? AND k.kid = ?)
576
- AND EXISTS (SELECT 1 FROM contact_vault_data_keys k WHERE k.tenant_id = ? AND k.stage = ? AND k.purpose = ? AND k.kid = ?)
577
- AND ? < ?
578
- ON CONFLICT DO NOTHING`,
579
- params: [
580
- ...columns.map(([, value]) => value),
581
- tenantId, stage, orderId, snapshot.placedAtRaw, snapshot.fulfillmentState,
582
- tenantId, stage, orderId, snapshot.terminalAtRaw,
583
- tenantId, stage, orderId,
584
- tenantId, stage, orderId,
585
- tenantId, stage, ORDER_KEY, orderKey.kid,
586
- tenantId, stage, BIDX_KEY, bidxKey.kid,
587
- nowIso, latest,
588
- ],
589
- },
590
- {
591
- sql: `INSERT INTO order_contact_markers (tenant_id, stage, order_id)
592
- SELECT ?, ?, ? WHERE EXISTS (${vaultRowSql})
593
- ON CONFLICT DO NOTHING`,
594
- params: [tenantId, stage, orderId, ...vaultRowParams],
595
- },
596
- {
597
- sql: `INSERT INTO scrappy_caller_replay (tenant_id, stage, issuer, jti, seen_at)
598
- SELECT ?, ?, ?, ?, ? WHERE EXISTS (${vaultRowSql})`,
599
- params: [tenantId, stage, issuer, jti, nowIso, ...vaultRowParams],
600
- },
601
- ];
602
- if (orderKey.pending.length > 0) statements.push(unreferencedKeyCleanup(orderCtx, orderKey.kid));
603
- if (bidxKey.pending.length > 0) statements.push(unreferencedKeyCleanup(bidxCtx, bidxKey.kid));
604
- try {
605
- await requireBatch(db)(statements);
606
- } catch (error) {
607
- // The only conflict the batch can raise is the replay key: this jti committed concurrently
608
- // elsewhere. Anything else is a fault the sender must retry, never a replay.
609
- if (await replayed(db, tenantId, stage, issuer, jti)) return { ok: false, status: 401, reason: "replay" };
610
- throw error;
611
- }
612
- const again = await sealSnapshot(db, tenantId, stage, orderId);
613
- if (again === "order-unknown") return { ok: false, status: 409, reason: "order-unknown" };
614
- if (again === "order-time-unreadable") return { ok: false, status: 409, reason: "order-time-unreadable" };
615
- const after = await classifyExisting(db, kms, input, again, sealedJti, policy);
616
- if (after) return after;
617
- // Nothing committed: the order's retention snapshot or the active key changed underneath. Re-read
618
- // and re-seal, bounded.
619
- if (attempts > 1) return sealAttempt(db, kms, input, attempts - 1);
620
- throw new Error("contact-retention-changed");
621
- }
622
-
623
- /**
624
- * Classify an order that already has a linked vault row or a marker, or null when it has neither.
625
- * A linked row with every group sealed and readable answers duplicate or conflict; one with any
626
- * group cleared or expired, or a marker without a linked row, answers 410 and never refills.
627
- */
628
- async function classifyExisting(
629
- db: Queryable,
630
- kms: KmsClient,
631
- input: SealInput,
632
- snapshot: SealSnapshot,
633
- sealedJti: string,
634
- policy: RetentionPolicy,
635
- ): Promise<SealOutcome | null> {
636
- const { tenantId, stage, command, now } = input;
637
- const row = await db.first<VaultRow>(
638
- `SELECT * FROM order_contact_vault WHERE tenant_id = ? AND stage = ? AND order_id = ?`,
639
- tenantId, stage, command.orderId,
640
- );
641
- if (!row) return snapshot.marked ? { ok: false, status: 410, reason: "contact-expired" } : null;
642
- // This command's own seal (the replay row committed with it, so this is only ever the post-batch read).
643
- if (row.sealed_jti === sealedJti) return { ok: true, status: 200, duplicate: false };
644
- const states = groupStates(row, tenantId, stage, snapshot, now, policy);
645
- if (GROUPS.some((group) => !states[group].readable)) {
646
- return { ok: false, status: 410, reason: row.erased_at ? "contact-erased" : "contact-expired" };
647
- }
648
- const kid = text(row, "order_kid");
649
- const key = kid ? await keyForKid(db, kms, keyContext(tenantId, stage, ORDER_KEY), kid) : null;
650
- if (!key) return { ok: false, status: 503, reason: "vault-key-unavailable" };
651
- const stored = await openGroups(key, row, tenantId, stage, GROUPS);
652
- return stored !== null && sameOrderContact(stored, orderContactPlaintext(command))
653
- ? { ok: true, status: 200, duplicate: true }
654
- : { ok: false, status: 409, reason: "contact-conflict" };
655
- }
656
-
657
- // ---------------------------------------------------------------------------------------------
658
- // Read and list
659
- // ---------------------------------------------------------------------------------------------
660
-
661
- export type ReadOutcome =
662
- | { ok: true; contact: ReadableContact; expiresAt: string; groups: Partial<Record<Group, GroupView>> }
663
- | { ok: false; status: 410; reason: "contact-expired" }
664
- | { ok: false; status: 404 | 429 | 503; reason: "not-found" | "quota" | "audit-unavailable" | "vault-key-unavailable" };
665
-
666
- /** TERMINAL_AT_SQL correlated to the order row aliased `alias` instead of bound parameters. */
667
- function correlatedTerminalSql(alias: string): string {
668
- const sql = TERMINAL_AT_SQL.replace(
669
- "tenant_id = ? AND stage = ? AND order_id = ?",
670
- `tenant_id = ${alias}.tenant_id AND stage = ${alias}.stage AND order_id = ${alias}.order_id`,
671
- );
672
- if (sql === TERMINAL_AT_SQL || sql.includes("?")) throw new Error("vault: terminal-time SQL shape changed");
673
- return sql;
674
- }
675
-
676
- const ORDER_JOIN_SELECT = `SELECT v.*, o.placed_at AS order_placed_at, o.fulfillment_state AS order_fulfillment_state,
677
- (${correlatedTerminalSql("o")}) AS order_terminal_at
678
- FROM scrappy_commerce_orders o
679
- JOIN order_contact_vault v ON v.tenant_id = o.tenant_id AND v.stage = o.stage AND v.order_id = o.order_id`;
680
-
681
- const AVAILABILITY_GROUPS = ["identity", "email", "ship"] as const;
682
- const AVAILABILITY_CHUNK_SIZE = 80;
683
-
684
- /** Structural envelope presence only; authentication belongs to an audited contact read. */
685
- function envelopePresentSql(column: string): string {
686
- return `(typeof(${column}) = 'text' AND length(${column}) >= 40 AND length(${column}) % 4 = 0
687
- AND rtrim(${column}, '=') NOT GLOB '*[^A-Za-z0-9+/]*'
688
- AND length(${column}) - length(rtrim(${column}, '=')) <= 2)`;
689
- }
690
-
691
- function completeGroupSql(group: typeof AVAILABILITY_GROUPS[number]): string {
692
- const required = group === "identity" ? "name_ct" : group === "email" ? "email_ct" : "ship_line1_ct";
693
- const encrypted = LAYOUT[group].sealed.map((column) => column === required
694
- ? envelopePresentSql(`v.${column}`)
695
- : `(v.${column} IS NULL OR ${envelopePresentSql(`v.${column}`)})`);
696
- if (group === "ship") {
697
- encrypted.push(...["ship_city", "ship_country"].map((column) => `(typeof(v.${column}) = 'text' AND length(trim(v.${column})) > 0)`));
698
- }
699
- return `(${encrypted.join(" AND ")})`;
700
- }
701
-
702
- const AVAILABILITY_SELECT = `SELECT o.order_id, o.placed_at AS order_placed_at,
703
- o.fulfillment_state AS order_fulfillment_state, (${correlatedTerminalSql("o")}) AS order_terminal_at,
704
- v.order_id IS NOT NULL AS vault_present,
705
- COALESCE((SELECT m.erased_groups FROM order_contact_markers m
706
- WHERE m.tenant_id = o.tenant_id AND m.stage = o.stage AND m.order_id = o.order_id), 0) AS erased_groups,
707
- EXISTS (SELECT 1 FROM order_contact_markers m
708
- WHERE m.tenant_id = o.tenant_id AND m.stage = o.stage AND m.order_id = o.order_id) AS marked,
709
- EXISTS (SELECT 1 FROM contact_vault_data_keys k
710
- WHERE k.tenant_id = v.tenant_id AND k.stage = v.stage AND k.purpose = 'order-contact' AND k.kid = v.order_kid
711
- AND typeof(k.wrapped_key) = 'text' AND length(trim(k.wrapped_key)) > 0
712
- AND typeof(k.kms_key_arn) = 'text' AND length(trim(k.kms_key_arn)) > 0) AS key_present,
713
- v.time_scale, v.ship_country, v.ship_region,
714
- ${AVAILABILITY_GROUPS.flatMap((group) => [
715
- // Sentinel columns let the shared retention reader see presence without selecting values.
716
- `CASE WHEN ${hasDataSql(group, "v.")} THEN 1 END AS ${LAYOUT[group].sealed[0]}`,
717
- `${completeGroupSql(group)} AS ${group}_complete`,
718
- ...["ceiling", "expires_at", "floor_until"].map((suffix) => `v.${group}_${suffix}`),
719
- ]).join(",\n ")}
720
- FROM scrappy_commerce_orders o
721
- LEFT JOIN order_contact_vault v ON v.tenant_id = o.tenant_id AND v.stage = o.stage AND v.order_id = o.order_id`;
722
-
723
- function uniformAvailability(state: OrderContactState): OrderContactAvailability {
724
- return { identity: state, email: state, shipTo: state };
725
- }
726
-
727
- function contactAvailability(row: VaultRow, input: {
728
- tenantId: string; stage: VaultStage; now: Date; policy: RetentionPolicy;
729
- }): OrderContactAvailability {
730
- const erased = (group: Group): boolean => (Number(row.erased_groups) & ERASURE_BITS[group]) !== 0;
731
- if (Number(row.vault_present) !== 1) {
732
- const missing = (group: Group): OrderContactState => erased(group) ? "erased" : Number(row.marked) === 1 ? "expired" : "absent";
733
- return { identity: missing("identity"), email: missing("email"), shipTo: missing("ship") };
734
- }
735
- const times = orderTimes(row.order_placed_at, row.order_fulfillment_state, row.order_terminal_at);
736
- if (times === "order-time-unreadable" || !Number.isFinite(input.now.getTime())) return uniformAvailability("unreadable");
737
- const states = groupStates(row, input.tenantId, input.stage, times, input.now, input.policy);
738
- const state = (group: typeof AVAILABILITY_GROUPS[number]): OrderContactState => {
739
- const current = states[group];
740
- if (!current.sealed && erased(group)) return "erased";
741
- if (!current.expiresAt) return "unreadable";
742
- if (!isGroupReadable(input.now, current.expiresAt, text(row, `${group}_ceiling`)) ||
743
- (input.stage === "preview" && input.now.getTime() >= Date.parse(previewDeleteAt(times.placedAt, input.policy)))) return "expired";
744
- if (!current.sealed) return "absent";
745
- if (Number(row.key_present) !== 1 || Number(row[`${group}_complete`]) !== 1) return "unreadable";
746
- return current.readable ? "present" : "unreadable";
747
- };
748
- return { identity: state("identity"), email: state("email"), shipTo: state("ship") };
749
- }
750
-
751
- /** Retained contact presence for a bounded order set; no decrypt, audit write, or private values. */
752
- export async function readOrderContactAvailability(
753
- db: { all<T extends Record<string, unknown>>(sql: string, ...params: unknown[]): Promise<T[]> },
754
- input: { tenantId: string; stage: VaultStage; orderIds: readonly string[]; now: Date; policy?: RetentionPolicy },
755
- ): Promise<ReadonlyMap<string, OrderContactAvailability>> {
756
- const orderIds = [...new Set(input.orderIds)];
757
- const result = new Map(orderIds.map((id) => [id, uniformAvailability("absent")]));
758
- const policy = input.policy ?? RETENTION_POLICY;
759
- try {
760
- for (let start = 0; start < orderIds.length; start += AVAILABILITY_CHUNK_SIZE) {
761
- const chunk = orderIds.slice(start, start + AVAILABILITY_CHUNK_SIZE);
762
- const rows = await db.all<VaultRow>(
763
- `${AVAILABILITY_SELECT} WHERE o.tenant_id = ? AND o.stage = ? AND o.order_id IN (${chunk.map(() => "?").join(", ")})`,
764
- input.tenantId, input.stage, ...chunk,
765
- );
766
- for (const row of rows) {
767
- const id = text(row, "order_id");
768
- if (id !== null && chunk.includes(id)) result.set(id, contactAvailability(row, { ...input, policy }));
769
- }
770
- }
771
- return result;
772
- } catch {
773
- return new Map(orderIds.map((id) => [id, uniformAvailability("unreadable")]));
774
- }
775
- }
776
-
777
- interface Viewable {
778
- groups: Group[];
779
- views: Partial<Record<Group, GroupView>>;
780
- expiresAt: string;
781
- }
782
-
783
- /** The groups of a joined row readable now, or null when none is (or the order times are unreadable). */
784
- function viewable(row: VaultRow, tenantId: string, stage: VaultStage, now: Date, policy: RetentionPolicy): Viewable | null {
785
- const times = orderTimes(row.order_placed_at, row.order_fulfillment_state, row.order_terminal_at);
786
- if (times === "order-time-unreadable") return null;
787
- const states = groupStates(row, tenantId, stage, times, now, policy);
788
- const groups = GROUPS.filter((group) => states[group].readable);
789
- if (groups.length === 0) return null;
790
- const views: Partial<Record<Group, GroupView>> = {};
791
- let earliest: string | null = null;
792
- for (const group of groups) {
793
- const ceiling = text(row, `${group}_ceiling`)!;
794
- const effective = states[group].expiresAt!;
795
- const expiresAt = effective < ceiling ? effective : ceiling;
796
- views[group] = { expiresAt, rule: text(row, `${group}_rule`) };
797
- if (earliest === null || expiresAt < earliest) earliest = expiresAt;
798
- }
799
- return { groups, views, expiresAt: earliest! };
800
- }
801
-
802
- /** True when a preview order is at or past placed_at + the preview cutoff (nothing is admitted then). */
803
- async function pastPreviewCutoff(db: Queryable, tenantId: string, stage: VaultStage, orderId: string, now: Date, policy: RetentionPolicy): Promise<boolean> {
804
- if (stage !== "preview") return false;
805
- const order = await db.first<{ placed_at: unknown }>(
806
- `SELECT placed_at FROM scrappy_commerce_orders WHERE tenant_id = ? AND stage = ? AND order_id = ?`, tenantId, stage, orderId,
807
- );
808
- const placedAt = order ? readInstant(order.placed_at) : null;
809
- return placedAt !== null && now.getTime() >= Date.parse(previewDeleteAt(placedAt, policy));
810
- }
811
-
812
- /**
813
- * Read one order's contact: only the groups readable now. A preview order at or past its cutoff
814
- * answers 410 with zero writes; otherwise the audit row commits before any decrypt.
815
- */
816
- export async function readOrderContact(
817
- db: Queryable,
818
- kms: KmsClient,
819
- input: { tenantId: string; stage: VaultStage; orderId: string; actor: ContactActor; auditId: string; now: Date; policy?: RetentionPolicy },
820
- ): Promise<ReadOutcome> {
821
- const { tenantId, stage, orderId, actor, auditId, now } = input;
822
- const policy = input.policy ?? RETENTION_POLICY;
823
- if (await pastPreviewCutoff(db, tenantId, stage, orderId, now, policy)) return { ok: false, status: 410, reason: "contact-expired" };
824
- const admitted = await admitAudit(db, auditStatement({
825
- auditId, tenantId, stage, recordKind: "order-contact", recordId: orderId, actor, action: "read", now,
826
- }));
827
- if (admitted === "quota") return { ok: false, status: 429, reason: "quota" };
828
- if (admitted === "unavailable") return { ok: false, status: 503, reason: "audit-unavailable" };
829
- const row = await db.first<VaultRow>(`${ORDER_JOIN_SELECT} WHERE o.tenant_id = ? AND o.stage = ? AND o.order_id = ?`, tenantId, stage, orderId);
830
- if (!row) return { ok: false, status: 404, reason: "not-found" };
831
- const view = viewable(row, tenantId, stage, now, policy);
832
- if (!view) return { ok: false, status: 404, reason: "not-found" };
833
- try {
834
- const kid = text(row, "order_kid");
835
- const key = kid ? await keyForKid(db, kms, keyContext(tenantId, stage, ORDER_KEY), kid) : null;
836
- if (!key) return { ok: false, status: 404, reason: "not-found" };
837
- const contact = await openGroups(key, row, tenantId, stage, view.groups);
838
- if (!contact) return { ok: false, status: 404, reason: "not-found" };
839
- return { ok: true, contact, expiresAt: view.expiresAt, groups: view.views };
840
- } catch (error) {
841
- if (error instanceof VaultKeyUnavailableError) return { ok: false, status: 503, reason: "vault-key-unavailable" };
842
- throw error;
843
- }
844
- }
845
-
846
- export type ShipRecipientOutcome =
847
- | { ok: true; shipTo: ContactAddress }
848
- | { ok: false; status: 0; reason: "not-admitted" }
849
- | {
850
- ok: false;
851
- status: 404 | 409 | 410 | 503;
852
- reason:
853
- | "contact-erased" | "contact-expired" | "contact-absent" | "contact-unreadable"
854
- | "audit-unavailable" | "vault-key-unavailable" | "unavailable";
855
- };
856
-
857
- const SHIP_SELECT = `SELECT fact_id, order_kid, ship_ceiling, ship_city, ship_postal_code, ship_region, ship_country,
858
- ${LAYOUT.ship.sealed.join(", ")}
859
- FROM order_contact_vault WHERE tenant_id = ? AND stage = ? AND order_id = ?`;
860
-
861
- /**
862
- * An app's recipient read of one order: the ship group only. `admission` is the app-access audit
863
- * insert; it runs first and nothing here reads contact state, loads a key or decrypts unless it
864
- * returned its row. Zero rows answer `not-admitted` (the caller classifies from authority state);
865
- * an error answers 503 audit-unavailable. After admission the ship group's state classifies the
866
- * order (erased, expired, absent, unreadable) and only a present group is opened. Every failure
867
- * after admission is a code: the data key 503 vault-key-unavailable, any other storage error 503
868
- * unavailable. No thrown message leaves this function.
869
- */
870
- export async function readOrderShipRecipient(
871
- db: Queryable,
872
- kms: KmsClient,
873
- input: { tenantId: string; stage: VaultStage; orderId: string; admission: AuditStatement; now: Date; policy?: RetentionPolicy },
874
- ): Promise<ShipRecipientOutcome> {
875
- const { tenantId, stage, orderId, now } = input;
876
- const admitted = await admitAudit(db, input.admission);
877
- if (admitted === "quota") return { ok: false, status: 0, reason: "not-admitted" };
878
- if (admitted === "unavailable") return { ok: false, status: 503, reason: "audit-unavailable" };
879
- const unreadable = { ok: false, status: 409, reason: "contact-unreadable" } as const;
880
- try {
881
- const availability = await readOrderContactAvailability(db, { tenantId, stage, orderIds: [orderId], now, policy: input.policy });
882
- const state = availability.get(orderId)?.shipTo ?? "unreadable";
883
- if (state === "erased") return { ok: false, status: 410, reason: "contact-erased" };
884
- if (state === "expired") return { ok: false, status: 410, reason: "contact-expired" };
885
- if (state === "absent") return { ok: false, status: 404, reason: "contact-absent" };
886
- if (state !== "present") return unreadable;
887
- const row = await db.first<VaultRow>(SHIP_SELECT, tenantId, stage, orderId);
888
- const kid = row ? text(row, "order_kid") : null;
889
- if (!row || !kid) return unreadable;
890
- const key = await keyForKid(db, kms, keyContext(tenantId, stage, ORDER_KEY), kid);
891
- if (!key) return unreadable;
892
- const opened = await openGroups(key, row, tenantId, stage, ["ship"]);
893
- return opened?.shipTo ? { ok: true, shipTo: opened.shipTo } : unreadable;
894
- } catch (error) {
895
- if (error instanceof VaultKeyUnavailableError) return { ok: false, status: 503, reason: "vault-key-unavailable" };
896
- return { ok: false, status: 503, reason: "unavailable" };
897
- }
898
- }
899
-
900
- export interface ListedContact {
901
- orderId: string;
902
- contact: ReadableContact;
903
- expiresAt: string;
904
- groups: Partial<Record<Group, GroupView>>;
905
- }
906
-
907
- export type ListOutcome =
908
- | { ok: true; contacts: ListedContact[] }
909
- | { ok: false; status: 403 | 429 | 503; reason: "support-read-required" | "quota" | "audit-unavailable" | "vault-key-unavailable" };
910
-
911
- /**
912
- * The Orders panel list: one query joining orders to the vault, one `list` audit row naming the
913
- * order ids it returns and their count (before anything is decrypted), then local decryption under
914
- * cached data keys. Owner only; at most {@link AUDIT_RECORD_IDS_MAX} records.
915
- */
916
- export async function listOrderContacts(
917
- db: Queryable,
918
- kms: KmsClient,
919
- input: { tenantId: string; stage: VaultStage; actor: ContactActor; auditId: string; now: Date; limit?: number; policy?: RetentionPolicy },
920
- ): Promise<ListOutcome> {
921
- const { tenantId, stage, actor, auditId, now } = input;
922
- const policy = input.policy ?? RETENTION_POLICY;
923
- if (actor.role !== "owner") return { ok: false, status: 403, reason: "support-read-required" };
924
- const limit = Math.max(1, Math.min(AUDIT_RECORD_IDS_MAX, Math.floor(input.limit ?? 100)));
925
- const rows = await db.all<VaultRow>(
926
- `${ORDER_JOIN_SELECT} WHERE o.tenant_id = ? AND o.stage = ? ORDER BY o.placed_at DESC, o.order_id LIMIT ?`,
927
- tenantId, stage, limit,
928
- );
929
- const candidates = rows.flatMap((row) => {
930
- const view = viewable(row, tenantId, stage, now, policy);
931
- return view ? [{ row, view }] : [];
932
- });
933
- const admitted = await admitAudit(db, auditStatement({
934
- auditId, tenantId, stage, recordKind: "order-contact", recordId: auditRecordIds(candidates.map(({ row }) => String(row.order_id))),
935
- recordCount: candidates.length, actor, action: "list", now,
936
- }));
937
- if (admitted === "quota") return { ok: false, status: 429, reason: "quota" };
938
- if (admitted === "unavailable") return { ok: false, status: 503, reason: "audit-unavailable" };
939
- const contacts: ListedContact[] = [];
940
- try {
941
- const keys = new Map<string, CryptoKey | null>();
942
- for (const { row, view } of candidates) {
943
- const kid = text(row, "order_kid");
944
- if (!kid) continue;
945
- if (!keys.has(kid)) keys.set(kid, await keyForKid(db, kms, keyContext(tenantId, stage, ORDER_KEY), kid));
946
- const key = keys.get(kid);
947
- if (!key) continue;
948
- const contact = await openGroups(key, row, tenantId, stage, view.groups);
949
- if (!contact) continue;
950
- contacts.push({ orderId: String(row.order_id), contact, expiresAt: view.expiresAt, groups: view.views });
951
- }
952
- } catch (error) {
953
- if (error instanceof VaultKeyUnavailableError) return { ok: false, status: 503, reason: "vault-key-unavailable" };
954
- throw error;
955
- }
956
- return { ok: true, contacts };
957
- }
958
-
959
- // ---------------------------------------------------------------------------------------------
960
- // Search
961
- // ---------------------------------------------------------------------------------------------
962
-
963
- export type SearchQuery = { email: string } | { phone: string };
964
-
965
- export type SearchOutcome =
966
- | { ok: true; orderIds: string[] }
967
- | { ok: false; status: 400 | 403 | 429 | 503; reason: "malformed" | "support-read-required" | "quota" | "audit-unavailable" | "vault-key-unavailable" };
968
-
969
- /** A search body: exactly `{email}` or exactly `{phone}`, a bounded string. Null otherwise. */
970
- export function readSearchQuery(body: unknown): SearchQuery | null {
971
- if (!body || typeof body !== "object" || Array.isArray(body)) return null;
972
- const keys = Object.keys(body);
973
- if (keys.length !== 1) return null;
974
- const record = body as Record<string, unknown>;
975
- if (keys[0] === "email" && typeof record.email === "string" && record.email.length <= 254) return { email: record.email };
976
- if (keys[0] === "phone" && typeof record.phone === "string" && record.phone.length <= 40) return { phone: record.phone };
977
- return null;
978
- }
979
-
980
- /**
981
- * Owner exact-match search by email or phone: the normalized value's blind index under every
982
- * blind-index key the tenant still holds, matched against linked rows of the routed tenant and
983
- * stage whose group is readable now, at most {@link AUDIT_RECORD_IDS_MAX}. The audit row stores the
984
- * action, the matched order ids and their count, never the searched value.
985
- */
986
- export async function searchOrderContacts(
987
- db: Queryable,
988
- kms: KmsClient,
989
- input: { tenantId: string; stage: VaultStage; actor: ContactActor; auditId: string; now: Date; query: SearchQuery },
990
- ): Promise<SearchOutcome> {
991
- const { tenantId, stage, actor, auditId, now, query } = input;
992
- if (actor.role !== "owner") return { ok: false, status: 403, reason: "support-read-required" };
993
- const isEmail = "email" in query;
994
- const normalized = isEmail ? normalizeEmail(query.email) : normalizePhone(query.phone);
995
- if (normalized === null) return { ok: false, status: 400, reason: "malformed" };
996
- const group: Group = isEmail ? "email" : "phone";
997
- const column = isEmail ? "email_bidx" : "phone_bidx";
998
- const pairs: Array<[string, string]> = [];
999
- try {
1000
- const kids = await db.all<{ kid: string }>(
1001
- `SELECT kid FROM contact_vault_data_keys WHERE tenant_id = ? AND stage = ? AND purpose = ? ORDER BY created_at`,
1002
- tenantId, stage, BIDX_KEY,
1003
- );
1004
- for (const { kid } of kids) {
1005
- const key = await keyForKid(db, kms, keyContext(tenantId, stage, BIDX_KEY), kid);
1006
- if (key) pairs.push([kid, await blindIndex(key, normalized)]);
1007
- }
1008
- } catch (error) {
1009
- if (error instanceof VaultKeyUnavailableError) return { ok: false, status: 503, reason: "vault-key-unavailable" };
1010
- throw error;
1011
- }
1012
- let orderIds: string[] = [];
1013
- if (pairs.length > 0) {
1014
- const rows = await db.all<{ order_id: string; expires_at: string | null; ceiling: string | null }>(
1015
- `SELECT order_id, ${group}_expires_at AS expires_at, ${group}_ceiling AS ceiling FROM order_contact_vault
1016
- WHERE tenant_id = ? AND stage = ? AND order_id IS NOT NULL AND ${group}_expires_at > ? AND ${group}_ceiling > ?
1017
- AND (${pairs.map(() => `(bidx_kid = ? AND ${column} = ?)`).join(" OR ")})
1018
- ORDER BY order_id LIMIT ?`,
1019
- tenantId, stage, now.toISOString(), now.toISOString(), ...pairs.flat(), AUDIT_RECORD_IDS_MAX,
1020
- );
1021
- orderIds = rows.filter((row) => isGroupReadable(now, row.expires_at, row.ceiling)).map((row) => row.order_id);
1022
- }
1023
- const admitted = await admitAudit(db, auditStatement({
1024
- auditId, tenantId, stage, recordKind: "order-contact", recordId: auditRecordIds(orderIds), recordCount: orderIds.length, actor, action: "search", now,
1025
- }));
1026
- if (admitted === "quota") return { ok: false, status: 429, reason: "quota" };
1027
- if (admitted === "unavailable") return { ok: false, status: 503, reason: "audit-unavailable" };
1028
- return { ok: true, orderIds };
1029
- }
1030
-
1031
- // ---------------------------------------------------------------------------------------------
1032
- // Erase
1033
- // ---------------------------------------------------------------------------------------------
1034
-
1035
- export type EraseOutcome =
1036
- | { ok: true; groups: Group[] }
1037
- | { ok: false; status: 404 | 429 | 503; reason: "not-found" | "quota" | "audit-unavailable" }
1038
- | { ok: false; status: 409; reason: "retention-hold"; group: Group; holdUntil: string };
1039
-
1040
- /** Erase-request groups: a non-empty list of distinct known groups, or null. */
1041
- export function readEraseGroups(value: unknown): Group[] | null {
1042
- if (!Array.isArray(value) || value.length === 0 || value.length > GROUPS.length) return null;
1043
- if (!value.every((group) => typeof group === "string" && (GROUPS as readonly string[]).includes(group))) return null;
1044
- if (new Set(value).size !== value.length) return null;
1045
- return value as Group[];
1046
- }
1047
-
1048
- /**
1049
- * Erase field groups of one order's contact. `groups` defaults to every group still holding data
1050
- * that no floor holds. A named group under a floor answers 409 retention-hold with its hold-until
1051
- * date, with no audit row and no change. Otherwise audit, clearing and detach commit together; the
1052
- * marker stays, so a later resend answers 410.
1053
- */
1054
- export async function eraseOrderContact(
1055
- db: Queryable,
1056
- input: { tenantId: string; stage: VaultStage; orderId: string; actor: ContactActor; auditId: string; now: Date; groups?: readonly Group[] },
1057
- ): Promise<EraseOutcome> {
1058
- const { tenantId, stage, orderId, actor, auditId, now } = input;
1059
- const row = await db.first<VaultRow>(
1060
- `SELECT * FROM order_contact_vault WHERE tenant_id = ? AND stage = ? AND order_id = ?`, tenantId, stage, orderId,
1061
- );
1062
- if (!row) return { ok: false, status: 404, reason: "not-found" };
1063
- const holdUntil = (group: Group): string | null => {
1064
- const floor = readInstant(text(row, `${group}_floor_until`));
1065
- return floor && floor.getTime() > now.getTime() ? text(row, `${group}_floor_until`) : null;
1066
- };
1067
- const named = input.groups;
1068
- if (named) {
1069
- for (const group of named) {
1070
- const hold = holdUntil(group);
1071
- if (hold) return { ok: false, status: 409, reason: "retention-hold", group, holdUntil: hold };
1072
- }
1073
- }
1074
- const targets = named ? [...named] : GROUPS.filter((group) => rowHasData(row, group) && !holdUntil(group));
1075
- if (targets.length === 0) {
1076
- const held = GROUPS.find((group) => rowHasData(row, group) && holdUntil(group));
1077
- return held
1078
- ? { ok: false, status: 409, reason: "retention-hold", group: held, holdUntil: holdUntil(held)! }
1079
- : { ok: false, status: 404, reason: "not-found" };
1080
- }
1081
- const scope = `tenant_id = ? AND stage = ? AND order_id = ? AND EXISTS (SELECT 1 FROM contact_access_audit WHERE audit_id = ?)`;
1082
- const scopeParams = [tenantId, stage, orderId, auditId];
1083
- const audit = auditStatement({
1084
- auditId, tenantId, stage, recordKind: "order-contact", recordId: orderId, groups: targets, actor, action: "erase", now,
1085
- requireRow: { sql: `SELECT 1 FROM order_contact_vault WHERE tenant_id = ? AND stage = ? AND order_id = ?`, params: [tenantId, stage, orderId] },
1086
- });
1087
- const statements: QueryStatement[] = [
1088
- batchAuditStatement(audit),
1089
- {
1090
- sql: `UPDATE order_contact_markers SET erased_groups = erased_groups | ? WHERE ${scope}`,
1091
- params: [targets.reduce((mask, group) => mask | ERASURE_BITS[group], 0), ...scopeParams],
1092
- },
1093
- { sql: `UPDATE order_contact_vault SET ${clearSql(targets)}, erased_at = ? WHERE ${scope}`, params: [now.toISOString(), ...scopeParams] },
1094
- ...normalizeStatements(scope, scopeParams),
1095
- ];
1096
- try {
1097
- await requireBatch(db)(statements);
1098
- } catch {
1099
- return { ok: false, status: 503, reason: "audit-unavailable" };
1100
- }
1101
- if (await db.first(`SELECT 1 AS present FROM contact_access_audit WHERE audit_id = ?`, auditId)) return { ok: true, groups: targets };
1102
- const still = await db.first(`SELECT 1 AS present FROM order_contact_vault WHERE tenant_id = ? AND stage = ? AND order_id = ?`, tenantId, stage, orderId);
1103
- return still ? { ok: false, status: 429, reason: "quota" } : { ok: false, status: 404, reason: "not-found" };
1104
- }
1105
-
1106
- // ---------------------------------------------------------------------------------------------
1107
- // Terminal transition
1108
- // ---------------------------------------------------------------------------------------------
1109
-
1110
- const FAR_FUTURE = "9999-12-31T23:59:59.999Z";
1111
-
1112
- /** The rederived non-floor expiry of `group` for each ship-to variant the tenant's rules distinguish, as a SQL CASE. */
1113
- function rederivedCaseSql(
1114
- group: Group,
1115
- tenantId: string,
1116
- stage: VaultStage,
1117
- placedAt: Date,
1118
- terminalAt: Date,
1119
- timeScale: number,
1120
- policy: RetentionPolicy,
1121
- ): string | null {
1122
- const tenantRules = rulesForTenant(tenantId, policy);
1123
- const countries = [...new Set(tenantRules.flatMap((rule) => rule.appliesWhen.shipCountries ?? []).map((c) => c.toUpperCase()))];
1124
- const regions = [...new Set(tenantRules.flatMap((rule) => rule.appliesWhen.regions ?? []).map((r) => r.toUpperCase()))];
1125
- const derive = (country: string | null, region: string | null): string | null => rederiveGroup({
1126
- group, ceiling: FAR_FUTURE, expiresAt: FAR_FUTURE, floorUntil: null, timeScale, stage, placedAt, terminalAt,
1127
- rules: rederivationRules(tenantId, country, region, policy), policy,
1128
- });
1129
- const fallback = derive(null, null);
1130
- if (fallback === null) return null;
1131
- const branches = new Map<string, string[]>();
1132
- const add = (condition: string, value: string | null) => {
1133
- if (value === null) return;
1134
- branches.set(value, [...(branches.get(value) ?? []), condition]);
1135
- };
1136
- const countryExpr = "UPPER(TRIM(COALESCE(ship_country, '')))";
1137
- const regionExpr = "UPPER(TRIM(COALESCE(ship_region, '')))";
1138
- for (const country of countries) {
1139
- for (const region of regions) add(`(${countryExpr} = ${sqlLiteral(country)} AND ${regionExpr} = ${sqlLiteral(region)})`, derive(country, region));
1140
- add(`${countryExpr} = ${sqlLiteral(country)}`, derive(country, null));
1141
- }
1142
- for (const region of regions) add(`${regionExpr} = ${sqlLiteral(region)}`, derive(null, region));
1143
- const whens = [...branches.entries()]
1144
- .filter(([value]) => value !== fallback)
1145
- .map(([value, conditions]) => `WHEN ${conditions.join(" OR ")} THEN ${sqlLiteral(value)}`);
1146
- return whens.length === 0 ? sqlLiteral(fallback) : `CASE ${whens.join(" ")} ELSE ${sqlLiteral(fallback)} END`;
1147
- }
1148
-
1149
- /**
1150
- * The statement for a fulfillment transition's own batch that shrinks each group's effective expiry
1151
- * now that the order is terminal: max(current non-floor rules given the terminal time, the row's
1152
- * floor_until), never above its current expiry or its ceiling. It applies only when the order row
1153
- * reached a terminal state at exactly `version` and the row was sealed on this stage's clock, so a
1154
- * refused transition changes nothing; the hourly purge re-derives anything it skips.
1155
- */
1156
- export function terminalTransitionExpiryStatement(
1157
- order: { tenantId: string; stage: VaultStage; orderId: string; placedAt: string },
1158
- version: number,
1159
- terminalAt: Date,
1160
- policy: RetentionPolicy = RETENTION_POLICY,
1161
- ): { sql: string; params: unknown[] } {
1162
- const placedAt = readInstant(order.placedAt);
1163
- const timeScale = order.stage === "preview" ? policy.previewTimeScale : 1;
1164
- const derived = placedAt && !Number.isNaN(terminalAt.getTime())
1165
- ? GROUPS.map((group) => [group, rederivedCaseSql(group, order.tenantId, order.stage, placedAt, terminalAt, timeScale, policy)] as const)
1166
- : [];
1167
- if (derived.length === 0 || derived.some(([, sql]) => sql === null)) {
1168
- return { sql: `UPDATE order_contact_vault SET time_scale = time_scale WHERE 0`, params: [] };
1169
- }
1170
- const sets = derived.map(([group, sql]) =>
1171
- `${group}_expires_at = CASE WHEN ${group}_expires_at IS NULL OR ${group}_ceiling IS NULL THEN ${group}_expires_at
1172
- ELSE MIN(${group}_expires_at, ${group}_ceiling, MAX(COALESCE(${group}_floor_until, ''), ${sql})) END`);
1173
- return {
1174
- sql: `UPDATE order_contact_vault SET ${sets.join(", ")}
1175
- WHERE tenant_id = ? AND stage = ? AND order_id = ? AND time_scale = ?
1176
- AND EXISTS (
1177
- SELECT 1 FROM scrappy_commerce_orders
1178
- WHERE tenant_id = ? AND stage = ? AND order_id = ? AND event_version = ? AND placed_at IS ?
1179
- AND fulfillment_state IN ('handed_off', 'cancelled')
1180
- )`,
1181
- params: [order.tenantId, order.stage, order.orderId, timeScale, order.tenantId, order.stage, order.orderId, version, order.placedAt],
1182
- };
1183
- }
1184
-
1185
- // ---------------------------------------------------------------------------------------------
1186
- // Purge
1187
- // ---------------------------------------------------------------------------------------------
1188
-
1189
- export interface PurgeCounts {
1190
- /** Field groups cleared, by the rule id that held them. */
1191
- groupsPurged: Record<string, number>;
1192
- /** Rows detached to unlinked facts. */
1193
- detached: number;
1194
- /** Preview rows deleted whole with their marker. */
1195
- previewDeleted: number;
1196
- /** Group expiries shrunk by re-derivation. */
1197
- shortened: number;
1198
- }
1199
-
1200
- /** SQL: the group still holds data and its effective expiry or ceiling has passed (two `now` params). */
1201
- function expiredSql(group: Group): string {
1202
- return `(${hasDataSql(group)} AND (${group}_expires_at IS NULL OR ${group}_expires_at <= ? OR ${group}_ceiling <= ?))`;
1203
- }
1204
-
1205
- const TERMINAL_CORRELATED_SQL = correlatedTerminalSql("v");
1206
-
1207
- /**
1208
- * The hourly purge, with one clock reading: re-derive terminal orders' expiries (shrink-only), clear
1209
- * every group whose effective expiry has passed (its ciphertexts, its blind index, and city and full
1210
- * postal code for an address group), detach publication rows whose last group is gone, and delete
1211
- * preview rows with their marker at placed_at + the cutoff. Keyset pages, one batch each, so no
1212
- * page repeats. Aborts on an unreadable clock.
1213
- */
1214
- export async function purgeOrderContacts(
1215
- db: Queryable,
1216
- now: Date,
1217
- options: { pageSize?: number; shortenLimit?: number; policy?: RetentionPolicy } = {},
1218
- ): Promise<PurgeCounts> {
1219
- if (!(now instanceof Date) || Number.isNaN(now.getTime())) throw new Error("vault purge: unreadable clock");
1220
- const pageSize = Math.floor(options.pageSize ?? 50);
1221
- const shortenLimit = Math.floor(options.shortenLimit ?? 500);
1222
- if (!Number.isFinite(pageSize) || pageSize < 1 || pageSize > 90) throw new Error("vault purge: unreadable page size");
1223
- if (!Number.isFinite(shortenLimit) || shortenLimit < 0) throw new Error("vault purge: unreadable limit");
1224
- const policy = options.policy ?? RETENTION_POLICY;
1225
- const batch = requireBatch(db);
1226
- const nowIso = now.toISOString();
1227
- const counts: PurgeCounts = { groupsPurged: {}, detached: 0, previewDeleted: 0, shortened: 0 };
1228
-
1229
- // 1. Shrink-only re-derivation for terminal orders, before clearing, so this run clears what it shrank.
1230
- let cursor = "";
1231
- while (counts.shortened < shortenLimit) {
1232
- const rows = await db.all<VaultRow>(
1233
- `SELECT v.*, o.placed_at AS order_placed_at, o.fulfillment_state AS order_fulfillment_state, (${TERMINAL_CORRELATED_SQL}) AS order_terminal_at
1234
- FROM order_contact_vault v
1235
- JOIN scrappy_commerce_orders o ON o.tenant_id = v.tenant_id AND o.stage = v.stage AND o.order_id = v.order_id
1236
- WHERE o.fulfillment_state IN ('handed_off', 'cancelled') AND v.fact_id > ?
1237
- ORDER BY v.fact_id LIMIT ?`,
1238
- cursor, pageSize,
1239
- );
1240
- if (rows.length === 0) break;
1241
- const updates: QueryStatement[] = [];
1242
- for (const row of rows) {
1243
- cursor = String(row.fact_id);
1244
- const times = orderTimes(row.order_placed_at, row.order_fulfillment_state, row.order_terminal_at);
1245
- if (times === "order-time-unreadable") continue;
1246
- const effective = effectiveExpiries(row, String(row.tenant_id), row.stage as VaultStage, times, policy);
1247
- for (const group of GROUPS) {
1248
- const current = text(row, `${group}_expires_at`);
1249
- const next = effective[group];
1250
- if (!rowHasData(row, group) || !current || !next || next >= current) continue;
1251
- if (counts.shortened + updates.length >= shortenLimit) break;
1252
- updates.push({
1253
- sql: `UPDATE order_contact_vault SET ${group}_expires_at = ? WHERE fact_id = ? AND ${group}_expires_at = ?`,
1254
- params: [next, row.fact_id, current],
1255
- });
1256
- }
1257
- }
1258
- if (updates.length > 0) await batch(updates);
1259
- counts.shortened += updates.length;
1260
- if (rows.length < pageSize) break;
1261
- }
1262
-
1263
- // 2. Clear expired groups and detach, page by page.
1264
- cursor = "";
1265
- for (;;) {
1266
- const rows = await db.all<VaultRow>(
1267
- `SELECT fact_id, stage, ${GROUPS.map((group) => `${group}_rule, ${group}_expires_at, ${group}_ceiling, ${hasDataSql(group)} AS ${group}_has`).join(", ")}
1268
- FROM order_contact_vault
1269
- WHERE fact_id > ? AND (${GROUPS.map(expiredSql).join(" OR ")})
1270
- ORDER BY fact_id LIMIT ?`,
1271
- cursor, ...GROUPS.flatMap(() => [nowIso, nowIso]), pageSize,
1272
- );
1273
- if (rows.length === 0) break;
1274
- const ids = rows.map((row) => String(row.fact_id));
1275
- const inList = ids.map(() => "?").join(", ");
1276
- const statements: QueryStatement[] = GROUPS.map((group) => ({
1277
- sql: `UPDATE order_contact_vault SET ${clearSql([group])} WHERE fact_id IN (${inList}) AND ${expiredSql(group)}`,
1278
- params: [...ids, nowIso, nowIso],
1279
- }));
1280
- statements.push(...normalizeStatements(`fact_id IN (${inList})`, ids));
1281
- await batch(statements);
1282
- for (const row of rows) {
1283
- let remaining = 0;
1284
- for (const group of GROUPS) {
1285
- if (Number(row[`${group}_has`]) !== 1) continue;
1286
- const expires = text(row, `${group}_expires_at`);
1287
- const ceiling = text(row, `${group}_ceiling`);
1288
- const due = expires === null || expires <= nowIso || (ceiling !== null && ceiling <= nowIso);
1289
- if (!due) {
1290
- remaining += 1;
1291
- continue;
1292
- }
1293
- const rule = text(row, `${group}_rule`) ?? "unrecorded";
1294
- counts.groupsPurged[rule] = (counts.groupsPurged[rule] ?? 0) + 1;
1295
- }
1296
- if (remaining === 0 && row.stage === "publication") counts.detached += 1;
1297
- }
1298
- cursor = ids[ids.length - 1]!;
1299
- if (rows.length < pageSize) break;
1300
- }
1301
-
1302
- // 3. Preview: delete the whole row and its marker at placed_at + the cutoff.
1303
- let markerCursor: [string, string] = ["", ""];
1304
- for (;;) {
1305
- const markers = await db.all<{ tenant_id: string; order_id: string; placed_at: unknown }>(
1306
- `SELECT m.tenant_id, m.order_id, o.placed_at FROM order_contact_markers m
1307
- JOIN scrappy_commerce_orders o ON o.tenant_id = m.tenant_id AND o.stage = m.stage AND o.order_id = m.order_id
1308
- WHERE m.stage = 'preview' AND (m.tenant_id, m.order_id) > (?, ?)
1309
- ORDER BY m.tenant_id, m.order_id LIMIT ?`,
1310
- ...markerCursor, pageSize,
1311
- );
1312
- if (markers.length === 0) break;
1313
- const due = markers.filter((marker) => {
1314
- const placed = readInstant(marker.placed_at);
1315
- return placed !== null && nowIso >= previewDeleteAt(placed, policy);
1316
- });
1317
- if (due.length > 0) {
1318
- const pairs = due.map(() => "(tenant_id = ? AND order_id = ?)").join(" OR ");
1319
- const params = due.flatMap((marker) => [marker.tenant_id, marker.order_id]);
1320
- await batch([
1321
- { sql: `DELETE FROM order_contact_vault WHERE stage = 'preview' AND (${pairs})`, params },
1322
- { sql: `DELETE FROM order_contact_markers WHERE stage = 'preview' AND (${pairs})`, params },
1323
- ]);
1324
- counts.previewDeleted += due.length;
1325
- }
1326
- const last = markers[markers.length - 1]!;
1327
- markerCursor = [last.tenant_id, last.order_id];
1328
- if (markers.length < pageSize) break;
1329
- }
1330
- return counts;
1331
- }
1332
-
1333
- // ---------------------------------------------------------------------------------------------
1334
- // Rotation
1335
- // ---------------------------------------------------------------------------------------------
1336
-
1337
- /** Correlated reference checks for every data-key purpose (orders and messages). */
1338
- export const DATA_KEY_REFERENCES: Readonly<Record<DataKeyPurpose, string>> = {
1339
- "order-contact": `SELECT 1 FROM order_contact_vault v WHERE v.tenant_id = contact_vault_data_keys.tenant_id
1340
- AND v.stage = contact_vault_data_keys.stage AND v.order_kid = contact_vault_data_keys.kid`,
1341
- "contact-message": `SELECT 1 FROM contact_messages m WHERE m.tenant_id = contact_vault_data_keys.tenant_id
1342
- AND m.stage = contact_vault_data_keys.stage AND m.msg_kid = contact_vault_data_keys.kid`,
1343
- "blind-index": `SELECT 1 FROM order_contact_vault v WHERE v.tenant_id = contact_vault_data_keys.tenant_id
1344
- AND v.stage = contact_vault_data_keys.stage AND v.bidx_kid = contact_vault_data_keys.kid
1345
- UNION ALL SELECT 1 FROM contact_messages m WHERE m.tenant_id = contact_vault_data_keys.tenant_id
1346
- AND m.stage = contact_vault_data_keys.stage AND m.bidx_kid = contact_vault_data_keys.kid`,
1347
- };
1348
-
1349
- /** Rows per table whose blind indexes one rotation run recomputes; the next run takes the rest. */
1350
- export const BLIND_INDEX_RECOMPUTE_LIMIT = 200;
1351
-
1352
- /**
1353
- * One table's blind-index recompute step: re-index up to `limit` still-sealed rows whose bidx_kid is
1354
- * retired under the active blind-index key, returning how many rows it moved. contactMessages.ts
1355
- * supplies the messages step; the sweep passes it in, since orders never import engagement.
1356
- */
1357
- export type BlindIndexRecompute = (db: Queryable, kms: KmsClient, now: Date, limit: number) => Promise<number>;
1358
-
1359
- /**
1360
- * Recompute order rows indexed under a retired blind-index kid: decrypt the email and phone fields
1361
- * under the row's order key, HMAC the normalized values with the active blind-index key, and write
1362
- * both indexes and bidx_kid in ONE update conditioned on the row being unchanged since it was read.
1363
- * An index whose field no longer opens is cleared. Throws VaultKeyUnavailableError when KMS refuses.
1364
- */
1365
- export const recomputeOrderBlindIndexes: BlindIndexRecompute = async (db, kms, now, limit) => {
1366
- const rows = await db.all<VaultRow>(
1367
- `SELECT v.fact_id, v.tenant_id, v.stage, v.order_kid, v.bidx_kid, v.email_ct, v.email_bidx, v.email_ceiling,
1368
- v.phone_ct, v.phone_bidx, v.phone_ceiling
1369
- FROM order_contact_vault v
1370
- JOIN contact_vault_data_keys k ON k.tenant_id = v.tenant_id AND k.stage = v.stage AND k.purpose = ? AND k.kid = v.bidx_kid
1371
- WHERE k.retired_at IS NOT NULL
1372
- ORDER BY v.fact_id LIMIT ?`,
1373
- BIDX_KEY, Math.max(0, Math.floor(limit)),
1374
- );
1375
- let moved = 0;
1376
- for (const row of rows) {
1377
- const tenantId = String(row.tenant_id);
1378
- const stage = row.stage as VaultStage;
1379
- const factId = String(row.fact_id);
1380
- const active = await activeKey(db, kms, keyContext(tenantId, stage, BIDX_KEY), now);
1381
- // Rotation installs the new active key before this runs; never mint one from here.
1382
- if (active.pending.length > 0 || active.kid === row.bidx_kid) continue;
1383
- const orderKid = text(row, "order_kid");
1384
- const orderKey = orderKid ? await keyForKid(db, kms, keyContext(tenantId, stage, ORDER_KEY), orderKid) : null;
1385
- const reindex = async (group: "email" | "phone"): Promise<string | null> => {
1386
- const sealed = text(row, `${group}_ct`);
1387
- const ceiling = text(row, `${group}_ceiling`);
1388
- if (text(row, `${group}_bidx`) === null || sealed === null || ceiling === null || !orderKey || !orderKid) return null;
1389
- const value = await openField(orderKey, fieldBinding(tenantId, stage, factId, orderKid, `${group}_ct`, ceiling), sealed);
1390
- const normalized = value === null ? null : group === "email" ? normalizeEmail(value) : normalizePhone(value);
1391
- return normalized === null ? null : blindIndex(active.key, normalized);
1392
- };
1393
- const email = await reindex("email");
1394
- const phone = await reindex("phone");
1395
- const updated = await db.all(
1396
- `UPDATE order_contact_vault SET email_bidx = ?, phone_bidx = ?, bidx_kid = ?
1397
- WHERE fact_id = ? AND bidx_kid IS ? AND email_bidx IS ? AND phone_bidx IS ? AND email_ct IS ? AND phone_ct IS ?
1398
- AND EXISTS (SELECT 1 FROM contact_vault_data_keys WHERE tenant_id = ? AND stage = ? AND purpose = ? AND kid = ? AND retired_at IS NULL)
1399
- RETURNING fact_id`,
1400
- email, phone, email === null && phone === null ? null : active.kid,
1401
- factId, row.bidx_kid, row.email_bidx, row.phone_bidx, row.email_ct, row.phone_ct,
1402
- tenantId, stage, BIDX_KEY, active.kid,
1403
- );
1404
- moved += updated.length;
1405
- }
1406
- return moved;
1407
- };
1408
-
1409
- /**
1410
- * Rotate data keys older than 365 days, recompute blind indexes still under a retired blind-index
1411
- * kid (orders here, plus each step in `recompute`, bounded per run), then delete retired keys no row
1412
- * references any more.
1413
- */
1414
- export async function rotateContactVaultKeys(
1415
- db: Queryable,
1416
- kms: KmsClient,
1417
- now: Date,
1418
- options: { recompute?: readonly BlindIndexRecompute[]; recomputeLimit?: number } = {},
1419
- ): Promise<{ rotated: number; recomputed: number }> {
1420
- if (!(now instanceof Date) || Number.isNaN(now.getTime())) throw new Error("vault rotation: unreadable clock");
1421
- const { rotated } = await rotateDueKeys(db, kms, now);
1422
- const limit = options.recomputeLimit ?? BLIND_INDEX_RECOMPUTE_LIMIT;
1423
- let recomputed = 0;
1424
- for (const step of [recomputeOrderBlindIndexes, ...(options.recompute ?? [])]) recomputed += await step(db, kms, now, limit);
1425
- await deleteUnreferencedRetiredKeys(db, DATA_KEY_REFERENCES);
1426
- return { rotated, recomputed };
1427
- }