@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.
- package/agency-kit/tools/lib/catalog-model/files.mjs +11 -4
- package/agency-kit/tools/lib/catalog-model/model.mjs +5 -1
- package/agency-kit/tools/lib/redirect-shadows.mjs +261 -0
- package/apps/storefront/astro.config.mjs +8 -2
- package/apps/storefront/package.json +1 -2
- package/apps/storefront/src/components/catalog/storefront/ProductCard.astro +20 -6
- package/apps/storefront/src/components/catalog/storefront/islands/ImageGallery.tsx +17 -6
- package/apps/storefront/src/components/compliance/storefront/islands/CheckoutComplianceGate.tsx +1 -32
- package/apps/storefront/src/config/compliance/rulesets.ts +1 -1
- package/apps/storefront/src/layouts/Layout.astro +17 -0
- package/apps/storefront/src/lib/access/auth/agentRoles.ts +20 -0
- package/apps/storefront/src/lib/access/auth/agentSessionGate.ts +147 -0
- package/apps/storefront/src/lib/access/auth/brokerAssertion.ts +67 -1
- package/apps/storefront/src/lib/access/auth/contactReaderAuthority.ts +39 -0
- package/apps/storefront/src/lib/access/auth/loginGate.ts +15 -17
- package/apps/storefront/src/lib/access/auth/session.ts +79 -0
- package/apps/storefront/src/lib/access/dashboard/staffAdmission.ts +5 -0
- package/apps/storefront/src/lib/access/dashboard/tenantSelection.ts +2 -0
- package/apps/storefront/src/lib/access/shared/capability.ts +14 -6
- package/apps/storefront/src/lib/access/shared/generated/capabilityCatalog.generated.ts +161 -0
- package/apps/storefront/src/lib/activity/activityScope.ts +36 -0
- package/apps/storefront/src/lib/activity/recordActivity.ts +23 -1
- package/apps/storefront/src/lib/activity/serverFanOut.ts +31 -0
- package/apps/storefront/src/lib/activity/store.ts +9 -3
- package/apps/storefront/src/lib/checkout/commerce/cardCartForm.ts +2 -0
- package/apps/storefront/src/lib/checkout/commerce/cartSession.ts +109 -12
- package/apps/storefront/src/lib/checkout/commerce/checkoutHandoffRoute.ts +53 -25
- package/apps/storefront/src/lib/checkout/commerce/finalCartAuthorization.ts +48 -6
- package/apps/storefront/src/lib/checkout/proposal/cartProposal.ts +388 -0
- package/apps/storefront/src/lib/checkout/proposal/listMatcher.ts +149 -0
- package/apps/storefront/src/lib/checkout/proposal/proposalRoutes.ts +447 -0
- package/apps/storefront/src/lib/checkout/proposal/reviewHtml.ts +100 -0
- package/apps/storefront/src/lib/compliance/browser/checkoutVerificationFlow.ts +26 -2
- package/apps/storefront/src/lib/content/shared/redirects.ts +21 -4
- package/apps/storefront/src/lib/publication/shared/edgeCache.ts +5 -2
- package/apps/storefront/src/lib/publication/shared/previewAnnotations/renderDecorator.ts +15 -8
- package/apps/storefront/src/lib/publication/shared/runtimeEnv.ts +1 -1
- package/apps/storefront/src/middleware/controlPlane.ts +15 -1
- package/apps/storefront/src/middleware/index.ts +40 -1
- package/apps/storefront/src/middleware/renderChain.ts +46 -33
- package/apps/storefront/src/pages/api/cart-proposal/confirm.ts +12 -0
- package/apps/storefront/src/pages/api/cart-proposal/review.ts +26 -0
- package/apps/storefront/src/pages/api/commerce/final-cart-authorization.ts +29 -6
- package/apps/storefront/src/pages/api/compliance/preflight.ts +25 -1
- package/apps/storefront/src/pages/products/[handle].astro +2 -15
- package/apps/storefront/tsconfig.astro.json +11 -0
- package/package.json +1 -1
- package/packages/public-runtime/src/activity/README.md +12 -0
- package/packages/public-runtime/src/activity/catalog.ts +7 -0
- package/packages/public-runtime/src/activity/event.ts +19 -0
- package/packages/public-runtime/src/activity/redaction.ts +31 -2
- package/packages/public-runtime/src/catalog-files.ts +3 -2
- package/packages/public-runtime/src/checkout-orders.ts +18 -19
- package/packages/public-runtime/src/checkout.ts +70 -0
- package/packages/public-runtime/src/compliance/evaluate.ts +60 -1
- package/packages/public-runtime/src/compliance/index.ts +1 -1
- package/packages/public-runtime/src/compliance/pact-report.ts +184 -3
- package/packages/public-runtime/src/compliance/profile.ts +268 -20
- package/packages/public-runtime/src/compliance/ruleset.ts +42 -0
- package/packages/public-runtime/src/customization-runtime.ts +1 -1
- package/packages/public-runtime/src/product.ts +9 -1
- package/packages/public-runtime/src/publication-content-redirects.ts +16 -3
- package/packages/public-runtime/tests/fixtures/compliance-decisions.golden.json +252 -52
- package/pnpm-lock.runner.yaml +0 -15
- package/scripts/tenant/materialize-tenant-content.mjs +3 -0
- package/scripts/tenant/validate.mjs +128 -0
- package/apps/storefront/dev-plugins/dev-publish.mjs +0 -55
- package/apps/storefront/drizzle.config.apps.ts +0 -13
- package/apps/storefront/integrations/preview-annotations-client-bundle.mjs +0 -80
- package/apps/storefront/migrations-apps/0000_fast_millenium_guard.sql +0 -129
- package/apps/storefront/migrations-apps/0001_woozy_lyja.sql +0 -22
- package/apps/storefront/migrations-apps/0002_good_switch.sql +0 -26
- package/apps/storefront/migrations-apps/0003_mute_marauders.sql +0 -12
- package/apps/storefront/migrations-apps/0004_deep_morph.sql +0 -36
- package/apps/storefront/migrations-apps/0005_common_mystique.sql +0 -23
- package/apps/storefront/migrations-apps/0006_broad_microchip.sql +0 -16
- package/apps/storefront/migrations-apps/0007_brave_outlaw_kid.sql +0 -15
- package/apps/storefront/migrations-apps/0008_blue_dazzler.sql +0 -11
- package/apps/storefront/migrations-apps/0009_bored_shinobi_shaw.sql +0 -15
- package/apps/storefront/migrations-apps/0010_ws4_verified_provider_measurement.sql +0 -35
- package/apps/storefront/migrations-apps/0011_dt_tracking_tenant_databases.sql +0 -23
- package/apps/storefront/migrations-apps/0012_test_destinations.sql +0 -29
- package/apps/storefront/migrations-apps/0013_publication_space_editorial.sql +0 -64
- package/apps/storefront/migrations-apps/0014_retire_candidate_ledger.sql +0 -12
- package/apps/storefront/migrations-apps/0015_merchant_calculation_settings.sql +0 -31
- package/apps/storefront/migrations-apps/0016_scrappy_commerce_contract.sql +0 -166
- package/apps/storefront/migrations-apps/0017_commerce_durable_projection.sql +0 -28
- package/apps/storefront/migrations-apps/0018_commerce_provider_cart_identity.sql +0 -13
- package/apps/storefront/migrations-apps/0019_commerce_source_authority.sql +0 -23
- package/apps/storefront/migrations-apps/0020_contact_messages.sql +0 -18
- package/apps/storefront/migrations-apps/0021_contact_vault.sql +0 -166
- package/apps/storefront/migrations-apps/0022_contact_vault_fields.sql +0 -342
- package/apps/storefront/migrations-apps/0023_principal_grant_contacts.sql +0 -15
- package/apps/storefront/migrations-apps/0024_order_contact_erasure_state.sql +0 -22
- package/apps/storefront/migrations-apps/0025_shipment_audit_order_lookup.sql +0 -2
- package/apps/storefront/migrations-apps/0026_fulfillment_assignment.sql +0 -44
- package/apps/storefront/migrations-apps/0027_app_contact_authority.sql +0 -70
- package/apps/storefront/migrations-apps/0028_app_jwk_and_candidates.sql +0 -133
- package/apps/storefront/migrations-apps/0029_inventory_locations_wms.sql +0 -38
- package/apps/storefront/migrations-apps/0030_assignment_split_shipments.sql +0 -149
- package/apps/storefront/migrations-apps/meta/0000_snapshot.json +0 -843
- package/apps/storefront/migrations-apps/meta/0001_snapshot.json +0 -990
- package/apps/storefront/migrations-apps/meta/0002_snapshot.json +0 -1160
- package/apps/storefront/migrations-apps/meta/0003_snapshot.json +0 -1235
- package/apps/storefront/migrations-apps/meta/0004_snapshot.json +0 -1474
- package/apps/storefront/migrations-apps/meta/0005_snapshot.json +0 -1617
- package/apps/storefront/migrations-apps/meta/0006_snapshot.json +0 -1716
- package/apps/storefront/migrations-apps/meta/0007_snapshot.json +0 -1812
- package/apps/storefront/migrations-apps/meta/0008_snapshot.json +0 -1881
- package/apps/storefront/migrations-apps/meta/0009_snapshot.json +0 -1979
- package/apps/storefront/migrations-apps/meta/_journal.json +0 -76
- package/apps/storefront/perf/README.md +0 -64
- package/apps/storefront/perf/assert-budgets.ts +0 -159
- package/apps/storefront/platform-reconcile-tenants.json +0 -3
- package/apps/storefront/playwright.config.ts +0 -23
- package/apps/storefront/public/js/dashboard-access-banner.js +0 -53
- package/apps/storefront/public/js/dashboard-apps.js +0 -183
- package/apps/storefront/public/js/dashboard-contact-capture.js +0 -52
- package/apps/storefront/public/js/dashboard-delegate.js +0 -167
- package/apps/storefront/public/js/dashboard-team.js +0 -356
- package/apps/storefront/public/js/dashboard-vendor-search.js +0 -115
- package/apps/storefront/src/components/content/storefront/AsyncStylesheet.astro +0 -26
- package/apps/storefront/src/components/integrations/storefront/WidgetFrame.astro +0 -34
- package/apps/storefront/src/config/adminTenantLookup.ts +0 -35
- package/apps/storefront/src/config/evidenceTenantRoster.ts +0 -25
- package/apps/storefront/src/config/staffProvisionProjection.ts +0 -24
- package/apps/storefront/src/config/storeName.ts +0 -34
- package/apps/storefront/src/lib/access/admin/README.md +0 -122
- package/apps/storefront/src/lib/access/admin/adminShell.ts +0 -281
- package/apps/storefront/src/lib/access/admin/envelope.ts +0 -9
- package/apps/storefront/src/lib/access/admin/viewmodels/settings.ts +0 -64
- package/apps/storefront/src/lib/access/auth/adminApiGuard.ts +0 -66
- package/apps/storefront/src/lib/access/auth/adminEntry.ts +0 -126
- package/apps/storefront/src/lib/access/auth/mcpClientAssertion.ts +0 -217
- package/apps/storefront/src/lib/access/auth/operatorSession.ts +0 -120
- package/apps/storefront/src/lib/access/dashboard/delegateGate.ts +0 -130
- package/apps/storefront/src/lib/access/dashboard/staffStoreEntry.ts +0 -150
- package/apps/storefront/src/lib/access/dashboard/staffVendorAccess.ts +0 -452
- package/apps/storefront/src/lib/access/dashboard/vendorQuery.ts +0 -61
- package/apps/storefront/src/lib/access/fixtures/settings.ts +0 -67
- package/apps/storefront/src/lib/access/fixtures/tenants.ts +0 -29
- package/apps/storefront/src/lib/access/notifications/magicLinkInviteEmail.ts +0 -62
- package/apps/storefront/src/lib/access/shared/grantContactLookup.ts +0 -97
- package/apps/storefront/src/lib/access/shared/principalGrants.ts +0 -775
- package/apps/storefront/src/lib/activity/alerts.ts +0 -426
- package/apps/storefront/src/lib/activity/candidateSubmitLease.ts +0 -87
- package/apps/storefront/src/lib/activity/changeActorAttribution.ts +0 -181
- package/apps/storefront/src/lib/activity/evidence/evidenceReference.ts +0 -32
- package/apps/storefront/src/lib/activity/fixtures/evidence.ts +0 -99
- package/apps/storefront/src/lib/activity/query.ts +0 -403
- package/apps/storefront/src/lib/activity/uiActor.ts +0 -152
- package/apps/storefront/src/lib/admin/services/mock/index.ts +0 -12
- package/apps/storefront/src/lib/assets/addons/catalog.ts +0 -60
- package/apps/storefront/src/lib/assets/addons/storeEntitlements.ts +0 -260
- package/apps/storefront/src/lib/assets/durableAssetsRoute.ts +0 -65
- package/apps/storefront/src/lib/assets/durableR2.ts +0 -473
- package/apps/storefront/src/lib/assets/durableR2Bindings.ts +0 -33
- package/apps/storefront/src/lib/automation/admin/viewmodels/aiWorkflows.ts +0 -65
- package/apps/storefront/src/lib/automation/ai/approvalMode.ts +0 -20
- package/apps/storefront/src/lib/automation/ai/askEnvelope.ts +0 -47
- package/apps/storefront/src/lib/automation/ai/audit.ts +0 -12
- package/apps/storefront/src/lib/automation/ai/operationalRuns.ts +0 -155
- package/apps/storefront/src/lib/automation/ai/recommendation.ts +0 -20
- package/apps/storefront/src/lib/automation/fixtures/aiWorkflows.ts +0 -59
- package/apps/storefront/src/lib/catalog/admin/catalogSettingsClient.ts +0 -250
- package/apps/storefront/src/lib/catalog/admin/catalogSettingsFields.ts +0 -134
- package/apps/storefront/src/lib/catalog/admin/catalogSettingsPreview.ts +0 -37
- package/apps/storefront/src/lib/catalog/admin/catalogSettingsPricingView.ts +0 -39
- package/apps/storefront/src/lib/catalog/admin/catalogSettingsRuleView.ts +0 -44
- package/apps/storefront/src/lib/catalog/admin/catalogSettingsSkuView.ts +0 -21
- package/apps/storefront/src/lib/catalog/admin/catalogSettingsState.ts +0 -132
- package/apps/storefront/src/lib/catalog/admin/productSetupPhoto.ts +0 -23
- package/apps/storefront/src/lib/catalog/admin/productsTabClient.ts +0 -193
- package/apps/storefront/src/lib/catalog/admin/services/catalogProducts.ts +0 -32
- package/apps/storefront/src/lib/catalog/admin/viewmodels/catalogProducts.ts +0 -164
- package/apps/storefront/src/lib/catalog/admin/viewmodels/products.ts +0 -267
- package/apps/storefront/src/lib/catalog/fixtures/products.ts +0 -105
- package/apps/storefront/src/lib/catalog/tot/syncState.ts +0 -111
- package/apps/storefront/src/lib/checkout/admin/checkoutStyleInput.ts +0 -172
- package/apps/storefront/src/lib/checkout/admin/checkoutStyleTarget.ts +0 -65
- package/apps/storefront/src/lib/checkout/browser/checkoutExciseForm.ts +0 -152
- package/apps/storefront/src/lib/checkout/browser/checkoutRequirementsForm.ts +0 -72
- package/apps/storefront/src/lib/checkout/browser/checkoutStyleForm.ts +0 -110
- package/apps/storefront/src/lib/checkout/browser/settingDraftActions.ts +0 -367
- package/apps/storefront/src/lib/checkout/commerce/checkoutSettings.ts +0 -246
- package/apps/storefront/src/lib/checkout/fixtures/checkoutSettings.ts +0 -77
- package/apps/storefront/src/lib/content/blog/markdown.ts +0 -174
- package/apps/storefront/src/lib/content/chrome/examples/tokenoftrust.chrome-assignments.example.json +0 -6
- package/apps/storefront/src/lib/content/chrome/examples/tokenoftrust.chrome.example.json +0 -79
- package/apps/storefront/src/lib/content/index.ts +0 -27
- package/apps/storefront/src/lib/content/the-build/readingTime.ts +0 -35
- package/apps/storefront/src/lib/content/the-build/toc.ts +0 -95
- package/apps/storefront/src/lib/customers/admin/viewmodels/customers.ts +0 -56
- package/apps/storefront/src/lib/customers/contactVault/blindIndex.ts +0 -28
- package/apps/storefront/src/lib/customers/contactVault/contactAudit.ts +0 -149
- package/apps/storefront/src/lib/customers/contactVault/dataKeys.ts +0 -283
- package/apps/storefront/src/lib/customers/contactVault/fieldEnvelope.ts +0 -88
- package/apps/storefront/src/lib/customers/contactVault/isolateMetrics.ts +0 -37
- package/apps/storefront/src/lib/customers/contactVault/kms.ts +0 -292
- package/apps/storefront/src/lib/customers/contactVault/retention.ts +0 -302
- package/apps/storefront/src/lib/customers/contactVault/retentionPolicy.ts +0 -290
- package/apps/storefront/src/lib/customers/contactVault/zip3.ts +0 -24
- package/apps/storefront/src/lib/customers/fixtures/customers.ts +0 -86
- package/apps/storefront/src/lib/developer-experience/admin/memoizeByEnvelope.ts +0 -27
- package/apps/storefront/src/lib/developer-experience/admin/seed.ts +0 -54
- package/apps/storefront/src/lib/developer-experience/dev/activityIngestToken.ts +0 -85
- package/apps/storefront/src/lib/developer-experience/dev/activityStore.ts +0 -82
- package/apps/storefront/src/lib/developer-experience/dev/ai-widget-client.js +0 -308
- package/apps/storefront/src/lib/developer-experience/dev/apiBase.ts +0 -17
- package/apps/storefront/src/lib/developer-experience/dev/cliSignInCode.ts +0 -124
- package/apps/storefront/src/lib/developer-experience/dev/cockpit/ask.ts +0 -49
- package/apps/storefront/src/lib/developer-experience/dev/cockpit/clickToSource.ts +0 -71
- package/apps/storefront/src/lib/developer-experience/dev/cockpit/copyCommand.ts +0 -227
- package/apps/storefront/src/lib/developer-experience/dev/cockpit/files.ts +0 -249
- package/apps/storefront/src/lib/developer-experience/dev/cockpit/hostedActivity.ts +0 -500
- package/apps/storefront/src/lib/developer-experience/dev/cockpit/infoPopover.ts +0 -12
- package/apps/storefront/src/lib/developer-experience/dev/cockpit/mcpCopy.ts +0 -34
- package/apps/storefront/src/lib/developer-experience/dev/cockpit/monitor.ts +0 -107
- package/apps/storefront/src/lib/developer-experience/dev/cockpit/stepper.ts +0 -116
- package/apps/storefront/src/lib/developer-experience/dev/cockpit/themeToggle.ts +0 -23
- package/apps/storefront/src/lib/developer-experience/dev/livePreview.ts +0 -77
- package/apps/storefront/src/lib/developer-experience/dev/obstacleStore.ts +0 -214
- package/apps/storefront/src/lib/developer-experience/dev/previewStatus.ts +0 -87
- package/apps/storefront/src/lib/developer-experience/dev/rendezvousBroker.ts +0 -226
- package/apps/storefront/src/lib/developer-experience/dev/runtimeStore.ts +0 -291
- package/apps/storefront/src/lib/developer-experience/dev/storeStatus.ts +0 -142
- package/apps/storefront/src/lib/developer-experience/dev/subjectReissue.ts +0 -67
- package/apps/storefront/src/lib/developer-experience/fixtures/regulated-commerce-truth/index.ts +0 -540
- package/apps/storefront/src/lib/developer-experience/fixtures/ws3-readonly-clone-preflight/index.ts +0 -495
- package/apps/storefront/src/lib/engagement/contact/contactMessages.ts +0 -671
- package/apps/storefront/src/lib/engagement/contact/messagesTabClient.ts +0 -175
- package/apps/storefront/src/lib/engagement/contact/submission.ts +0 -112
- package/apps/storefront/src/lib/engagement/messaging/messagesClient.ts +0 -149
- package/apps/storefront/src/lib/engagement/newsletter/digest.ts +0 -117
- package/apps/storefront/src/lib/engagement/newsletter/resendClient.ts +0 -79
- package/apps/storefront/src/lib/engagement/newsletter/send.ts +0 -265
- package/apps/storefront/src/lib/engagement/social/golive.ts +0 -212
- package/apps/storefront/src/lib/engagement/social/notify.ts +0 -32
- package/apps/storefront/src/lib/engagement/social/tokenStore.ts +0 -171
- package/apps/storefront/src/lib/fulfillment/admin/commerceDesk.ts +0 -180
- package/apps/storefront/src/lib/fulfillment/admin/commerceDeskRouting.ts +0 -45
- package/apps/storefront/src/lib/fulfillment/admin/viewmodels/fulfillment.ts +0 -1071
- package/apps/storefront/src/lib/fulfillment/appShipmentEvidence.ts +0 -271
- package/apps/storefront/src/lib/fulfillment/carrierEvidence.ts +0 -105
- package/apps/storefront/src/lib/fulfillment/commerceProjection.ts +0 -157
- package/apps/storefront/src/lib/fulfillment/commerceReadback.ts +0 -60
- package/apps/storefront/src/lib/fulfillment/commerceRecovery.ts +0 -84
- package/apps/storefront/src/lib/fulfillment/commerceRuntime.ts +0 -41
- package/apps/storefront/src/lib/fulfillment/fulfillmentService.ts +0 -2842
- package/apps/storefront/src/lib/fulfillment/readiness.ts +0 -217
- package/apps/storefront/src/lib/fulfillment/splitShipments.ts +0 -388
- package/apps/storefront/src/lib/fulfillment/syntheticPreviewOrders.ts +0 -292
- package/apps/storefront/src/lib/integrations/apps/appContactAuthority.ts +0 -27
- package/apps/storefront/src/lib/integrations/apps/appContactConsents.ts +0 -118
- package/apps/storefront/src/lib/integrations/apps/appInstallEnv.ts +0 -28
- package/apps/storefront/src/lib/integrations/apps/gtmMigrationDraft.ts +0 -103
- package/apps/storefront/src/lib/integrations/apps/inventoryWrite.ts +0 -906
- package/apps/storefront/src/lib/integrations/apps/orders/customerHash.ts +0 -28
- package/apps/storefront/src/lib/integrations/apps/orders/idempotency.ts +0 -100
- package/apps/storefront/src/lib/integrations/apps/reports/salesVelocityReport.ts +0 -96
- package/apps/storefront/src/lib/integrations/apps/routeParams.ts +0 -45
- package/apps/storefront/src/lib/integrations/webhooks/cloudflareQueueDispatcher.ts +0 -82
- package/apps/storefront/src/lib/integrations/webhooks/commercePayloads.ts +0 -159
- package/apps/storefront/src/lib/integrations/webhooks/deliveryEngine.ts +0 -379
- package/apps/storefront/src/lib/integrations/webhooks/deliveryMapper.ts +0 -34
- package/apps/storefront/src/lib/integrations/webhooks/deliveryStore.ts +0 -903
- package/apps/storefront/src/lib/integrations/webhooks/dispatcher.ts +0 -168
- package/apps/storefront/src/lib/integrations/webhooks/emit.ts +0 -245
- package/apps/storefront/src/lib/integrations/webhooks/events.ts +0 -105
- package/apps/storefront/src/lib/integrations/webhooks/getDispatcher.ts +0 -77
- package/apps/storefront/src/lib/integrations/webhooks/orderFulfilledClaim.ts +0 -75
- package/apps/storefront/src/lib/measurement/admin/analyticsRegionPolicy.ts +0 -151
- package/apps/storefront/src/lib/measurement/admin/analyticsRegionsClient.ts +0 -84
- package/apps/storefront/src/lib/measurement/admin/consentSettingsClient.ts +0 -113
- package/apps/storefront/src/lib/measurement/analytics/index.ts +0 -44
- package/apps/storefront/src/lib/measurement/attribution/attributionService.ts +0 -206
- package/apps/storefront/src/lib/measurement/attribution/orderConversionD1.ts +0 -150
- package/apps/storefront/src/lib/measurement/attribution/verifiedProviderMeasurement.ts +0 -118
- package/apps/storefront/src/lib/measurement/tracking/interactionCollector.ts +0 -205
- package/apps/storefront/src/lib/measurement/tracking/pruneRollup.ts +0 -260
- package/apps/storefront/src/lib/measurement/tracking/tenantReadAccess.ts +0 -138
- package/apps/storefront/src/lib/measurement/tracking-writeback/rewriteTrackingIds.ts +0 -175
- package/apps/storefront/src/lib/measurement/tracking-writeback/writebackCandidate.ts +0 -110
- package/apps/storefront/src/lib/observability/diag/capture.ts +0 -162
- package/apps/storefront/src/lib/observability/diag/consoleLine.ts +0 -76
- package/apps/storefront/src/lib/observability/diag/debugConsole.ts +0 -118
- package/apps/storefront/src/lib/observability/diag/debugMode.ts +0 -163
- package/apps/storefront/src/lib/observability/diag/debugWindow.ts +0 -111
- package/apps/storefront/src/lib/observability/diag/redact.ts +0 -17
- package/apps/storefront/src/lib/observability/diag/reference.ts +0 -148
- package/apps/storefront/src/lib/observability/diag/referenceStore.ts +0 -113
- package/apps/storefront/src/lib/observability/diag/report.ts +0 -110
- package/apps/storefront/src/lib/observability/diag/serverResponseTime.ts +0 -91
- package/apps/storefront/src/lib/observability/diag/session.ts +0 -93
- package/apps/storefront/src/lib/observability/monitoring/manifest.ts +0 -301
- package/apps/storefront/src/lib/observability/performance/lighthouseReport.ts +0 -109
- package/apps/storefront/src/lib/observability/performance/rumAlert.ts +0 -179
- package/apps/storefront/src/lib/orders/admin/orderActions.ts +0 -556
- package/apps/storefront/src/lib/orders/admin/orderClient.ts +0 -248
- package/apps/storefront/src/lib/orders/admin/orderSource.ts +0 -410
- package/apps/storefront/src/lib/orders/admin/services/orders.ts +0 -922
- package/apps/storefront/src/lib/orders/admin/viewmodels/orders.ts +0 -135
- package/apps/storefront/src/lib/orders/data/commerceCallerConfig.ts +0 -37
- package/apps/storefront/src/lib/orders/data/ledgerContractOrders.ts +0 -148
- package/apps/storefront/src/lib/orders/data/orderForwardReceiver.ts +0 -532
- package/apps/storefront/src/lib/orders/data/orderMapper.ts +0 -454
- package/apps/storefront/src/lib/orders/data/ordersStore.ts +0 -623
- package/apps/storefront/src/lib/orders/data/sourceAuthorityContract.ts +0 -380
- package/apps/storefront/src/lib/orders/data/sourceAuthorityStore.ts +0 -830
- package/apps/storefront/src/lib/orders/fixtures/orders.ts +0 -186
- package/apps/storefront/src/lib/orders/providers/foxyOrderClient.ts +0 -207
- package/apps/storefront/src/lib/orders/vault/appRecipientRead.ts +0 -222
- package/apps/storefront/src/lib/orders/vault/contactIntake.ts +0 -63
- package/apps/storefront/src/lib/orders/vault/contactRoutes.ts +0 -110
- package/apps/storefront/src/lib/orders/vault/kmsEnv.ts +0 -11
- package/apps/storefront/src/lib/orders/vault/orderContact.ts +0 -96
- package/apps/storefront/src/lib/orders/vault/orderContactVault.ts +0 -1427
- package/apps/storefront/src/lib/orders/vault/vault-test-support.ts +0 -258
- package/apps/storefront/src/lib/publication/d1/schema-apps.ts +0 -808
- package/apps/storefront/src/lib/publication/notifications/candidateConflictEmail.ts +0 -80
- package/apps/storefront/src/lib/publication/servingMode.ts +0 -52
- package/apps/storefront/src/lib/publication/shared/previewAnnotations/moduleAsset.ts +0 -65
- package/apps/storefront/src/lib/publication/shared/routedApiParam.ts +0 -38
- package/apps/storefront/src/lib/reporting/admin/viewmodels/reporting.ts +0 -34
- package/apps/storefront/src/lib/reporting/fixtures/reporting.ts +0 -51
- package/apps/storefront/src/lib/subscriptions/admin/viewmodels/subscriptions.ts +0 -106
- package/apps/storefront/src/lib/subscriptions/fixtures/subscriptions.ts +0 -398
- package/apps/storefront/src/pages/api/admin/activity-alerts.ts +0 -58
- package/apps/storefront/src/pages/api/admin/commerce-readiness.ts +0 -172
- package/apps/storefront/src/pages/api/admin/fulfillment/batches.ts +0 -59
- package/apps/storefront/src/pages/api/admin/fulfillment/orders/[id]/address.ts +0 -66
- package/apps/storefront/src/pages/api/admin/fulfillment/orders/[id].ts +0 -118
- package/apps/storefront/src/pages/api/admin/fulfillment/orders/contact-search.ts +0 -26
- package/apps/storefront/src/pages/api/admin/fulfillment/orders/contacts.ts +0 -22
- package/apps/storefront/src/pages/api/admin/interaction-insights.ts +0 -101
- package/apps/storefront/src/pages/api/admin/orders/[id].ts +0 -63
- package/apps/storefront/src/pages/api/admin/orders.ts +0 -65
- package/apps/storefront/src/pages/api/contact.ts +0 -144
- package/apps/storefront/src/scheduled/contactVaultSweep.ts +0 -113
- package/apps/storefront/src/styles/admin.css +0 -1161
- package/apps/storefront/test/pipeline/fake-preview-services.ts +0 -288
- package/apps/storefront/test/pipeline/harness.ts +0 -209
- package/apps/storefront/test/pipeline/intake-worker.mjs +0 -14
- package/apps/storefront/test/pipeline/matrix-faults.ts +0 -366
- package/apps/storefront/test/pipeline/pipeline-host.ts +0 -418
- package/apps/storefront/test/pipeline/pool-config.cjs +0 -85
- package/apps/storefront/test/pipeline/publish-kinds.ts +0 -279
- package/apps/storefront/test/pipeline/synthetic-job.ts +0 -303
- package/apps/storefront/test/pipeline-faults/matrix-lib.ts +0 -696
- package/apps/storefront/vitest.config.cts +0 -44
- package/apps/storefront/vitest.faults.config.cts +0 -13
- package/apps/storefront/vitest.workers.config.cts +0 -7
- package/packages/feedback/fixtures/v1/expected-findings.json +0 -16
- package/packages/feedback/fixtures/v1/feedback-action/invalid/carries-transport-credential.json +0 -14
- package/packages/feedback/fixtures/v1/feedback-action/invalid/control-char-in-description.json +0 -13
- package/packages/feedback/fixtures/v1/feedback-action/invalid/legacy-schema-version.json +0 -13
- package/packages/feedback/fixtures/v1/feedback-action/invalid/page-path-with-query.json +0 -14
- package/packages/feedback/fixtures/v1/feedback-action/invalid/title-too-short.json +0 -13
- package/packages/feedback/fixtures/v1/feedback-action/valid/element-problem.json +0 -33
- package/packages/feedback/fixtures/v1/feedback-action/valid/page-comment.json +0 -20
- package/packages/feedback/fixtures/v1/feedback-action/valid/region-improvement.json +0 -24
- package/packages/feedback/fixtures/v1/feedback-action/valid/text-selection-feature.json +0 -30
- package/packages/feedback/fixtures/v1/submission-receipt/invalid/accepted-at-not-utc.json +0 -9
- package/packages/feedback/fixtures/v1/submission-receipt/invalid/bad-feedback-id.json +0 -9
- package/packages/feedback/fixtures/v1/submission-receipt/invalid/legacy-contract-version.json +0 -9
- package/packages/feedback/fixtures/v1/submission-receipt/invalid/missing-replayed.json +0 -8
- package/packages/feedback/fixtures/v1/submission-receipt/valid/accepted.json +0 -9
- package/packages/feedback/fixtures/v1/submission-receipt/valid/fractional-seconds.json +0 -9
- package/packages/feedback/fixtures/v1/submission-receipt/valid/replayed.json +0 -9
- package/packages/feedback/fixtures/v1/target-evidence/invalid/page-kind-claims-structure.json +0 -6
- package/packages/feedback/fixtures/v1/target-evidence/invalid/path-too-deep.json +0 -17
- package/packages/feedback/fixtures/v1/target-evidence/invalid/relative-region-out-of-range.json +0 -11
- package/packages/feedback/fixtures/v1/target-evidence/invalid/selector-uses-class.json +0 -7
- package/packages/feedback/fixtures/v1/target-evidence/invalid/source-precision-without-anchor.json +0 -6
- package/packages/feedback/fixtures/v1/target-evidence/valid/element-structure.json +0 -21
- package/packages/feedback/fixtures/v1/target-evidence/valid/host-iframe.json +0 -14
- package/packages/feedback/fixtures/v1/target-evidence/valid/source-anchor.json +0 -12
- package/packages/feedback/fixtures/v1/target-evidence/valid/text-selection.json +0 -26
- package/packages/feedback/package.json +0 -35
- package/packages/feedback/scripts/build-player.mjs +0 -28
- package/packages/feedback/src/index.ts +0 -1
- package/packages/feedback/src/primitives/composer.ts +0 -639
- package/packages/feedback/src/primitives/dialog.ts +0 -263
- package/packages/feedback/src/primitives/hostAdapter.ts +0 -116
- package/packages/feedback/src/primitives/index.ts +0 -10
- package/packages/feedback/src/primitives/launcher.ts +0 -200
- package/packages/feedback/src/primitives/picker.ts +0 -663
- package/packages/feedback/src/primitives/redaction.ts +0 -204
- package/packages/feedback/src/primitives/selection.ts +0 -49
- package/packages/feedback/src/primitives/shiftAccelerator.ts +0 -160
- package/packages/feedback/src/primitives/styles.ts +0 -77
- package/packages/feedback/src/primitives/surface.ts +0 -124
- package/packages/feedback/src/primitives/target.ts +0 -293
- package/packages/feedback/src/tour/canonical.ts +0 -27
- package/packages/feedback/src/tour/index.ts +0 -3
- package/packages/feedback/src/tour/player/browser.ts +0 -5
- package/packages/feedback/src/tour/player/host.ts +0 -12
- package/packages/feedback/src/tour/player/index.ts +0 -205
- package/packages/feedback/src/tour/player/manifest.ts +0 -76
- package/packages/feedback/src/tour/player/player.css +0 -130
- package/packages/feedback/src/tour/player/resolver.ts +0 -12
- package/packages/feedback/src/tour/player/surface.ts +0 -295
- package/packages/feedback/src/tour/player/types.ts +0 -8
- package/packages/feedback/src/tour/resolve/core.ts +0 -267
- package/packages/feedback/src/tour/resolve/dom.ts +0 -115
- package/packages/feedback/src/tour/resolve/index.ts +0 -29
- package/packages/feedback/src/tour/sanitize.ts +0 -76
- package/packages/feedback/src/tour/schema.ts +0 -362
- package/packages/feedback/src/v1/guards.ts +0 -335
- package/packages/feedback/src/v1/index.ts +0 -3
- package/packages/feedback/src/v1/protectedSurfaces.ts +0 -32
- package/packages/feedback/src/v1/types.ts +0 -177
- package/packages/feedback/tsconfig.json +0 -9
- package/packages/feedback/vitest.config.cts +0 -21
|
@@ -1,671 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* `contact_messages` store — visitor messages from a store's contact form, kept in
|
|
3
|
-
* `STOREFRONT_APPS_DB` (migrations-apps/0022). Pure over a minimal SQL seam and an injected KMS
|
|
4
|
-
* client, so the Worker runs it against D1 and tests against `node:sqlite`.
|
|
5
|
-
*
|
|
6
|
-
* Field-level vault. The visitor's name, email, phone and message are each their own AES-256-GCM
|
|
7
|
-
* ciphertext (`lib/customers/contactVault/fieldEnvelope.ts`) under the tenant's `contact-message`
|
|
8
|
-
* data key; the AAD binds purpose, field, tenant, stage, message id, kid and the row's immutable
|
|
9
|
-
* `ceiling`, so a ciphertext moved to another field, row, tenant or stage reads as absent. Email and
|
|
10
|
-
* phone also carry blind indexes under the tenant's `blind-index` key for exact-match search.
|
|
11
|
-
* A message is sealed in ONE batch: any pending data-key rows first, the conditional insert, the
|
|
12
|
-
* key cleanups last (the dataKeys.ts seal protocol), so a refused or racing insert commits nothing.
|
|
13
|
-
*
|
|
14
|
-
* Retention (retention.ts `messageRetention`): 365 days from receipt; preview runs it on the
|
|
15
|
-
* compressed clock and deletes the whole row at receipt + the preview cutoff. Content is readable
|
|
16
|
-
* strictly before `min(expires_at, ceiling)`.
|
|
17
|
-
*
|
|
18
|
-
* Every method takes the tenant id and the routed stage and scopes its SQL by both: an id belonging
|
|
19
|
-
* to another tenant or stage is indistinguishable from an id that does not exist. Every read writes
|
|
20
|
-
* its `contact_access_audit` row before anything is decrypted. Nothing here logs, and every error is
|
|
21
|
-
* a fixed code.
|
|
22
|
-
*/
|
|
23
|
-
import { activeKey, cleanupStatement, keyForKid, type ActiveDataKey } from "@/lib/customers/contactVault/dataKeys.js";
|
|
24
|
-
import { openField, sealField, type FieldBinding } from "@/lib/customers/contactVault/fieldEnvelope.js";
|
|
25
|
-
import { blindIndex, normalizeEmail, normalizePhone } from "@/lib/customers/contactVault/blindIndex.js";
|
|
26
|
-
import { VaultKeyUnavailableError, type EncryptionContext, type KmsClient } from "@/lib/customers/contactVault/kms.js";
|
|
27
|
-
import { isGroupReadable, messageRetention, previewDeleteAt, readInstant } from "@/lib/customers/contactVault/retention.js";
|
|
28
|
-
import { RETENTION_POLICY } from "@/lib/customers/contactVault/retentionPolicy.js";
|
|
29
|
-
import {
|
|
30
|
-
AUDIT_RECORD_IDS_MAX,
|
|
31
|
-
admitAudit,
|
|
32
|
-
auditRecordIds,
|
|
33
|
-
auditStatement,
|
|
34
|
-
batchAuditStatement,
|
|
35
|
-
type ContactActor,
|
|
36
|
-
type VaultStage,
|
|
37
|
-
} from "@/lib/customers/contactVault/contactAudit.js";
|
|
38
|
-
|
|
39
|
-
export interface QueryStatement {
|
|
40
|
-
sql: string;
|
|
41
|
-
params?: readonly unknown[];
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
/** The SQL surface this store needs; D1's `fromD1` and the test harness both satisfy it. */
|
|
45
|
-
export interface ContactDb {
|
|
46
|
-
all<T = Record<string, unknown>>(sql: string, ...params: unknown[]): Promise<T[]>;
|
|
47
|
-
first<T = Record<string, unknown>>(sql: string, ...params: unknown[]): Promise<T | null>;
|
|
48
|
-
run(sql: string, ...params: unknown[]): Promise<void>;
|
|
49
|
-
exec(sql: string): Promise<void>;
|
|
50
|
-
/** D1 executes a batch sequentially inside one implicit transaction. */
|
|
51
|
-
batch?(statements: readonly QueryStatement[]): Promise<void>;
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
export const CONTACT_LIST_LIMIT = AUDIT_RECORD_IDS_MAX;
|
|
55
|
-
/** Insert attempts when a concurrent first seal for the tenant wins the data-key race. */
|
|
56
|
-
const SEAL_ATTEMPTS = 3;
|
|
57
|
-
const DAY_MS = 86_400_000;
|
|
58
|
-
|
|
59
|
-
export type ContactMessageStatus = "unread" | "read";
|
|
60
|
-
export type MessageField = "name" | "email" | "phone" | "message";
|
|
61
|
-
|
|
62
|
-
export interface NewContactMessage {
|
|
63
|
-
id: string;
|
|
64
|
-
tenantId: string;
|
|
65
|
-
stage: VaultStage;
|
|
66
|
-
name: string;
|
|
67
|
-
email: string;
|
|
68
|
-
phone: string;
|
|
69
|
-
message: string;
|
|
70
|
-
pagePath: string | null;
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
export interface ContactMessage {
|
|
74
|
-
id: string;
|
|
75
|
-
name: string;
|
|
76
|
-
email: string;
|
|
77
|
-
phone: string;
|
|
78
|
-
message: string;
|
|
79
|
-
pagePath: string | null;
|
|
80
|
-
status: ContactMessageStatus;
|
|
81
|
-
createdAt: string;
|
|
82
|
-
readAt: string | null;
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
/** An exact-match inbox filter; the value never reaches a log, an audit row or a URL. */
|
|
86
|
-
export type ContactSearch = { kind: "email"; value: string } | { kind: "phone"; value: string };
|
|
87
|
-
|
|
88
|
-
export type ContactRefusal =
|
|
89
|
-
| { ok: false; status: 404; reason: "not-found" }
|
|
90
|
-
| { ok: false; status: 410; reason: "contact-expired" }
|
|
91
|
-
| { ok: false; status: 429; reason: "quota" }
|
|
92
|
-
| { ok: false; status: 503; reason: "audit-unavailable" | "vault-key-unavailable" };
|
|
93
|
-
|
|
94
|
-
export type ListOutcome = { ok: true; messages: ContactMessage[] } | ContactRefusal;
|
|
95
|
-
export type SupportReadOutcome = { ok: true; message: ContactMessage } | ContactRefusal;
|
|
96
|
-
export type EraseOutcome = { ok: true } | ContactRefusal;
|
|
97
|
-
|
|
98
|
-
/** A message the store could not write; carries a fixed code only. */
|
|
99
|
-
export class ContactMessageNotStoredError extends Error {
|
|
100
|
-
constructor(readonly code: "contact-expired" | "seal-race-lost") {
|
|
101
|
-
super(code);
|
|
102
|
-
this.name = "ContactMessageNotStoredError";
|
|
103
|
-
}
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
interface SealedRow {
|
|
107
|
-
id: string;
|
|
108
|
-
msg_kid: string;
|
|
109
|
-
name_ct: string | null;
|
|
110
|
-
email_ct: string | null;
|
|
111
|
-
phone_ct: string | null;
|
|
112
|
-
message_ct: string;
|
|
113
|
-
ceiling: string;
|
|
114
|
-
expires_at: string;
|
|
115
|
-
page_path: string | null;
|
|
116
|
-
status: string;
|
|
117
|
-
created_at: string;
|
|
118
|
-
read_at: string | null;
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
const SEALED_COLUMNS =
|
|
122
|
-
"id, msg_kid, name_ct, email_ct, phone_ct, message_ct, ceiling, expires_at, page_path, status, created_at, read_at";
|
|
123
|
-
/** A row the store may act on: sealed, and strictly before both its expiry and its ceiling. */
|
|
124
|
-
const READABLE = "msg_kid IS NOT NULL AND message_ct IS NOT NULL AND ? < expires_at AND ? < ceiling";
|
|
125
|
-
/** Rows that still hold legacy plaintext in any column. */
|
|
126
|
-
const HOLDS_LEGACY =
|
|
127
|
-
"(legacy_name IS NOT NULL OR legacy_email IS NOT NULL OR legacy_phone IS NOT NULL OR legacy_message IS NOT NULL)";
|
|
128
|
-
const REFERENCES_MSG_KID = `SELECT 1 FROM contact_messages WHERE tenant_id = ? AND stage = ? AND msg_kid = ?`;
|
|
129
|
-
const REFERENCES_BIDX_KID = `SELECT 1 FROM order_contact_vault WHERE tenant_id = ? AND stage = ? AND bidx_kid = ?
|
|
130
|
-
UNION ALL SELECT 1 FROM contact_messages WHERE tenant_id = ? AND stage = ? AND bidx_kid = ?`;
|
|
131
|
-
|
|
132
|
-
function messageContext(tenantId: string, stage: VaultStage): EncryptionContext {
|
|
133
|
-
return { tenantId, stage, purpose: "contact-message" };
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
function blindIndexContext(tenantId: string, stage: VaultStage): EncryptionContext {
|
|
137
|
-
return { tenantId, stage, purpose: "blind-index" };
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
function fieldBinding(tenantId: string, stage: VaultStage, id: string, kid: string, ceiling: string, field: MessageField): FieldBinding {
|
|
141
|
-
return { purpose: "contact-message", field, tenantId, stage, recordId: id, kid, notAfter: ceiling };
|
|
142
|
-
}
|
|
143
|
-
|
|
144
|
-
function requireBatch(db: ContactDb): NonNullable<ContactDb["batch"]> {
|
|
145
|
-
if (!db.batch) throw new Error("D1 batch is unavailable");
|
|
146
|
-
return db.batch.bind(db);
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
function keyExists(ctx: EncryptionContext, kid: string): { sql: string; params: unknown[] } {
|
|
150
|
-
return {
|
|
151
|
-
sql: `SELECT 1 FROM contact_vault_data_keys WHERE tenant_id = ? AND stage = ? AND purpose = ? AND kid = ?`,
|
|
152
|
-
params: [ctx.tenantId, ctx.stage, ctx.purpose, kid],
|
|
153
|
-
};
|
|
154
|
-
}
|
|
155
|
-
|
|
156
|
-
function cleanups(ctx: EncryptionContext, key: ActiveDataKey, referenced: string, params: readonly unknown[]): QueryStatement[] {
|
|
157
|
-
return key.pending.length > 0 ? [cleanupStatement(ctx, key.kid, referenced, params)] : [];
|
|
158
|
-
}
|
|
159
|
-
|
|
160
|
-
interface SealedFields {
|
|
161
|
-
msgKid: string;
|
|
162
|
-
bidxKid: string | null;
|
|
163
|
-
nameCt: string | null;
|
|
164
|
-
emailCt: string | null;
|
|
165
|
-
emailBidx: string | null;
|
|
166
|
-
phoneCt: string | null;
|
|
167
|
-
phoneBidx: string | null;
|
|
168
|
-
messageCt: string;
|
|
169
|
-
/** Batch prefix (pending key rows), the key-existence guard for the record write, and the batch suffix (cleanups). */
|
|
170
|
-
pending: QueryStatement[];
|
|
171
|
-
guard: { sql: string; params: unknown[] };
|
|
172
|
-
cleanup: QueryStatement[];
|
|
173
|
-
}
|
|
174
|
-
|
|
175
|
-
/**
|
|
176
|
-
* Seal one message's fields under the tenant's active keys. Empty optional values store NULL; the
|
|
177
|
-
* message text is always sealed. Throws {@link VaultKeyUnavailableError} when KMS cannot serve.
|
|
178
|
-
*/
|
|
179
|
-
async function sealFields(
|
|
180
|
-
db: ContactDb,
|
|
181
|
-
kms: KmsClient,
|
|
182
|
-
tenantId: string,
|
|
183
|
-
stage: VaultStage,
|
|
184
|
-
id: string,
|
|
185
|
-
ceiling: string,
|
|
186
|
-
values: { name: string; email: string; phone: string; message: string },
|
|
187
|
-
now: Date,
|
|
188
|
-
): Promise<SealedFields> {
|
|
189
|
-
const msgCtx = messageContext(tenantId, stage);
|
|
190
|
-
const bidxCtx = blindIndexContext(tenantId, stage);
|
|
191
|
-
const email = normalizeEmail(values.email);
|
|
192
|
-
const phone = normalizePhone(values.phone);
|
|
193
|
-
const msgKey = await activeKey(db, kms, msgCtx, now);
|
|
194
|
-
const bidxKey = email !== null || phone !== null ? await activeKey(db, kms, bidxCtx, now) : null;
|
|
195
|
-
const seal = (field: MessageField, value: string) =>
|
|
196
|
-
sealField(msgKey.key, fieldBinding(tenantId, stage, id, msgKey.kid, ceiling, field), value);
|
|
197
|
-
const optional = (field: MessageField, value: string) => (value === "" ? Promise.resolve(null) : seal(field, value));
|
|
198
|
-
const msgGuard = keyExists(msgCtx, msgKey.kid);
|
|
199
|
-
const bidxGuard = bidxKey ? keyExists(bidxCtx, bidxKey.kid) : null;
|
|
200
|
-
return {
|
|
201
|
-
msgKid: msgKey.kid,
|
|
202
|
-
bidxKid: bidxKey?.kid ?? null,
|
|
203
|
-
nameCt: await optional("name", values.name),
|
|
204
|
-
emailCt: await optional("email", values.email),
|
|
205
|
-
emailBidx: bidxKey && email !== null ? await blindIndex(bidxKey.key, email) : null,
|
|
206
|
-
phoneCt: await optional("phone", values.phone),
|
|
207
|
-
phoneBidx: bidxKey && phone !== null ? await blindIndex(bidxKey.key, phone) : null,
|
|
208
|
-
messageCt: await seal("message", values.message),
|
|
209
|
-
pending: [...msgKey.pending, ...(bidxKey?.pending ?? [])],
|
|
210
|
-
guard: {
|
|
211
|
-
sql: `EXISTS (${msgGuard.sql})${bidxGuard ? ` AND EXISTS (${bidxGuard.sql})` : ""}`,
|
|
212
|
-
params: [...msgGuard.params, ...(bidxGuard?.params ?? [])],
|
|
213
|
-
},
|
|
214
|
-
cleanup: [
|
|
215
|
-
...cleanups(msgCtx, msgKey, REFERENCES_MSG_KID, [tenantId, stage, msgKey.kid]),
|
|
216
|
-
...(bidxKey ? cleanups(bidxCtx, bidxKey, REFERENCES_BIDX_KID, [tenantId, stage, bidxKey.kid, tenantId, stage, bidxKey.kid]) : []),
|
|
217
|
-
],
|
|
218
|
-
};
|
|
219
|
-
}
|
|
220
|
-
|
|
221
|
-
function isKeyUnavailable(error: unknown): boolean {
|
|
222
|
-
return error instanceof VaultKeyUnavailableError;
|
|
223
|
-
}
|
|
224
|
-
|
|
225
|
-
export class ContactMessagesStore {
|
|
226
|
-
constructor(
|
|
227
|
-
private readonly db: ContactDb,
|
|
228
|
-
private readonly kms: KmsClient,
|
|
229
|
-
private readonly now: () => Date = () => new Date(),
|
|
230
|
-
) {}
|
|
231
|
-
|
|
232
|
-
/**
|
|
233
|
-
* Seal and store one message in one batch. Throws {@link VaultKeyUnavailableError} (writing
|
|
234
|
-
* nothing) when KMS cannot serve, and {@link ContactMessageNotStoredError} when retention refuses
|
|
235
|
-
* or the data-key race is lost on every attempt.
|
|
236
|
-
*/
|
|
237
|
-
async insert(input: NewContactMessage): Promise<void> {
|
|
238
|
-
const received = this.now();
|
|
239
|
-
const retention = await messageRetention({ stage: input.stage, receivedAt: received, now: received });
|
|
240
|
-
if (retention.kind !== "ok") throw new ContactMessageNotStoredError("contact-expired");
|
|
241
|
-
const batch = requireBatch(this.db);
|
|
242
|
-
for (let attempt = 0; attempt < SEAL_ATTEMPTS; attempt++) {
|
|
243
|
-
const sealed = await sealFields(this.db, this.kms, input.tenantId, input.stage, input.id, retention.ceiling, input, received);
|
|
244
|
-
await batch([
|
|
245
|
-
...sealed.pending,
|
|
246
|
-
{
|
|
247
|
-
sql: `INSERT INTO contact_messages
|
|
248
|
-
(id, tenant_id, stage, msg_kid, bidx_kid, name_ct, email_ct, email_bidx, phone_ct, phone_bidx, message_ct,
|
|
249
|
-
ceiling, expires_at, time_scale, rule_version, page_path, status, created_at, notify_status, notify_attempts)
|
|
250
|
-
SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'unread', ?, 'pending', 0
|
|
251
|
-
WHERE ${sealed.guard.sql} AND NOT EXISTS (SELECT 1 FROM contact_messages WHERE id = ?)`,
|
|
252
|
-
params: [
|
|
253
|
-
input.id, input.tenantId, input.stage, sealed.msgKid, sealed.bidxKid, sealed.nameCt, sealed.emailCt, sealed.emailBidx,
|
|
254
|
-
sealed.phoneCt, sealed.phoneBidx, sealed.messageCt, retention.ceiling, retention.expiresAt, retention.timeScale,
|
|
255
|
-
retention.ruleVersion, input.pagePath, received.toISOString(), ...sealed.guard.params, input.id,
|
|
256
|
-
],
|
|
257
|
-
},
|
|
258
|
-
...sealed.cleanup,
|
|
259
|
-
]);
|
|
260
|
-
const stored = await this.db.first(
|
|
261
|
-
`SELECT 1 AS present FROM contact_messages WHERE id = ? AND tenant_id = ? AND stage = ? AND msg_kid = ?`,
|
|
262
|
-
input.id, input.tenantId, input.stage, sealed.msgKid,
|
|
263
|
-
);
|
|
264
|
-
if (stored) return;
|
|
265
|
-
}
|
|
266
|
-
throw new ContactMessageNotStoredError("seal-race-lost");
|
|
267
|
-
}
|
|
268
|
-
|
|
269
|
-
/**
|
|
270
|
-
* The owner inbox, newest first and capped at {@link CONTACT_LIST_LIMIT}, optionally narrowed by
|
|
271
|
-
* an exact email or phone match. Order: select the sealed rows, unwrap their keys (a KMS failure
|
|
272
|
-
* answers 503 with no audit row), commit ONE `list` (or `search`) audit row naming the message ids
|
|
273
|
-
* it returns and their count (never the searched value), then decrypt.
|
|
274
|
-
*/
|
|
275
|
-
async list(tenantId: string, stage: VaultStage, actor: ContactActor, auditId: string, search?: ContactSearch): Promise<ListOutcome> {
|
|
276
|
-
const now = this.now();
|
|
277
|
-
const iso = now.toISOString();
|
|
278
|
-
let rows: SealedRow[];
|
|
279
|
-
let keys: Map<string, CryptoKey | null>;
|
|
280
|
-
try {
|
|
281
|
-
rows = search ? await this.searchRows(tenantId, stage, iso, search) : await this.db.all<SealedRow>(
|
|
282
|
-
`SELECT ${SEALED_COLUMNS} FROM contact_messages
|
|
283
|
-
WHERE tenant_id = ? AND stage = ? AND ${READABLE}
|
|
284
|
-
ORDER BY created_at DESC, id DESC
|
|
285
|
-
LIMIT ?`,
|
|
286
|
-
tenantId, stage, iso, iso, CONTACT_LIST_LIMIT,
|
|
287
|
-
);
|
|
288
|
-
keys = await this.keysFor(tenantId, stage, rows);
|
|
289
|
-
} catch (error) {
|
|
290
|
-
if (isKeyUnavailable(error)) return { ok: false, status: 503, reason: "vault-key-unavailable" };
|
|
291
|
-
throw error;
|
|
292
|
-
}
|
|
293
|
-
const admitted = await admitAudit(this.db, auditStatement({
|
|
294
|
-
auditId, tenantId, stage, recordKind: "contact-message", recordId: auditRecordIds(rows.map((row) => row.id)), recordCount: rows.length,
|
|
295
|
-
actor, action: search ? "search" : "list", now,
|
|
296
|
-
}));
|
|
297
|
-
if (admitted === "quota") return { ok: false, status: 429, reason: "quota" };
|
|
298
|
-
if (admitted === "unavailable") return { ok: false, status: 503, reason: "audit-unavailable" };
|
|
299
|
-
const messages: ContactMessage[] = [];
|
|
300
|
-
for (const row of rows) {
|
|
301
|
-
const message = await this.open(tenantId, stage, row, keys.get(row.msg_kid) ?? null, now);
|
|
302
|
-
if (message) messages.push(message);
|
|
303
|
-
}
|
|
304
|
-
return { ok: true, messages };
|
|
305
|
-
}
|
|
306
|
-
|
|
307
|
-
/**
|
|
308
|
-
* ToT support reads one message. The caller has already proven a live staff selection and a live
|
|
309
|
-
* owner-consented grant. A preview message at or past received_at + the preview cutoff answers 410
|
|
310
|
-
* with zero writes; otherwise the audit row (with the staff quota in the same statement) commits first.
|
|
311
|
-
*/
|
|
312
|
-
async supportRead(tenantId: string, stage: VaultStage, id: string, actor: ContactActor, auditId: string): Promise<SupportReadOutcome> {
|
|
313
|
-
const now = this.now();
|
|
314
|
-
if (stage === "preview") {
|
|
315
|
-
const received = await this.db.first<{ created_at: unknown }>(
|
|
316
|
-
`SELECT created_at FROM contact_messages WHERE tenant_id = ? AND stage = ? AND id = ?`, tenantId, stage, id,
|
|
317
|
-
);
|
|
318
|
-
const receivedAt = received ? readInstant(received.created_at) : null;
|
|
319
|
-
if (receivedAt && now.getTime() >= Date.parse(previewDeleteAt(receivedAt))) return { ok: false, status: 410, reason: "contact-expired" };
|
|
320
|
-
}
|
|
321
|
-
const admitted = await admitAudit(this.db, auditStatement({
|
|
322
|
-
auditId, tenantId, stage, recordKind: "contact-message", recordId: id, actor, action: "read", now,
|
|
323
|
-
}));
|
|
324
|
-
if (admitted === "quota") return { ok: false, status: 429, reason: "quota" };
|
|
325
|
-
if (admitted === "unavailable") return { ok: false, status: 503, reason: "audit-unavailable" };
|
|
326
|
-
const iso = now.toISOString();
|
|
327
|
-
const row = await this.db.first<SealedRow>(
|
|
328
|
-
`SELECT ${SEALED_COLUMNS} FROM contact_messages WHERE tenant_id = ? AND stage = ? AND id = ? AND ${READABLE}`,
|
|
329
|
-
tenantId, stage, id, iso, iso,
|
|
330
|
-
);
|
|
331
|
-
if (!row) return { ok: false, status: 404, reason: "not-found" };
|
|
332
|
-
let key: CryptoKey | null;
|
|
333
|
-
try {
|
|
334
|
-
key = await keyForKid(this.db, this.kms, messageContext(tenantId, stage), row.msg_kid);
|
|
335
|
-
} catch (error) {
|
|
336
|
-
if (isKeyUnavailable(error)) return { ok: false, status: 503, reason: "vault-key-unavailable" };
|
|
337
|
-
throw error;
|
|
338
|
-
}
|
|
339
|
-
const message = await this.open(tenantId, stage, row, key, now);
|
|
340
|
-
return message ? { ok: true, message } : { ok: false, status: 404, reason: "not-found" };
|
|
341
|
-
}
|
|
342
|
-
|
|
343
|
-
async unreadCount(tenantId: string, stage: VaultStage): Promise<number> {
|
|
344
|
-
const iso = this.now().toISOString();
|
|
345
|
-
const row = await this.db.first<{ n: number }>(
|
|
346
|
-
`SELECT COUNT(*) AS n FROM contact_messages WHERE tenant_id = ? AND stage = ? AND status = 'unread' AND ${READABLE}`,
|
|
347
|
-
tenantId, stage, iso, iso,
|
|
348
|
-
);
|
|
349
|
-
return Number(row?.n ?? 0);
|
|
350
|
-
}
|
|
351
|
-
|
|
352
|
-
/** True when the tenant holds a readable message with this id in this stage (now marked read). */
|
|
353
|
-
async markRead(tenantId: string, stage: VaultStage, id: string): Promise<boolean> {
|
|
354
|
-
const iso = this.now().toISOString();
|
|
355
|
-
const rows = await this.db.all<{ id: string }>(
|
|
356
|
-
`UPDATE contact_messages
|
|
357
|
-
SET status = 'read', read_at = COALESCE(read_at, ?)
|
|
358
|
-
WHERE tenant_id = ? AND stage = ? AND id = ? AND ${READABLE}
|
|
359
|
-
RETURNING id`,
|
|
360
|
-
iso, tenantId, stage, id, iso, iso,
|
|
361
|
-
);
|
|
362
|
-
return rows.length > 0;
|
|
363
|
-
}
|
|
364
|
-
|
|
365
|
-
/** Erase one sealed message: its audit row and its delete commit in one batch, or neither does. */
|
|
366
|
-
async erase(tenantId: string, stage: VaultStage, id: string, actor: ContactActor, auditId: string): Promise<EraseOutcome> {
|
|
367
|
-
const now = this.now();
|
|
368
|
-
const rowSql = `SELECT 1 FROM contact_messages WHERE tenant_id = ? AND stage = ? AND id = ? AND message_ct IS NOT NULL`;
|
|
369
|
-
const exists = await this.db.first(rowSql, tenantId, stage, id);
|
|
370
|
-
if (!exists) return { ok: false, status: 404, reason: "not-found" };
|
|
371
|
-
const audit = auditStatement({
|
|
372
|
-
auditId, tenantId, stage, recordKind: "contact-message", recordId: id, actor, action: "erase", now,
|
|
373
|
-
requireRow: { sql: rowSql, params: [tenantId, stage, id] },
|
|
374
|
-
});
|
|
375
|
-
const statements: QueryStatement[] = [
|
|
376
|
-
batchAuditStatement(audit),
|
|
377
|
-
{
|
|
378
|
-
sql: `DELETE FROM contact_messages WHERE tenant_id = ? AND stage = ? AND id = ? AND message_ct IS NOT NULL
|
|
379
|
-
AND EXISTS (SELECT 1 FROM contact_access_audit WHERE audit_id = ?)`,
|
|
380
|
-
params: [tenantId, stage, id, auditId],
|
|
381
|
-
},
|
|
382
|
-
];
|
|
383
|
-
try {
|
|
384
|
-
await requireBatch(this.db)(statements);
|
|
385
|
-
} catch {
|
|
386
|
-
return { ok: false, status: 503, reason: "audit-unavailable" };
|
|
387
|
-
}
|
|
388
|
-
const audited = await this.db.first(`SELECT 1 AS present FROM contact_access_audit WHERE audit_id = ?`, auditId);
|
|
389
|
-
if (audited) return { ok: true };
|
|
390
|
-
const still = await this.db.first(rowSql, tenantId, stage, id);
|
|
391
|
-
return still ? { ok: false, status: 429, reason: "quota" } : { ok: false, status: 404, reason: "not-found" };
|
|
392
|
-
}
|
|
393
|
-
|
|
394
|
-
/**
|
|
395
|
-
* Readable rows whose blind index equals the searched value under ANY of the tenant's blind-index
|
|
396
|
-
* keys (rotation leaves still-sealed rows on the retired kid until they are recomputed). A tenant
|
|
397
|
-
* with no blind-index key holds no indexed row; a value that normalizes to nothing matches nothing.
|
|
398
|
-
*/
|
|
399
|
-
private async searchRows(tenantId: string, stage: VaultStage, iso: string, search: ContactSearch): Promise<SealedRow[]> {
|
|
400
|
-
const normalized = search.kind === "email" ? normalizeEmail(search.value) : normalizePhone(search.value);
|
|
401
|
-
if (normalized === null) return [];
|
|
402
|
-
const ctx = blindIndexContext(tenantId, stage);
|
|
403
|
-
const kids = await this.db.all<{ kid: string }>(
|
|
404
|
-
`SELECT kid FROM contact_vault_data_keys WHERE tenant_id = ? AND stage = ? AND purpose = 'blind-index' ORDER BY created_at, kid`,
|
|
405
|
-
tenantId, stage,
|
|
406
|
-
);
|
|
407
|
-
const pairs: unknown[] = [];
|
|
408
|
-
for (const { kid } of kids) {
|
|
409
|
-
const key = await keyForKid(this.db, this.kms, ctx, kid);
|
|
410
|
-
if (key) pairs.push(kid, await blindIndex(key, normalized));
|
|
411
|
-
}
|
|
412
|
-
if (pairs.length === 0) return [];
|
|
413
|
-
const column = search.kind === "email" ? "email_bidx" : "phone_bidx";
|
|
414
|
-
const match = Array.from({ length: pairs.length / 2 }, () => `(bidx_kid = ? AND ${column} = ?)`).join(" OR ");
|
|
415
|
-
return this.db.all<SealedRow>(
|
|
416
|
-
`SELECT ${SEALED_COLUMNS} FROM contact_messages
|
|
417
|
-
WHERE tenant_id = ? AND stage = ? AND ${READABLE} AND (${match})
|
|
418
|
-
ORDER BY created_at DESC, id DESC
|
|
419
|
-
LIMIT ?`,
|
|
420
|
-
tenantId, stage, iso, iso, ...pairs, CONTACT_LIST_LIMIT,
|
|
421
|
-
);
|
|
422
|
-
}
|
|
423
|
-
|
|
424
|
-
/** Each distinct kid's key, its row read from D1 once per call (null when the row is gone). */
|
|
425
|
-
private async keysFor(tenantId: string, stage: VaultStage, rows: readonly SealedRow[]): Promise<Map<string, CryptoKey | null>> {
|
|
426
|
-
const keys = new Map<string, CryptoKey | null>();
|
|
427
|
-
for (const kid of new Set(rows.map((row) => row.msg_kid))) {
|
|
428
|
-
keys.set(kid, await keyForKid(this.db, this.kms, messageContext(tenantId, stage), kid));
|
|
429
|
-
}
|
|
430
|
-
return keys;
|
|
431
|
-
}
|
|
432
|
-
|
|
433
|
-
/**
|
|
434
|
-
* Decrypt one row, or null when it is past retention, its key is gone, or any present field does
|
|
435
|
-
* not authenticate under its own binding.
|
|
436
|
-
*/
|
|
437
|
-
private async open(tenantId: string, stage: VaultStage, row: SealedRow, key: CryptoKey | null, now: Date): Promise<ContactMessage | null> {
|
|
438
|
-
if (!key || !isGroupReadable(now, row.expires_at, row.ceiling)) return null;
|
|
439
|
-
const read = async (field: MessageField, sealed: string | null): Promise<string | null> =>
|
|
440
|
-
sealed === null ? "" : openField(key, fieldBinding(tenantId, stage, row.id, row.msg_kid, row.ceiling, field), sealed);
|
|
441
|
-
const name = await read("name", row.name_ct);
|
|
442
|
-
const email = await read("email", row.email_ct);
|
|
443
|
-
const phone = await read("phone", row.phone_ct);
|
|
444
|
-
const message = await read("message", row.message_ct);
|
|
445
|
-
if (name === null || email === null || phone === null || message === null) return null;
|
|
446
|
-
return {
|
|
447
|
-
id: row.id,
|
|
448
|
-
name,
|
|
449
|
-
email,
|
|
450
|
-
phone,
|
|
451
|
-
message,
|
|
452
|
-
pagePath: row.page_path,
|
|
453
|
-
status: row.status === "read" ? "read" : "unread",
|
|
454
|
-
createdAt: row.created_at,
|
|
455
|
-
readAt: row.read_at,
|
|
456
|
-
};
|
|
457
|
-
}
|
|
458
|
-
}
|
|
459
|
-
|
|
460
|
-
export interface MessagePurgeCounts {
|
|
461
|
-
/** Rows whose expired content (ciphertexts, blind indexes, legacy plaintext) was nulled. */
|
|
462
|
-
contentCleared: number;
|
|
463
|
-
/** Preview rows deleted whole at receipt + the preview cutoff. */
|
|
464
|
-
previewDeleted: number;
|
|
465
|
-
/** Publication rows deleted once their content was gone and their ceiling had passed. */
|
|
466
|
-
publicationDeleted: number;
|
|
467
|
-
}
|
|
468
|
-
|
|
469
|
-
export const PURGE_PAGE_SIZE = 500;
|
|
470
|
-
export const PURGE_MAX_PAGES = 20;
|
|
471
|
-
|
|
472
|
-
/**
|
|
473
|
-
* The hourly purge, across all tenants and stages, under ONE clock reading:
|
|
474
|
-
* 1. null the content of every row at or past `min(expires_at, ceiling)`: each ciphertext, both
|
|
475
|
-
* blind indexes, `bidx_kid` and any legacy plaintext. `msg_kid` stays, so the row can never
|
|
476
|
-
* be refilled (the 0022 trigger guards the ciphertexts while a kid is set);
|
|
477
|
-
* 2. delete every preview row at or past receipt + the preview cutoff, content or not;
|
|
478
|
-
* 3. delete every publication row whose content is gone and whose ceiling has passed. A message
|
|
479
|
-
* has no facts row (design 8c), so once its content is gone nothing left in it is worth
|
|
480
|
-
* keeping: the row goes rather than lingering as metadata.
|
|
481
|
-
* Bounded: each step works in pages of `pageSize`, at most `maxPages` pages per step per run; the
|
|
482
|
-
* next run takes whatever is left. Returns counts only. An unreadable clock throws.
|
|
483
|
-
*/
|
|
484
|
-
export async function purgeContactMessages(
|
|
485
|
-
db: ContactDb,
|
|
486
|
-
now: Date,
|
|
487
|
-
pageSize = PURGE_PAGE_SIZE,
|
|
488
|
-
maxPages = PURGE_MAX_PAGES,
|
|
489
|
-
): Promise<MessagePurgeCounts> {
|
|
490
|
-
if (Number.isNaN(now.getTime())) throw new Error("contact message purge: unreadable clock");
|
|
491
|
-
const iso = now.toISOString();
|
|
492
|
-
const previewCutoff = new Date(now.getTime() - RETENTION_POLICY.previewCutoffDays * DAY_MS).toISOString();
|
|
493
|
-
const paged = async (sql: string, params: unknown[]): Promise<number> => {
|
|
494
|
-
let total = 0;
|
|
495
|
-
for (let page = 0; page < maxPages; page++) {
|
|
496
|
-
const rows = await db.all<{ id: string }>(sql, ...params, pageSize);
|
|
497
|
-
total += rows.length;
|
|
498
|
-
if (rows.length < pageSize) break;
|
|
499
|
-
}
|
|
500
|
-
return total;
|
|
501
|
-
};
|
|
502
|
-
const contentCleared = await paged(
|
|
503
|
-
`UPDATE contact_messages
|
|
504
|
-
SET name_ct = NULL, email_ct = NULL, email_bidx = NULL, phone_ct = NULL, phone_bidx = NULL, message_ct = NULL,
|
|
505
|
-
bidx_kid = NULL, legacy_name = NULL, legacy_email = NULL, legacy_phone = NULL, legacy_message = NULL
|
|
506
|
-
WHERE id IN (
|
|
507
|
-
SELECT id FROM contact_messages
|
|
508
|
-
WHERE (expires_at <= ? OR ceiling <= ?)
|
|
509
|
-
AND (name_ct IS NOT NULL OR email_ct IS NOT NULL OR email_bidx IS NOT NULL OR phone_ct IS NOT NULL
|
|
510
|
-
OR phone_bidx IS NOT NULL OR message_ct IS NOT NULL OR bidx_kid IS NOT NULL OR ${HOLDS_LEGACY})
|
|
511
|
-
LIMIT ?)
|
|
512
|
-
RETURNING id`,
|
|
513
|
-
[iso, iso],
|
|
514
|
-
);
|
|
515
|
-
const previewDeleted = await paged(
|
|
516
|
-
`DELETE FROM contact_messages
|
|
517
|
-
WHERE id IN (SELECT id FROM contact_messages WHERE stage = 'preview' AND created_at <= ? LIMIT ?)
|
|
518
|
-
RETURNING id`,
|
|
519
|
-
[previewCutoff],
|
|
520
|
-
);
|
|
521
|
-
const publicationDeleted = await paged(
|
|
522
|
-
`DELETE FROM contact_messages
|
|
523
|
-
WHERE id IN (
|
|
524
|
-
SELECT id FROM contact_messages
|
|
525
|
-
WHERE stage = 'publication' AND ceiling <= ?
|
|
526
|
-
AND name_ct IS NULL AND email_ct IS NULL AND phone_ct IS NULL AND message_ct IS NULL
|
|
527
|
-
AND email_bidx IS NULL AND phone_bidx IS NULL AND NOT ${HOLDS_LEGACY}
|
|
528
|
-
LIMIT ?)
|
|
529
|
-
RETURNING id`,
|
|
530
|
-
[iso],
|
|
531
|
-
);
|
|
532
|
-
return { contentCleared, previewDeleted, publicationDeleted };
|
|
533
|
-
}
|
|
534
|
-
|
|
535
|
-
interface BlindIndexRow {
|
|
536
|
-
id: string;
|
|
537
|
-
tenant_id: string;
|
|
538
|
-
stage: VaultStage;
|
|
539
|
-
msg_kid: string;
|
|
540
|
-
bidx_kid: string;
|
|
541
|
-
email_ct: string | null;
|
|
542
|
-
email_bidx: string | null;
|
|
543
|
-
phone_ct: string | null;
|
|
544
|
-
phone_bidx: string | null;
|
|
545
|
-
ceiling: string;
|
|
546
|
-
}
|
|
547
|
-
|
|
548
|
-
/**
|
|
549
|
-
* Blind-index rotation recompute for messages (orderContactVault.ts `rotateContactVaultKeys` runs
|
|
550
|
-
* it): up to `limit` sealed rows whose bidx_kid is retired are re-indexed under the active
|
|
551
|
-
* blind-index key, by decrypting email and phone under the message key, in ONE update per row that
|
|
552
|
-
* moves both indexes and bidx_kid together, conditioned on the row being unchanged since it was
|
|
553
|
-
* read. An index whose field no longer opens is cleared. Returns the rows moved. Throws
|
|
554
|
-
* {@link VaultKeyUnavailableError} when KMS cannot serve.
|
|
555
|
-
*/
|
|
556
|
-
export async function recomputeMessageBlindIndexes(
|
|
557
|
-
db: Pick<ContactDb, "all" | "first">,
|
|
558
|
-
kms: KmsClient,
|
|
559
|
-
now: Date,
|
|
560
|
-
limit: number,
|
|
561
|
-
): Promise<number> {
|
|
562
|
-
const rows = await db.all<BlindIndexRow>(
|
|
563
|
-
`SELECT m.id, m.tenant_id, m.stage, m.msg_kid, m.bidx_kid, m.email_ct, m.email_bidx, m.phone_ct, m.phone_bidx, m.ceiling
|
|
564
|
-
FROM contact_messages m
|
|
565
|
-
JOIN contact_vault_data_keys k ON k.tenant_id = m.tenant_id AND k.stage = m.stage AND k.purpose = 'blind-index' AND k.kid = m.bidx_kid
|
|
566
|
-
WHERE k.retired_at IS NOT NULL AND m.msg_kid IS NOT NULL
|
|
567
|
-
ORDER BY m.id LIMIT ?`,
|
|
568
|
-
Math.max(0, Math.floor(limit)),
|
|
569
|
-
);
|
|
570
|
-
let moved = 0;
|
|
571
|
-
for (const row of rows) {
|
|
572
|
-
const active = await activeKey(db, kms, blindIndexContext(row.tenant_id, row.stage), now);
|
|
573
|
-
// Rotation installs the new active key before this runs; never mint one from here.
|
|
574
|
-
if (active.pending.length > 0 || active.kid === row.bidx_kid) continue;
|
|
575
|
-
const msgKey = await keyForKid(db, kms, messageContext(row.tenant_id, row.stage), row.msg_kid);
|
|
576
|
-
const reindex = async (field: "email" | "phone", sealed: string | null, current: string | null): Promise<string | null> => {
|
|
577
|
-
if (current === null || sealed === null || !msgKey) return null;
|
|
578
|
-
const value = await openField(msgKey, fieldBinding(row.tenant_id, row.stage, row.id, row.msg_kid, row.ceiling, field), sealed);
|
|
579
|
-
const normalized = value === null ? null : field === "email" ? normalizeEmail(value) : normalizePhone(value);
|
|
580
|
-
return normalized === null ? null : blindIndex(active.key, normalized);
|
|
581
|
-
};
|
|
582
|
-
const email = await reindex("email", row.email_ct, row.email_bidx);
|
|
583
|
-
const phone = await reindex("phone", row.phone_ct, row.phone_bidx);
|
|
584
|
-
const updated = await db.all(
|
|
585
|
-
`UPDATE contact_messages SET email_bidx = ?, phone_bidx = ?, bidx_kid = ?
|
|
586
|
-
WHERE id = ? AND msg_kid = ? AND bidx_kid = ? AND email_bidx IS ? AND phone_bidx IS ? AND email_ct IS ? AND phone_ct IS ?
|
|
587
|
-
AND EXISTS (SELECT 1 FROM contact_vault_data_keys
|
|
588
|
-
WHERE tenant_id = ? AND stage = ? AND purpose = 'blind-index' AND kid = ? AND retired_at IS NULL)
|
|
589
|
-
RETURNING id`,
|
|
590
|
-
email, phone, email === null && phone === null ? null : active.kid,
|
|
591
|
-
row.id, row.msg_kid, row.bidx_kid, row.email_bidx, row.phone_bidx, row.email_ct, row.phone_ct,
|
|
592
|
-
row.tenant_id, row.stage, active.kid,
|
|
593
|
-
);
|
|
594
|
-
moved += updated.length;
|
|
595
|
-
}
|
|
596
|
-
return moved;
|
|
597
|
-
}
|
|
598
|
-
|
|
599
|
-
interface LegacyRow {
|
|
600
|
-
id: string;
|
|
601
|
-
tenant_id: string;
|
|
602
|
-
stage: VaultStage;
|
|
603
|
-
ceiling: string;
|
|
604
|
-
expires_at: string;
|
|
605
|
-
legacy_name: string | null;
|
|
606
|
-
legacy_email: string | null;
|
|
607
|
-
legacy_phone: string | null;
|
|
608
|
-
legacy_message: string | null;
|
|
609
|
-
}
|
|
610
|
-
|
|
611
|
-
/**
|
|
612
|
-
* Seal up to `limit` rows still holding legacy plaintext (oldest id first), across all tenants.
|
|
613
|
-
* Each row is sealed field by field under its own tenant and stage keys, keeping its recorded
|
|
614
|
-
* ceiling, and ONE statement writes `msg_kid`, every ciphertext and blind index and nulls every
|
|
615
|
-
* `legacy_*` column, only while the row is still unsealed (any pending key rows before it and the
|
|
616
|
-
* key cleanups after it, in one batch). A row already past its retention is not sealed: its
|
|
617
|
-
* plaintext is nulled instead. `sealed` counts rows that no longer hold plaintext; `remaining`
|
|
618
|
-
* counts the rows that still do. Throws {@link VaultKeyUnavailableError} when KMS cannot serve.
|
|
619
|
-
*/
|
|
620
|
-
export async function sealLegacyContactMessages(
|
|
621
|
-
db: ContactDb,
|
|
622
|
-
kms: KmsClient,
|
|
623
|
-
now: Date,
|
|
624
|
-
limit: number,
|
|
625
|
-
): Promise<{ sealed: number; remaining: number }> {
|
|
626
|
-
if (Number.isNaN(now.getTime())) throw new Error("contact message sealing: unreadable clock");
|
|
627
|
-
const batch = requireBatch(db);
|
|
628
|
-
const rows = await db.all<LegacyRow>(
|
|
629
|
-
`SELECT id, tenant_id, stage, ceiling, expires_at, legacy_name, legacy_email, legacy_phone, legacy_message
|
|
630
|
-
FROM contact_messages WHERE msg_kid IS NULL AND ${HOLDS_LEGACY}
|
|
631
|
-
ORDER BY id LIMIT ?`,
|
|
632
|
-
Math.max(0, Math.floor(limit)),
|
|
633
|
-
);
|
|
634
|
-
const unsealed = `id = ? AND msg_kid IS NULL AND ${HOLDS_LEGACY}`;
|
|
635
|
-
let sealed = 0;
|
|
636
|
-
for (const row of rows) {
|
|
637
|
-
if (!isGroupReadable(now, row.expires_at, row.ceiling)) {
|
|
638
|
-
const cleared = await db.all<{ id: string }>(
|
|
639
|
-
`UPDATE contact_messages SET legacy_name = NULL, legacy_email = NULL, legacy_phone = NULL, legacy_message = NULL
|
|
640
|
-
WHERE ${unsealed} RETURNING id`,
|
|
641
|
-
row.id,
|
|
642
|
-
);
|
|
643
|
-
sealed += cleared.length;
|
|
644
|
-
continue;
|
|
645
|
-
}
|
|
646
|
-
const fields = await sealFields(db, kms, row.tenant_id, row.stage, row.id, row.ceiling, {
|
|
647
|
-
name: row.legacy_name ?? "",
|
|
648
|
-
email: row.legacy_email ?? "",
|
|
649
|
-
phone: row.legacy_phone ?? "",
|
|
650
|
-
message: row.legacy_message ?? "",
|
|
651
|
-
}, now);
|
|
652
|
-
await batch([
|
|
653
|
-
...fields.pending,
|
|
654
|
-
{
|
|
655
|
-
sql: `UPDATE contact_messages
|
|
656
|
-
SET msg_kid = ?, bidx_kid = ?, name_ct = ?, email_ct = ?, email_bidx = ?, phone_ct = ?, phone_bidx = ?, message_ct = ?,
|
|
657
|
-
legacy_name = NULL, legacy_email = NULL, legacy_phone = NULL, legacy_message = NULL
|
|
658
|
-
WHERE ${unsealed} AND ${fields.guard.sql}`,
|
|
659
|
-
params: [
|
|
660
|
-
fields.msgKid, fields.bidxKid, fields.nameCt, fields.emailCt, fields.emailBidx, fields.phoneCt, fields.phoneBidx,
|
|
661
|
-
fields.messageCt, row.id, ...fields.guard.params,
|
|
662
|
-
],
|
|
663
|
-
},
|
|
664
|
-
...fields.cleanup,
|
|
665
|
-
]);
|
|
666
|
-
const done = await db.first(`SELECT 1 AS present FROM contact_messages WHERE id = ? AND msg_kid = ?`, row.id, fields.msgKid);
|
|
667
|
-
if (done) sealed++;
|
|
668
|
-
}
|
|
669
|
-
const left = await db.first<{ n: number }>(`SELECT COUNT(*) AS n FROM contact_messages WHERE ${HOLDS_LEGACY}`);
|
|
670
|
-
return { sealed, remaining: Number(left?.n ?? 0) };
|
|
671
|
-
}
|