@cosmicdrift/kumiko-samples 0.413.1 → 0.415.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 (479) hide show
  1. package/package.json +1 -1
  2. package/packages/bundled-features/package.json +16 -1
  3. package/packages/bundled-features/src/admin-shell/changes.json +6 -0
  4. package/packages/bundled-features/src/admin-shell/feature.ts +8 -7
  5. package/packages/bundled-features/src/agent-tools/agent-doc-lint.ts +5 -1
  6. package/packages/bundled-features/src/agent-tools/agent-manifest.ts +36 -27
  7. package/packages/bundled-features/src/agent-tools/api-docs/collect-events.ts +8 -1
  8. package/packages/bundled-features/src/agent-tools/api-docs/collect.ts +3 -2
  9. package/packages/bundled-features/src/agent-tools/api-docs/generate.ts +6 -0
  10. package/packages/bundled-features/src/agent-tools/api-docs/index.ts +1 -0
  11. package/packages/bundled-features/src/agent-tools/api-docs/problems.ts +38 -1
  12. package/packages/bundled-features/src/agent-tools/api-docs/render-openapi.ts +1 -0
  13. package/packages/bundled-features/src/agent-tools/api-docs/resolve-config.ts +17 -0
  14. package/packages/bundled-features/src/agent-tools/api-docs/scope-slug-collisions.ts +17 -0
  15. package/packages/bundled-features/src/agent-tools/api-docs/translation-gaps.ts +42 -0
  16. package/packages/bundled-features/src/agent-tools/api-docs/webhook-example-problems.ts +30 -0
  17. package/packages/bundled-features/src/agent-tools/changes.json +12 -0
  18. package/packages/bundled-features/src/agent-tools/index.ts +1 -0
  19. package/packages/bundled-features/src/agent-tools/labels.ts +19 -6
  20. package/packages/bundled-features/src/agent-tools/tool-catalog.ts +18 -7
  21. package/packages/bundled-features/src/agent-tools/tool-dispatch.ts +14 -1
  22. package/packages/bundled-features/src/agent-tools/types.ts +4 -0
  23. package/packages/bundled-features/src/audit/event-classification.ts +6 -0
  24. package/packages/bundled-features/src/audit/web/i18n.ts +1 -0
  25. package/packages/bundled-features/src/auth-email-password/changes.json +18 -0
  26. package/packages/bundled-features/src/auth-email-password/errors.ts +0 -13
  27. package/packages/bundled-features/src/auth-email-password/handlers/invite-signup-complete.write.ts +147 -121
  28. package/packages/bundled-features/src/auth-email-password/handlers/login-options.query.ts +1 -1
  29. package/packages/bundled-features/src/auth-email-password/handlers/request-account-unlock.write.ts +1 -1
  30. package/packages/bundled-features/src/auth-email-password/handlers/request-email-verification.write.ts +0 -1
  31. package/packages/bundled-features/src/auth-email-password/handlers/request-password-reset.write.ts +0 -1
  32. package/packages/bundled-features/src/auth-email-password/handlers/self-registration-status.query.ts +1 -1
  33. package/packages/bundled-features/src/auth-email-password/reset-token.ts +0 -2
  34. package/packages/bundled-features/src/auth-email-password/seeding.ts +39 -7
  35. package/packages/bundled-features/src/auth-email-password/signup-token-store.ts +2 -3
  36. package/packages/bundled-features/src/auth-email-password/unlock-token.ts +0 -2
  37. package/packages/bundled-features/src/auth-email-password/verification-token.ts +0 -2
  38. package/packages/bundled-features/src/auth-email-password/web/auth-form-primitives.tsx +2 -2
  39. package/packages/bundled-features/src/auth-email-password/web/auth-gate.tsx +2 -2
  40. package/packages/bundled-features/src/auth-email-password/web/auth-redirect.ts +5 -0
  41. package/packages/bundled-features/src/auth-email-password/web/forgot-password-screen.tsx +1 -6
  42. package/packages/bundled-features/src/auth-email-password/web/invite-accept-screen.tsx +1 -1
  43. package/packages/bundled-features/src/auth-email-password/web/return-path.ts +2 -1
  44. package/packages/bundled-features/src/auth-email-password/web/session.tsx +12 -13
  45. package/packages/bundled-features/src/auth-email-password/web/signup-screen.tsx +1 -6
  46. package/packages/bundled-features/src/auth-email-password/web/static-account.ts +6 -1
  47. package/packages/bundled-features/src/auth-email-password/web/tenant-switcher.tsx +1 -1
  48. package/packages/bundled-features/src/auth-email-password/web/token-confirm-screen.tsx +4 -5
  49. package/packages/bundled-features/src/auth-email-password/web/user-menu.tsx +1 -1
  50. package/packages/bundled-features/src/auth-mfa/changes.json +6 -0
  51. package/packages/bundled-features/src/auth-mfa/web/mfa-code-or-recovery-field.tsx +17 -1
  52. package/packages/bundled-features/src/auth-mfa/web/mfa-disable-dialog.tsx +1 -1
  53. package/packages/bundled-features/src/auth-mfa/web/mfa-regenerate-recovery-dialog.tsx +1 -1
  54. package/packages/bundled-features/src/auth-mfa/web/mfa-setup-preauth-screen.tsx +1 -1
  55. package/packages/bundled-features/src/auth-mfa/web/mfa-verify-screen.tsx +16 -47
  56. package/packages/bundled-features/src/auth-mfa-user-data/index.ts +5 -6
  57. package/packages/bundled-features/src/billing-foundation/aggregate-id.ts +0 -4
  58. package/packages/bundled-features/src/billing-foundation/changes.json +61 -0
  59. package/packages/bundled-features/src/billing-foundation/checkout-core.ts +19 -1
  60. package/packages/bundled-features/src/billing-foundation/checkout-ledger.ts +67 -0
  61. package/packages/bundled-features/src/billing-foundation/consumer-protection/consent-gate.ts +2 -1
  62. package/packages/bundled-features/src/billing-foundation/consumer-protection/consent-text.ts +49 -2
  63. package/packages/bundled-features/src/billing-foundation/consumer-protection/termination-open-cancels.ts +5 -0
  64. package/packages/bundled-features/src/billing-foundation/consumer-protection/termination-provider-timeout.ts +23 -0
  65. package/packages/bundled-features/src/billing-foundation/consumer-protection/termination-record.ts +12 -7
  66. package/packages/bundled-features/src/billing-foundation/consumer-protection/termination-revoke.ts +1 -1
  67. package/packages/bundled-features/src/billing-foundation/events.ts +51 -10
  68. package/packages/bundled-features/src/billing-foundation/feature.ts +15 -1
  69. package/packages/bundled-features/src/billing-foundation/handlers/billing-plans.query.ts +47 -14
  70. package/packages/bundled-features/src/billing-foundation/handlers/create-checkout-session.write.ts +9 -1
  71. package/packages/bundled-features/src/billing-foundation/handlers/process-event.write.ts +183 -17
  72. package/packages/bundled-features/src/billing-foundation/handlers/process-payment-event.write.ts +35 -10
  73. package/packages/bundled-features/src/billing-foundation/handlers/record-checkout-opened.write.ts +25 -0
  74. package/packages/bundled-features/src/billing-foundation/handlers/start-plan-checkout.write.ts +9 -1
  75. package/packages/bundled-features/src/billing-foundation/handlers/switch-plan.write.ts +16 -4
  76. package/packages/bundled-features/src/billing-foundation/i18n.ts +3 -0
  77. package/packages/bundled-features/src/billing-foundation/pending-plan-switch.ts +80 -0
  78. package/packages/bundled-features/src/billing-foundation/scrub-raw-payload-headers.ts +50 -0
  79. package/packages/bundled-features/src/billing-foundation/types.ts +47 -30
  80. package/packages/bundled-features/src/billing-foundation/validate-options.ts +18 -0
  81. package/packages/bundled-features/src/billing-foundation/web/billing-plans-panel.tsx +10 -5
  82. package/packages/bundled-features/src/billing-foundation/web/cancel-contract-dialog.tsx +1 -1
  83. package/packages/bundled-features/src/billing-foundation/web/checkout-consent-dialog.tsx +1 -1
  84. package/packages/bundled-features/src/billing-foundation/web/constants.ts +5 -2
  85. package/packages/bundled-features/src/billing-foundation/web/plan-switch-confirm-dialog.tsx +1 -1
  86. package/packages/bundled-features/src/billing-foundation/webhook-handler.ts +65 -17
  87. package/packages/bundled-features/src/cap-counter/aggregate-id.ts +0 -2
  88. package/packages/bundled-features/src/cap-counter/changes.json +6 -0
  89. package/packages/bundled-features/src/cap-counter/stock-cap-guard.ts +19 -4
  90. package/packages/bundled-features/src/cap-overview/changes.json +6 -0
  91. package/packages/bundled-features/src/cap-overview/handlers/tenant-caps-list.query.ts +22 -6
  92. package/packages/bundled-features/src/cap-overview/i18n.ts +1 -0
  93. package/packages/bundled-features/src/cap-overview/index.ts +1 -0
  94. package/packages/bundled-features/src/cap-overview/types.ts +11 -1
  95. package/packages/bundled-features/src/cap-overview/web/cap-cards-panel.tsx +6 -2
  96. package/packages/bundled-features/src/cap-overview/web/cap-usage-bar.tsx +10 -1
  97. package/packages/bundled-features/src/cap-overview/web/usage-math.ts +5 -0
  98. package/packages/bundled-features/src/channel-in-app/changes.json +6 -0
  99. package/packages/bundled-features/src/channel-in-app/handlers/read-state-by-keys.query.ts +2 -2
  100. package/packages/bundled-features/src/channel-whatsapp/aggregate-id.ts +29 -0
  101. package/packages/bundled-features/src/channel-whatsapp/changes.json +32 -0
  102. package/packages/bundled-features/src/channel-whatsapp/constants.ts +46 -0
  103. package/packages/bundled-features/src/channel-whatsapp/events.ts +94 -0
  104. package/packages/bundled-features/src/channel-whatsapp/feature.ts +72 -0
  105. package/packages/bundled-features/src/channel-whatsapp/graph-client.ts +398 -0
  106. package/packages/bundled-features/src/channel-whatsapp/in-memory-meta.ts +300 -0
  107. package/packages/bundled-features/src/channel-whatsapp/inbound-handlers.ts +210 -0
  108. package/packages/bundled-features/src/channel-whatsapp/index.ts +66 -0
  109. package/packages/bundled-features/src/channel-whatsapp/meta-signature.ts +26 -0
  110. package/packages/bundled-features/src/channel-whatsapp/options.ts +149 -0
  111. package/packages/bundled-features/src/channel-whatsapp/pii.ts +109 -0
  112. package/packages/bundled-features/src/channel-whatsapp/webhook-normalize.ts +247 -0
  113. package/packages/bundled-features/src/channel-whatsapp/webhook-routes.ts +185 -0
  114. package/packages/bundled-features/src/compliance-profiles/changes.json +5 -0
  115. package/packages/bundled-features/src/compliance-profiles/handlers/set-profile.write.ts +2 -0
  116. package/packages/bundled-features/src/compliance-profiles/handlers/sub-processors.query.ts +1 -1
  117. package/packages/bundled-features/src/config/changes.json +12 -0
  118. package/packages/bundled-features/src/config/handlers/set.write.ts +7 -0
  119. package/packages/bundled-features/src/config/handlers/values.query.ts +8 -1
  120. package/packages/bundled-features/src/config/index.ts +1 -0
  121. package/packages/bundled-features/src/config/read-redaction.ts +6 -3
  122. package/packages/bundled-features/src/config/table.ts +1 -0
  123. package/packages/bundled-features/src/config/write-helpers.ts +3 -2
  124. package/packages/bundled-features/src/crypto-shredding/changes.json +18 -0
  125. package/packages/bundled-features/src/crypto-shredding/constants.ts +2 -0
  126. package/packages/bundled-features/src/crypto-shredding/handlers/forget-subject.write.ts +38 -18
  127. package/packages/bundled-features/src/crypto-shredding/index.ts +4 -0
  128. package/packages/bundled-features/src/crypto-shredding/subject-forget-after-delete-hook.ts +49 -0
  129. package/packages/bundled-features/src/custom-fields/aggregate-id.ts +0 -1
  130. package/packages/bundled-features/src/custom-fields/entity.ts +1 -0
  131. package/packages/bundled-features/src/custom-fields/wire-for-entity.ts +0 -1
  132. package/packages/bundled-features/src/data-retention/changes.json +12 -0
  133. package/packages/bundled-features/src/data-retention/erase-notes-of-deleted-row.ts +23 -0
  134. package/packages/bundled-features/src/data-retention/feature.ts +2 -5
  135. package/packages/bundled-features/src/data-retention/run-retention-cleanup.ts +38 -18
  136. package/packages/bundled-features/src/data-retention/tenant-destruction-hold.ts +9 -0
  137. package/packages/bundled-features/src/delivery/attempt-log-factory.ts +11 -0
  138. package/packages/bundled-features/src/delivery/attempt-log.ts +3 -3
  139. package/packages/bundled-features/src/delivery/changes.json +12 -0
  140. package/packages/bundled-features/src/delivery/channel-context.ts +6 -3
  141. package/packages/bundled-features/src/delivery/db/queries/preferences.ts +0 -1
  142. package/packages/bundled-features/src/delivery/delivery-service.ts +3 -0
  143. package/packages/bundled-features/src/delivery/feature.ts +4 -13
  144. package/packages/bundled-features/src/delivery/handlers/opted-in-user-ids.query.ts +54 -0
  145. package/packages/bundled-features/src/delivery/handlers/preferences.query.ts +2 -20
  146. package/packages/bundled-features/src/delivery/handlers/resubscribe-user.write.ts +2 -25
  147. package/packages/bundled-features/src/delivery/handlers/unsubscribe-page-chrome.query.ts +2 -0
  148. package/packages/bundled-features/src/delivery/handlers/unsubscribe-user.write.ts +2 -27
  149. package/packages/bundled-features/src/delivery/index.ts +3 -1
  150. package/packages/bundled-features/src/delivery/options.ts +11 -0
  151. package/packages/bundled-features/src/delivery/preference-rows.ts +33 -0
  152. package/packages/bundled-features/src/delivery/set-preference-enabled.ts +40 -0
  153. package/packages/bundled-features/src/delivery/testing.ts +3 -1
  154. package/packages/bundled-features/src/delivery/types.ts +1 -0
  155. package/packages/bundled-features/src/delivery/unsubscribe-page.ts +7 -1
  156. package/packages/bundled-features/src/delivery/upsert-preference.ts +0 -1
  157. package/packages/bundled-features/src/delivery/web/public-names.ts +1 -0
  158. package/packages/bundled-features/src/derivatives-sharp/render.ts +9 -9
  159. package/packages/bundled-features/src/document-ingest-foundation/aggregate-id.ts +0 -1
  160. package/packages/bundled-features/src/document-ingest-foundation/append-missing-extract-event.ts +37 -25
  161. package/packages/bundled-features/src/document-ingest-foundation/changes.json +6 -0
  162. package/packages/bundled-features/src/document-ingest-foundation/feature.ts +1 -0
  163. package/packages/bundled-features/src/document-ingest-foundation/report-ingest-progress.ts +34 -14
  164. package/packages/bundled-features/src/documents/aggregate-id.ts +0 -2
  165. package/packages/bundled-features/src/documents/changes.json +24 -0
  166. package/packages/bundled-features/src/documents/constants.ts +10 -2
  167. package/packages/bundled-features/src/documents/ensure-link.ts +3 -4
  168. package/packages/bundled-features/src/documents/feature.ts +33 -6
  169. package/packages/bundled-features/src/documents/handlers/import.write.ts +2 -2
  170. package/packages/bundled-features/src/documents/queries/expiry-overview.query.ts +2 -1
  171. package/packages/bundled-features/src/documents/queries/for-record.query.ts +3 -4
  172. package/packages/bundled-features/src/documents/queries/list-page.ts +11 -3
  173. package/packages/bundled-features/src/documents/queries/overview.query.ts +2 -2
  174. package/packages/bundled-features/src/documents/screens.ts +8 -3
  175. package/packages/bundled-features/src/documents/tab.ts +1 -1
  176. package/packages/bundled-features/src/feature-toggles/toggle-sync-signal.ts +6 -3
  177. package/packages/bundled-features/src/file-derivatives/handlers/public-variant-by-file-ref.query.ts +1 -1
  178. package/packages/bundled-features/src/file-derivatives/handlers/public-variant.query.ts +1 -1
  179. package/packages/bundled-features/src/file-foundation/probe.ts +9 -3
  180. package/packages/bundled-features/src/file-foundation/read-file-ref-content.ts +24 -11
  181. package/packages/bundled-features/src/file-provider-inmemory/feature.ts +1 -1
  182. package/packages/bundled-features/src/file-provider-s3/changes.json +14 -0
  183. package/packages/bundled-features/src/file-provider-s3/env-feature.ts +1 -1
  184. package/packages/bundled-features/src/file-provider-s3/env-named-feature.ts +1 -1
  185. package/packages/bundled-features/src/file-provider-s3/env-schema.ts +24 -7
  186. package/packages/bundled-features/src/file-provider-s3/feature.ts +1 -1
  187. package/packages/bundled-features/src/file-provider-s3/index.ts +7 -1
  188. package/packages/bundled-features/src/file-provider-s3/lib/env-helper.ts +21 -13
  189. package/packages/bundled-features/src/file-provider-s3/lib/s3-provider.ts +8 -1
  190. package/packages/bundled-features/src/files/changes.json +7 -0
  191. package/packages/bundled-features/src/folders/aggregate-id.ts +0 -1
  192. package/packages/bundled-features/src/folders/web/folder-manager.tsx +6 -6
  193. package/packages/bundled-features/src/folders-user-data/index.ts +12 -14
  194. package/packages/bundled-features/src/form-draft/feature.ts +1 -0
  195. package/packages/bundled-features/src/helpdesk/changes.json +56 -0
  196. package/packages/bundled-features/src/helpdesk/entity.ts +4 -1
  197. package/packages/bundled-features/src/helpdesk/feature.ts +42 -0
  198. package/packages/bundled-features/src/helpdesk/handlers/access.ts +0 -10
  199. package/packages/bundled-features/src/helpdesk/handlers/attempts.ts +7 -14
  200. package/packages/bundled-features/src/helpdesk/handlers/challenge.query.ts +1 -2
  201. package/packages/bundled-features/src/helpdesk/handlers/reply.write.ts +5 -12
  202. package/packages/bundled-features/src/helpdesk/handlers/report.write.ts +4 -10
  203. package/packages/bundled-features/src/helpdesk/handlers/submit.write.ts +5 -12
  204. package/packages/bundled-features/src/helpdesk/index.ts +1 -0
  205. package/packages/bundled-features/src/helpdesk/legacy-contact-config.ts +61 -0
  206. package/packages/bundled-features/src/helpdesk/legacy-contact-erasure.ts +45 -0
  207. package/packages/bundled-features/src/helpdesk/legacy-contact-retention.ts +65 -0
  208. package/packages/bundled-features/src/helpdesk/legacy-contact-streams.ts +187 -0
  209. package/packages/bundled-features/src/helpdesk/legacy-contact-user-data.ts +84 -0
  210. package/packages/bundled-features/src/helpdesk/lib.ts +55 -37
  211. package/packages/bundled-features/src/helpdesk/user-data-hooks.ts +89 -48
  212. package/packages/bundled-features/src/helpdesk/web/constants.ts +0 -1
  213. package/packages/bundled-features/src/inbound-mail-foundation/account-health.ts +1 -1
  214. package/packages/bundled-features/src/inbound-mail-foundation/account-poll.ts +9 -2
  215. package/packages/bundled-features/src/inbound-mail-foundation/aggregate-id.ts +0 -2
  216. package/packages/bundled-features/src/inbound-mail-foundation/changes.json +54 -0
  217. package/packages/bundled-features/src/inbound-mail-foundation/constants.ts +6 -0
  218. package/packages/bundled-features/src/inbound-mail-foundation/content-refetch.ts +23 -2
  219. package/packages/bundled-features/src/inbound-mail-foundation/entities.ts +73 -15
  220. package/packages/bundled-features/src/inbound-mail-foundation/events.ts +24 -16
  221. package/packages/bundled-features/src/inbound-mail-foundation/feature.ts +3 -1
  222. package/packages/bundled-features/src/inbound-mail-foundation/handlers/account-address.ts +16 -2
  223. package/packages/bundled-features/src/inbound-mail-foundation/handlers/attach-message-content.write.ts +10 -3
  224. package/packages/bundled-features/src/inbound-mail-foundation/handlers/connect-account.write.ts +23 -9
  225. package/packages/bundled-features/src/inbound-mail-foundation/handlers/forget-message.write.ts +79 -0
  226. package/packages/bundled-features/src/inbound-mail-foundation/handlers/ingest-message-schema.ts +18 -5
  227. package/packages/bundled-features/src/inbound-mail-foundation/i18n.ts +3 -0
  228. package/packages/bundled-features/src/inbound-mail-foundation/index.ts +1 -0
  229. package/packages/bundled-features/src/inbound-mail-foundation/normalize-inbound-message.ts +22 -8
  230. package/packages/bundled-features/src/inbound-mail-foundation/oauth-access-token.ts +1 -1
  231. package/packages/bundled-features/src/inbound-mail-foundation/outbound-mail.ts +2 -0
  232. package/packages/bundled-features/src/inbound-mail-foundation/personal-address.ts +20 -0
  233. package/packages/bundled-features/src/inbound-mail-foundation/purge-messages.ts +54 -0
  234. package/packages/bundled-features/src/inbound-mail-foundation/quarantine.ts +15 -5
  235. package/packages/bundled-features/src/inbound-mail-foundation/retention-job.ts +1 -5
  236. package/packages/bundled-features/src/inbound-mail-foundation/retention-sweep.ts +21 -34
  237. package/packages/bundled-features/src/inbound-mail-foundation/sanitize-inbound-html.ts +2 -5
  238. package/packages/bundled-features/src/inbound-mail-foundation/send-from-account.ts +9 -1
  239. package/packages/bundled-features/src/inbound-mail-foundation/supervisor-ingest.ts +7 -1
  240. package/packages/bundled-features/src/inbound-mail-foundation/sync-account-now.ts +1 -1
  241. package/packages/bundled-features/src/inbound-mail-foundation/tenant-destroy-hook.ts +14 -17
  242. package/packages/bundled-features/src/inbound-mail-foundation/watch-supervisor.ts +1 -1
  243. package/packages/bundled-features/src/inbound-provider-imap/byte-budget.ts +80 -0
  244. package/packages/bundled-features/src/inbound-provider-imap/changes.json +13 -0
  245. package/packages/bundled-features/src/inbound-provider-imap/connect-mailbox.ts +8 -4
  246. package/packages/bundled-features/src/inbound-provider-imap/connect-my-mailbox.ts +23 -6
  247. package/packages/bundled-features/src/inbound-provider-imap/connect-target-rate-limit.ts +46 -0
  248. package/packages/bundled-features/src/inbound-provider-imap/download-batch.ts +47 -10
  249. package/packages/bundled-features/src/inbound-provider-imap/feature.ts +7 -4
  250. package/packages/bundled-features/src/inbound-provider-imap/fetch-content.ts +43 -29
  251. package/packages/bundled-features/src/inbound-provider-imap/i18n.ts +2 -2
  252. package/packages/bundled-features/src/inbound-provider-imap/parse-message.ts +14 -0
  253. package/packages/bundled-features/src/inbound-provider-imap/reconnect-mailbox.ts +5 -4
  254. package/packages/bundled-features/src/inbound-provider-imap/send-mail.ts +39 -7
  255. package/packages/bundled-features/src/inbound-provider-imap/smtp-client.ts +19 -4
  256. package/packages/bundled-features/src/inbound-provider-imap/watch-mailbox.ts +8 -23
  257. package/packages/bundled-features/src/inbound-provider-inmemory/feature.ts +1 -1
  258. package/packages/bundled-features/src/jobs/events.ts +10 -0
  259. package/packages/bundled-features/src/jobs/feature.ts +2 -0
  260. package/packages/bundled-features/src/jobs/handlers/consumer.write.ts +41 -16
  261. package/packages/bundled-features/src/jobs/web/constants.ts +4 -0
  262. package/packages/bundled-features/src/mail-foundation/changes.json +6 -0
  263. package/packages/bundled-features/src/mail-transport-inmemory/feature.ts +1 -1
  264. package/packages/bundled-features/src/mail-transport-smtp/feature.ts +3 -2
  265. package/packages/bundled-features/src/managed-pages/changes.json +12 -0
  266. package/packages/bundled-features/src/managed-pages/handlers/branding.query.ts +1 -1
  267. package/packages/bundled-features/src/managed-pages/handlers/by-slug.query.ts +1 -1
  268. package/packages/bundled-features/src/managed-pages/handlers/by-tenant-published.query.ts +1 -1
  269. package/packages/bundled-features/src/managed-pages/render-page-body.ts +18 -10
  270. package/packages/bundled-features/src/managed-pages/screens/page-screens.ts +18 -38
  271. package/packages/bundled-features/src/managed-pages/table.ts +1 -0
  272. package/packages/bundled-features/src/managed-pages/web/client-plugin.tsx +8 -6
  273. package/packages/bundled-features/src/managed-pages/web/constants.ts +8 -1
  274. package/packages/bundled-features/src/managed-pages/web/i18n.ts +11 -3
  275. package/packages/bundled-features/src/managed-pages/web/markdown-to-document.ts +1 -1
  276. package/packages/bundled-features/src/managed-pages/web/page-edit-draft.ts +108 -0
  277. package/packages/bundled-features/src/managed-pages/web/page-edit-screen.tsx +204 -0
  278. package/packages/bundled-features/src/managed-pages/web/page-settings-rail.tsx +117 -0
  279. package/packages/bundled-features/src/notes-history-user-data/index.ts +8 -14
  280. package/packages/bundled-features/src/personal-access-tokens/boot-rules.ts +5 -0
  281. package/packages/bundled-features/src/personal-access-tokens/handlers/create.write.ts +0 -1
  282. package/packages/bundled-features/src/personal-access-tokens/scope-events-check.ts +31 -5
  283. package/packages/bundled-features/src/presence/changes.json +6 -0
  284. package/packages/bundled-features/src/presence/handlers/list.query.ts +28 -11
  285. package/packages/bundled-features/src/presence/room.ts +21 -7
  286. package/packages/bundled-features/src/presence/store.ts +79 -21
  287. package/packages/bundled-features/src/readiness/changes.json +25 -0
  288. package/packages/bundled-features/src/readiness/handlers/latest-summary.query.ts +11 -6
  289. package/packages/bundled-features/src/readiness/handlers/run-probes.write.ts +35 -5
  290. package/packages/bundled-features/src/readiness/handlers/run-tone.ts +3 -2
  291. package/packages/bundled-features/src/readiness/handlers/status.query.ts +15 -1
  292. package/packages/bundled-features/src/readiness/probe-context.ts +11 -10
  293. package/packages/bundled-features/src/readiness/screens.ts +4 -4
  294. package/packages/bundled-features/src/readiness/visible-results.ts +5 -3
  295. package/packages/bundled-features/src/renderer-foundation/api.ts +6 -13
  296. package/packages/bundled-features/src/renderer-foundation/types.ts +2 -2
  297. package/packages/bundled-features/src/secrets/changes.json +7 -0
  298. package/packages/bundled-features/src/secrets/db/queries/read.ts +18 -4
  299. package/packages/bundled-features/src/secrets/handlers/list.query.ts +8 -2
  300. package/packages/bundled-features/src/secrets/secret-scope.ts +2 -3
  301. package/packages/bundled-features/src/secrets/secrets-context.ts +6 -4
  302. package/packages/bundled-features/src/secrets/write-gate.ts +4 -2
  303. package/packages/bundled-features/src/seo/handlers/seo-config.query.ts +1 -1
  304. package/packages/bundled-features/src/shared/acknowledged-system-db.ts +20 -0
  305. package/packages/bundled-features/src/shared/assert-billing-live.ts +9 -2
  306. package/packages/bundled-features/src/shared/changes.json +12 -0
  307. package/packages/bundled-features/src/shared/hmac-signature.ts +4 -2
  308. package/packages/bundled-features/src/shared/index.ts +7 -1
  309. package/packages/bundled-features/src/shared/normalize-email.ts +3 -0
  310. package/packages/bundled-features/src/shared/parent-visibility.ts +25 -1
  311. package/packages/bundled-features/src/shared/password-hashing.ts +0 -1
  312. package/packages/bundled-features/src/shared/price-env-shape.ts +1 -4
  313. package/packages/bundled-features/src/shared/register-user-data-hooks.ts +29 -0
  314. package/packages/bundled-features/src/shared/require-bootstrap-extension.ts +26 -0
  315. package/packages/bundled-features/src/shared/send-best-effort.ts +29 -0
  316. package/packages/bundled-features/src/shared/stream-tenant-backfill.ts +22 -1
  317. package/packages/bundled-features/src/shared/stream-tenant-derived-state.ts +31 -1
  318. package/packages/bundled-features/src/step-dispatcher/changes.json +18 -0
  319. package/packages/bundled-features/src/step-dispatcher/constants.ts +13 -0
  320. package/packages/bundled-features/src/step-dispatcher/deliver-dispatch-request.ts +50 -2
  321. package/packages/bundled-features/src/step-dispatcher/feature.ts +42 -1
  322. package/packages/bundled-features/src/step-dispatcher/mail-runner.ts +0 -1
  323. package/packages/bundled-features/src/step-dispatcher/sweep-abandoned.ts +61 -0
  324. package/packages/bundled-features/src/subscription-mollie/changes.json +7 -0
  325. package/packages/bundled-features/src/subscription-mollie/plugin-methods.ts +5 -3
  326. package/packages/bundled-features/src/subscription-mollie/verify-webhook.ts +5 -5
  327. package/packages/bundled-features/src/subscription-paddle/backfill-checkout-ledger.ts +161 -0
  328. package/packages/bundled-features/src/subscription-paddle/changes.json +19 -0
  329. package/packages/bundled-features/src/subscription-paddle/checkout-config.query.ts +1 -1
  330. package/packages/bundled-features/src/subscription-paddle/checkout-methods.ts +2 -8
  331. package/packages/bundled-features/src/subscription-paddle/constants.ts +1 -2
  332. package/packages/bundled-features/src/subscription-paddle/feature.ts +26 -24
  333. package/packages/bundled-features/src/subscription-paddle/ledger-backfill-marker.ts +70 -0
  334. package/packages/bundled-features/src/subscription-paddle/plan-switch-methods.ts +2 -8
  335. package/packages/bundled-features/src/subscription-paddle/redeliver-legacy-checkout.ts +57 -0
  336. package/packages/bundled-features/src/subscription-paddle/runtime.ts +13 -24
  337. package/packages/bundled-features/src/subscription-paddle/subscription-state.ts +1 -0
  338. package/packages/bundled-features/src/subscription-paddle/webhook-events.ts +68 -21
  339. package/packages/bundled-features/src/subscription-stripe/changes.json +13 -0
  340. package/packages/bundled-features/src/subscription-stripe/feature.ts +5 -0
  341. package/packages/bundled-features/src/subscription-stripe/plugin-methods.ts +6 -6
  342. package/packages/bundled-features/src/subscription-stripe/runtime.ts +8 -7
  343. package/packages/bundled-features/src/subscription-stripe/verify-webhook.ts +38 -6
  344. package/packages/bundled-features/src/tags/aggregate-id.ts +0 -1
  345. package/packages/bundled-features/src/tags/web/tag-chip.tsx +4 -5
  346. package/packages/bundled-features/src/tags/web/tag-manager.tsx +2 -1
  347. package/packages/bundled-features/src/template-resolver/api.ts +6 -13
  348. package/packages/bundled-features/src/template-resolver/changes.json +48 -0
  349. package/packages/bundled-features/src/template-resolver/document-sanitizer.ts +25 -0
  350. package/packages/bundled-features/src/template-resolver/feature.ts +2 -0
  351. package/packages/bundled-features/src/template-resolver/handlers/body-preview.query.ts +41 -0
  352. package/packages/bundled-features/src/template-resolver/handlers/by-slug.query.ts +1 -1
  353. package/packages/bundled-features/src/template-resolver/handlers/by-tenant.query.ts +1 -1
  354. package/packages/bundled-features/src/template-resolver/handlers/collection-shared.ts +5 -11
  355. package/packages/bundled-features/src/template-resolver/handlers/overview.query.ts +3 -2
  356. package/packages/bundled-features/src/template-resolver/handlers/send-test.write.ts +37 -8
  357. package/packages/bundled-features/src/template-resolver/linked-resources.ts +2 -5
  358. package/packages/bundled-features/src/template-resolver/seeding.ts +107 -0
  359. package/packages/bundled-features/src/template-resolver/table.ts +1 -0
  360. package/packages/bundled-features/src/template-resolver/template-draft.ts +2 -1
  361. package/packages/bundled-features/src/template-resolver/template-preview.ts +14 -3
  362. package/packages/bundled-features/src/template-resolver/testing.ts +0 -2
  363. package/packages/bundled-features/src/template-resolver/web/client-plugin.tsx +3 -0
  364. package/packages/bundled-features/src/template-resolver/web/collection-entry-create-form.tsx +33 -33
  365. package/packages/bundled-features/src/template-resolver/web/constants.ts +7 -0
  366. package/packages/bundled-features/src/template-resolver/web/content-tree-provider.ts +0 -1
  367. package/packages/bundled-features/src/template-resolver/web/content-workbench.tsx +142 -0
  368. package/packages/bundled-features/src/template-resolver/web/document-insert-model.ts +3 -8
  369. package/packages/bundled-features/src/template-resolver/web/document-link-policy.ts +58 -0
  370. package/packages/bundled-features/src/template-resolver/web/document-schema.ts +11 -57
  371. package/packages/bundled-features/src/template-resolver/web/document-tiptap-bubble.tsx +2 -4
  372. package/packages/bundled-features/src/template-resolver/web/document-tiptap-context.ts +4 -5
  373. package/packages/bundled-features/src/template-resolver/web/document-tiptap-editor.tsx +2 -2
  374. package/packages/bundled-features/src/template-resolver/web/document-tiptap-helpers.ts +6 -3
  375. package/packages/bundled-features/src/template-resolver/web/document-tiptap-toolbar-groups.tsx +2 -3
  376. package/packages/bundled-features/src/template-resolver/web/editor-handle.ts +1 -0
  377. package/packages/bundled-features/src/template-resolver/web/fill-document-variables.ts +24 -0
  378. package/packages/bundled-features/src/template-resolver/web/i18n.ts +14 -0
  379. package/packages/bundled-features/src/template-resolver/web/index.ts +3 -0
  380. package/packages/bundled-features/src/template-resolver/web/preview-targets.ts +25 -0
  381. package/packages/bundled-features/src/template-resolver/web/qualified-names.ts +1 -0
  382. package/packages/bundled-features/src/template-resolver/web/snippet-preview-renderer.tsx +24 -0
  383. package/packages/bundled-features/src/template-resolver/web/string-values.ts +7 -0
  384. package/packages/bundled-features/src/template-resolver/web/text-block-editor.tsx +38 -50
  385. package/packages/bundled-features/src/template-resolver/web/use-collection-entry-create.ts +7 -0
  386. package/packages/bundled-features/src/template-resolver/web/use-content-write.ts +1 -3
  387. package/packages/bundled-features/src/template-resolver/web/use-document-tiptap-model.ts +1 -2
  388. package/packages/bundled-features/src/template-resolver/web/use-text-block-editor.ts +28 -7
  389. package/packages/bundled-features/src/template-resolver/web/web-preview-renderer.tsx +132 -0
  390. package/packages/bundled-features/src/template-resolver-user-data/index.ts +11 -10
  391. package/packages/bundled-features/src/tenant/changes.json +6 -0
  392. package/packages/bundled-features/src/tenant/handlers/create.write.ts +7 -8
  393. package/packages/bundled-features/src/tenant/handlers/list.query.ts +7 -9
  394. package/packages/bundled-features/src/tenant/handlers/member-directory.query.ts +10 -4
  395. package/packages/bundled-features/src/tenant/handlers/toggle-enabled.write.ts +1 -1
  396. package/packages/bundled-features/src/tenant/invited-membership.ts +10 -1
  397. package/packages/bundled-features/src/tenant/seeding.ts +4 -2
  398. package/packages/bundled-features/src/tenant/stream-tenant-backfill.ts +5 -1
  399. package/packages/bundled-features/src/tenant/testing.ts +1 -1
  400. package/packages/bundled-features/src/tenant-inactivity/changes.json +6 -0
  401. package/packages/bundled-features/src/tenant-inactivity/check-inactive-tenants.ts +36 -17
  402. package/packages/bundled-features/src/tenant-inactivity/constants.ts +1 -2
  403. package/packages/bundled-features/src/tenant-inactivity/handlers/keep-account.write.ts +7 -2
  404. package/packages/bundled-features/src/tenant-inactivity/state-store.ts +22 -2
  405. package/packages/bundled-features/src/tenant-lifecycle/changes.json +24 -0
  406. package/packages/bundled-features/src/tenant-lifecycle/constants.ts +4 -0
  407. package/packages/bundled-features/src/tenant-lifecycle/feature.ts +1 -0
  408. package/packages/bundled-features/src/tenant-lifecycle/run-tenant-destroy.ts +43 -6
  409. package/packages/bundled-features/src/tenant-lifecycle/stages.ts +15 -2
  410. package/packages/bundled-features/src/tier-engine/aggregate-id.ts +0 -1
  411. package/packages/bundled-features/src/tier-engine/changes.json +6 -0
  412. package/packages/bundled-features/src/tier-engine/feature.ts +8 -2
  413. package/packages/bundled-features/src/user/changes.json +6 -0
  414. package/packages/bundled-features/src/user/db/queries/stream-tenant-backfill.ts +2 -1
  415. package/packages/bundled-features/src/user/handlers/me.query.ts +3 -1
  416. package/packages/bundled-features/src/user/index.ts +1 -0
  417. package/packages/bundled-features/src/user/resolve-verified-user-email.ts +17 -0
  418. package/packages/bundled-features/src/user-data-rights/db/queries/export-jobs.ts +0 -1
  419. package/packages/bundled-features/src/user-data-rights/feature.ts +1 -0
  420. package/packages/bundled-features/src/user-data-rights/handlers/confirm-deletion-by-token.write.ts +1 -1
  421. package/packages/bundled-features/src/user-data-rights/handlers/download-by-token.query.ts +1 -1
  422. package/packages/bundled-features/src/user-data-rights/handlers/request-deletion-by-email.write.ts +1 -1
  423. package/packages/bundled-features/src/user-data-rights/run-export-jobs.ts +0 -2
  424. package/packages/bundled-features/src/user-data-rights/run-forget-cleanup.ts +3 -3
  425. package/packages/bundled-features/src/user-data-rights/schema/download-attempt.ts +3 -2
  426. package/packages/bundled-features/src/user-data-rights/web/confirm-deletion-screen.tsx +1 -1
  427. package/packages/bundled-features/src/user-data-rights/web/privacy-center-screen.tsx +1 -1
  428. package/packages/bundled-features/src/user-data-rights/web/request-deletion-screen.tsx +1 -1
  429. package/packages/bundled-features/src/user-data-rights-defaults/hooks/api-token.userdata-hook.ts +5 -5
  430. package/packages/bundled-features/src/user-data-rights-defaults/hooks/hard-delete-own-rows-hook.ts +17 -0
  431. package/packages/bundled-features/src/user-data-rights-defaults/hooks/in-app-message.userdata-hook.ts +5 -5
  432. package/packages/bundled-features/src/user-data-rights-defaults/hooks/job-run.userdata-hook.ts +2 -1
  433. package/packages/bundled-features/src/user-data-rights-defaults/hooks/user-session.userdata-hook.ts +5 -5
  434. package/packages/bundled-features/src/user-profile/handlers/change-email.write.ts +0 -1
  435. package/packages/bundled-features/src/waitlist/changes.json +6 -0
  436. package/packages/bundled-features/src/waitlist/handlers/reject.write.ts +1 -1
  437. package/packages/bundled-features/src/waitlist/handlers/submit.write.ts +5 -29
  438. package/packages/bundled-features/src/waitlist/import.ts +2 -1
  439. package/packages/bundled-features/src/waitlist/lib.ts +2 -11
  440. package/packages/bundled-features/src/waitlist/link-on-signup.ts +2 -2
  441. package/packages/bundled-features/src/waitlist/user-data-hooks.ts +6 -19
  442. package/packages/bundled-features/src/workflow-runner/aggregate-id.ts +0 -1
  443. package/packages/bundled-features/src/workflow-runner/changes.json +6 -0
  444. package/packages/bundled-features/src/workflow-runner/event-trigger.ts +6 -2
  445. package/packages/bundled-features/src/workflow-runner/feature.ts +1 -5
  446. package/packages/bundled-features/src/workflow-runner/handlers/resume-run.write.ts +7 -4
  447. package/packages/bundled-features/src/workflow-runner/runner.ts +2 -0
  448. package/samples/apps/admin-console/src/app/shell.tsx +1 -0
  449. package/samples/apps/showcase/src/features/demos/web/pages/dialog.tsx +0 -1
  450. package/samples/apps/showcase/src/features/demos/web/pages/layout.tsx +1 -1
  451. package/samples/apps/showcase/src/features/demos/web/pages/sidebar-panel.tsx +0 -1
  452. package/samples/apps/styleguide/src/features/gallery/web/Gallery.tsx +1 -4
  453. package/samples/apps/ui-walkthrough/src/features/subscription-plans/feature.ts +6 -2
  454. package/samples/apps/use-all-bundled/e2e-billing-gallery/gallery-features.ts +12 -14
  455. package/samples/apps/use-all-bundled/feature-manifest.json +60 -29
  456. package/samples/apps/use-all-bundled/playwright.billing-docs.config.ts +1 -1
  457. package/samples/apps/use-all-bundled/playwright.config.ts +1 -0
  458. package/samples/apps/use-all-bundled/src/app/seed.ts +1 -1
  459. package/samples/apps/use-all-bundled/src/run-config.ts +2 -1
  460. package/samples/recipes/auth-mfa/src/web/confirmation-code-step.tsx +32 -10
  461. package/samples/recipes/chat-channels/README.md +2 -0
  462. package/samples/recipes/crypto-shredding-hr/README.md +11 -0
  463. package/samples/recipes/crypto-shredding-hr/src/feature.ts +27 -0
  464. package/samples/recipes/currencies-global/src/entities/currency.ts +1 -0
  465. package/samples/recipes/managed-pages/README.md +5 -1
  466. package/samples/recipes/managed-pages/package.json +3 -2
  467. package/samples/recipes/managed-pages/src/web/branded-preview.tsx +21 -0
  468. package/samples/recipes/managed-pages/tsconfig.json +8 -0
  469. package/samples/recipes/pwa-shell/README.md +52 -0
  470. package/samples/recipes/pwa-shell/bin/server.ts +12 -0
  471. package/samples/recipes/pwa-shell/package.json +13 -0
  472. package/samples/recipes/pwa-shell/src/app.ts +34 -0
  473. package/samples/recipes/rate-limiting/README.md +3 -3
  474. package/samples/recipes/record-detail-layout/README.md +33 -0
  475. package/samples/recipes/record-detail-layout/src/feature.ts +556 -44
  476. package/samples/recipes/record-detail-layout/src/order-board.ts +529 -0
  477. package/packages/bundled-features/src/managed-pages/web/page-body-section.tsx +0 -72
  478. package/packages/bundled-features/src/subscription-paddle/tenant-binding.ts +0 -34
  479. package/packages/bundled-features/src/template-resolver/web/content-field.tsx +0 -61
@@ -7,9 +7,12 @@
7
7
  // already-seen `metadata.providerEventId`. A provider replay
8
8
  // (Stripe retry storm) has the same event ID → duplicate=true,
9
9
  // with no second append.
10
- // 2. Type mapping: SubscriptionEvent.type (= normalized by the plugin)
10
+ // 2. Admission (handler only, not the shared append): `created` needs a
11
+ // checkout from the server's ledger; every other type needs the tenant's
12
+ // current subscription or a ledgered checkout. Else the event is ignored.
13
+ // 3. Type mapping: SubscriptionEvent.type (= normalized by the plugin)
11
14
  // → one of the 5 ES event types.
12
- // 3. ctx.events.unsafeAppend — the inline projection materializes the
15
+ // 4. ctx.events.unsafeAppend — the inline projection materializes the
13
16
  // `read_subscriptions` row in the same TX.
14
17
 
15
18
  import {
@@ -21,10 +24,20 @@ import { Temporal } from "@cosmicdrift/kumiko-types/temporal";
21
24
  import { propertyOf } from "@cosmicdrift/kumiko-types/type-guards";
22
25
  import * as z from "zod";
23
26
  import { subscriptionAggregateId } from "../aggregate-id.ts";
27
+ import { findProviderPlugin } from "../checkout-core.ts";
28
+ import {
29
+ findCheckoutOpened,
30
+ type IgnoredEventReason,
31
+ IgnoredEventReasons,
32
+ } from "../checkout-ledger.ts";
24
33
  import { SUBSCRIPTION_PII_FIELDS, subscriptionEntity } from "../entities.ts";
25
34
  import {
35
+ CHECKOUT_CONSENT_RECORDED_EVENT_QN,
36
+ type CheckoutOpenedPayload,
37
+ checkoutConsentRecordedPayloadSchema,
26
38
  INVOICE_PAID_EVENT_QN,
27
39
  INVOICE_PAYMENT_FAILED_EVENT_QN,
40
+ PROVIDER_ID_MAX_CHARS,
28
41
  SUBSCRIPTION_AGGREGATE_TYPE,
29
42
  SUBSCRIPTION_CANCELED_EVENT_QN,
30
43
  SUBSCRIPTION_CREATED_EVENT_QN,
@@ -68,14 +81,14 @@ export const processEventSchema = z.object({
68
81
  providerEventId: z.string().min(1).max(200),
69
82
  providerName: z.string().min(1).max(50),
70
83
  type: eventTypeSchema,
71
- providerCustomerId: z.string().min(1).max(200),
72
- providerSubscriptionId: z.string().min(1).max(200),
84
+ providerCustomerId: z.string().min(1).max(PROVIDER_ID_MAX_CHARS),
85
+ providerSubscriptionId: z.string().min(1).max(PROVIDER_ID_MAX_CHARS),
73
86
  status: statusSchema,
74
87
  tier: z.string().min(1).max(50),
75
88
  currentPeriodEndIso: z.string().min(1),
76
89
  cancelAtIso: z.string().min(1).nullable().optional(),
77
90
  providerEventAtIso: z.iso.datetime().optional(),
78
- consentId: z.string().min(1).max(100).optional(),
91
+ providerCheckoutId: z.string().min(1).max(200).optional(),
79
92
  });
80
93
  export type ProcessEventPayload = z.infer<typeof processEventSchema>;
81
94
 
@@ -88,6 +101,12 @@ const NORMALIZED_TO_ES_EVENT: Readonly<Record<string, string>> = {
88
101
  [SubscriptionEventTypes.invoicePaymentFailed]: INVOICE_PAYMENT_FAILED_EVENT_QN,
89
102
  } satisfies Readonly<Record<string, string>>;
90
103
 
104
+ const STATE_EVENT_QNS: ReadonlySet<string> = new Set([
105
+ SUBSCRIPTION_CREATED_EVENT_QN,
106
+ SUBSCRIPTION_UPDATED_EVENT_QN,
107
+ SUBSCRIPTION_CANCELED_EVENT_QN,
108
+ ]);
109
+
91
110
  const STATE_EVENT_TYPES: ReadonlySet<string> = new Set([
92
111
  SubscriptionEventTypes.created,
93
112
  SubscriptionEventTypes.updated,
@@ -133,6 +152,16 @@ export function isLateStateEvent(
133
152
  // who constructs `payload` and what `providerEventId` they use.
134
153
  // =============================================================================
135
154
 
155
+ type SubscriptionStreamEvent = Awaited<ReturnType<HandlerContext["events"]["load"]>>[number];
156
+
157
+ async function lockAndLoadSubscriptionStream(
158
+ ctx: HandlerContext,
159
+ aggId: string,
160
+ ): Promise<readonly SubscriptionStreamEvent[]> {
161
+ await ctx.db.advisoryXactLock(BILLING_SUBSCRIPTION_LOCK_NAMESPACE, aggId);
162
+ return ctx.events.load(aggId);
163
+ }
164
+
136
165
  // A provider timestamp far in the future would make every later, genuine event look late.
137
166
  const PROVIDER_EVENT_CLOCK_SKEW_SECONDS = 300;
138
167
 
@@ -152,6 +181,8 @@ export async function appendSubscriptionEvent(
152
181
  tenantId: string,
153
182
  rawPayload: ProcessEventPayload,
154
183
  now: Temporal.Instant = Temporal.Now.instant(),
184
+ consentId?: string,
185
+ lockedStream?: readonly SubscriptionStreamEvent[],
155
186
  ): Promise<{
156
187
  readonly duplicate: boolean;
157
188
  readonly stale?: true;
@@ -160,10 +191,9 @@ export async function appendSubscriptionEvent(
160
191
  const aggId = subscriptionAggregateId(tenantId);
161
192
  const payload = clampProviderEventAt(rawPayload, now);
162
193
 
163
- // Serialises the read (idempotency + late check) with the append: the append re-reads the
164
- // stream version itself, so without the lock a concurrent delivery could slip in between and
165
- // the late check would have judged an outdated stream.
166
- await ctx.db.advisoryXactLock(BILLING_SUBSCRIPTION_LOCK_NAMESPACE, aggId);
194
+ // The lock serialises the read (idempotency + late check) with the append: the append re-reads the
195
+ // stream version itself, so without it a concurrent delivery could slip in between and the late
196
+ // check would have judged an outdated stream. A caller that already holds it passes its stream.
167
197
 
168
198
  // ---------------------------------------------------------------
169
199
  // 1. Idempotency: load the subscription stream and check whether this
@@ -176,7 +206,7 @@ export async function appendSubscriptionEvent(
176
206
  // streams, optimize via snapshot or a per-tenant dedup table as the
177
207
  // idempotency anchor (like cap-counter).
178
208
  // ---------------------------------------------------------------
179
- const existingEvents = await ctx.events.load(aggId);
209
+ const existingEvents = lockedStream ?? (await lockAndLoadSubscriptionStream(ctx, aggId));
180
210
  if (hasSeenProviderEvent(existingEvents, payload)) {
181
211
  return { duplicate: true, subscriptionAggregateId: aggId };
182
212
  }
@@ -245,7 +275,7 @@ export async function appendSubscriptionEvent(
245
275
  tier: payload.tier,
246
276
  currentPeriodEndIso: payload.currentPeriodEndIso,
247
277
  ...(payload.cancelAtIso !== undefined && { cancelAtIso: payload.cancelAtIso }),
248
- ...(payload.consentId !== undefined && { consentId: payload.consentId }),
278
+ ...(consentId !== undefined && { consentId }),
249
279
  ...(payload.providerEventAtIso !== undefined && {
250
280
  providerEventAtIso: payload.providerEventAtIso,
251
281
  }),
@@ -294,6 +324,120 @@ function isStaleSubscriptionEvent(
294
324
  return !supersedesCurrent;
295
325
  }
296
326
 
327
+ type Admission =
328
+ | { readonly admitted: true; readonly consentId?: string }
329
+ | { readonly admitted: false; readonly reason: IgnoredEventReason; readonly retry?: true };
330
+
331
+ function isBoundToLedgerEntry(
332
+ ctx: HandlerContext,
333
+ entry: CheckoutOpenedPayload,
334
+ payload: ProcessEventPayload,
335
+ ): boolean {
336
+ const plugin = findProviderPlugin(ctx, payload.providerName)?.plugin;
337
+ return plugin?.priceToTier?.[entry.priceId] === payload.tier;
338
+ }
339
+
340
+ // A plan switch has no checkout of its own: its consent is the newest one recorded for the target
341
+ // tier, as long as no stored subscription event carries it yet. No window by state events: another
342
+ // state event (renewal, status change) may arrive between the consent and the tier change. The age
343
+ // limit keeps an abandoned consent from being attached to a portal switch months later.
344
+ const SWITCH_CONSENT_MAX_AGE_HOURS = 24;
345
+
346
+ function providerEventInstant(payload: ProcessEventPayload, now: Temporal.Instant) {
347
+ const iso = clampProviderEventAt(payload, now).providerEventAtIso;
348
+ return iso === undefined ? now : Temporal.Instant.from(iso);
349
+ }
350
+
351
+ function pendingSwitchConsentId(
352
+ storedEvents: readonly SubscriptionStreamEvent[],
353
+ payload: ProcessEventPayload,
354
+ now: Temporal.Instant,
355
+ ): string | undefined {
356
+ const referenceAt = providerEventInstant(payload, now);
357
+ const oldestAcceptedAt = referenceAt.subtract({ hours: SWITCH_CONSENT_MAX_AGE_HOURS });
358
+ const carried = new Set<string>();
359
+ for (const stored of storedEvents) {
360
+ // skip: only subscription state events can carry a consent
361
+ if (!STATE_EVENT_QNS.has(stored.type)) continue;
362
+ const consentId = propertyOf(stored.payload, "consentId");
363
+ if (typeof consentId === "string") carried.add(consentId);
364
+ }
365
+ for (let index = storedEvents.length - 1; index >= 0; index--) {
366
+ const stored = storedEvents[index];
367
+ if (stored?.type !== CHECKOUT_CONSENT_RECORDED_EVENT_QN) continue;
368
+ if (Temporal.Instant.compare(stored.createdAt, oldestAcceptedAt) < 0) continue;
369
+ const parsed = checkoutConsentRecordedPayloadSchema.safeParse(stored.payload);
370
+ if (!parsed.success) continue;
371
+ const consent = parsed.data;
372
+ if (
373
+ consent.mode === "subscription" &&
374
+ consent.tier === payload.tier &&
375
+ (consent.providerName === undefined || consent.providerName === payload.providerName) &&
376
+ !carried.has(consent.consentId)
377
+ ) {
378
+ return consent.consentId;
379
+ }
380
+ }
381
+ return undefined;
382
+ }
383
+
384
+ // A `created` that never comes (subscription from before the ledger, foreign custom_data, deleted
385
+ // subscription) would otherwise answer 503 until the provider gives up, and Stripe disables an
386
+ // endpoint that keeps failing. Only a young event may still be overtaken by its `created`.
387
+ // A provider that sends no event time (mollie) cannot be aged and keeps retrying.
388
+ const MISSING_SUBSCRIPTION_RETRY_WINDOW_MINUTES = 60;
389
+
390
+ function isWithinMissingSubscriptionRetryWindow(
391
+ payload: ProcessEventPayload,
392
+ now: Temporal.Instant,
393
+ ): boolean {
394
+ if (payload.providerEventAtIso === undefined) return true;
395
+ const oldestRetriedAt = now.subtract({ minutes: MISSING_SUBSCRIPTION_RETRY_WINDOW_MINUTES });
396
+ return Temporal.Instant.compare(providerEventInstant(payload, now), oldestRetriedAt) >= 0;
397
+ }
398
+
399
+ function admitProviderEvent(
400
+ ctx: HandlerContext,
401
+ storedEvents: readonly SubscriptionStreamEvent[],
402
+ current: SubscriptionView | null,
403
+ payload: ProcessEventPayload,
404
+ now: Temporal.Instant,
405
+ ): Admission {
406
+ const entry =
407
+ payload.providerCheckoutId === undefined
408
+ ? undefined
409
+ : findCheckoutOpened(storedEvents, {
410
+ providerName: payload.providerName,
411
+ providerCheckoutId: payload.providerCheckoutId,
412
+ mode: "subscription",
413
+ });
414
+ if (entry !== undefined && isBoundToLedgerEntry(ctx, entry, payload)) {
415
+ return { admitted: true, ...(entry.consentId !== undefined && { consentId: entry.consentId }) };
416
+ }
417
+ if (payload.type === SubscriptionEventTypes.created) {
418
+ return { admitted: false, reason: IgnoredEventReasons.checkoutNotInLedger };
419
+ }
420
+ // The provider does not guarantee order: an update that beats the `created` of its
421
+ // subscription must be redelivered, not dropped.
422
+ if (current === null) {
423
+ return {
424
+ admitted: false,
425
+ reason: IgnoredEventReasons.subscriptionNotYetCreated,
426
+ ...(isWithinMissingSubscriptionRetryWindow(payload, now) && { retry: true }),
427
+ };
428
+ }
429
+ const isCurrentSubscription =
430
+ current.providerName === payload.providerName &&
431
+ current.providerSubscriptionId === payload.providerSubscriptionId;
432
+ if (!isCurrentSubscription)
433
+ return { admitted: false, reason: IgnoredEventReasons.foreignSubscription };
434
+ const switchConsentId =
435
+ payload.type === SubscriptionEventTypes.updated && current.tier !== payload.tier
436
+ ? pendingSwitchConsentId(storedEvents, payload, now)
437
+ : undefined;
438
+ return { admitted: true, ...(switchConsentId !== undefined && { consentId: switchConsentId }) };
439
+ }
440
+
297
441
  export function createProcessEventHandler(now: () => Temporal.Instant): WriteHandlerDef {
298
442
  return {
299
443
  name: "process-event",
@@ -303,21 +447,43 @@ export function createProcessEventHandler(now: () => Temporal.Instant): WriteHan
303
447
  handler: async (event, ctx) => {
304
448
  // @cast-boundary engine-payload — dispatcher-zod-validated payload
305
449
  const payload = event.payload as ProcessEventPayload;
450
+ const aggId = subscriptionAggregateId(event.user.tenantId);
451
+ // One locked load serves admission and the append; the stream grows with every opened checkout.
452
+ // The lock comes first so the stream and `current` are both read under it.
453
+ const stream = await lockAndLoadSubscriptionStream(ctx, aggId);
306
454
  const current = await getSubscriptionForTenant(ctx, event.user.tenantId);
307
- if (isStaleSubscriptionEvent(current, payload, now())) {
455
+ const admission = admitProviderEvent(ctx, stream, current, payload, now());
456
+ if (!admission.admitted) {
308
457
  ctx.obs.log?.warn(
309
- `[billing-foundation:process-event] dropped stale ${payload.type} ${payload.providerEventId}: tenant already tracks another subscription`,
458
+ `[billing-foundation:process-event] ignored ${payload.type} ${payload.providerEventId} (${admission.reason}): provider ${payload.providerName}`,
310
459
  );
311
460
  return {
312
461
  isSuccess: true as const,
313
462
  data: {
314
- duplicate: false,
315
- stale: true,
316
- subscriptionAggregateId: subscriptionAggregateId(event.user.tenantId),
463
+ ignored: true as const,
464
+ reason: admission.reason,
465
+ ...(admission.retry === true && { retry: true as const }),
466
+ subscriptionAggregateId: aggId,
317
467
  },
318
468
  };
319
469
  }
320
- const result = await appendSubscriptionEvent(ctx, event.user.tenantId, payload, now());
470
+ if (isStaleSubscriptionEvent(current, payload, now())) {
471
+ ctx.obs.log?.warn(
472
+ `[billing-foundation:process-event] dropped stale ${payload.type} ${payload.providerEventId}: tenant already tracks another subscription`,
473
+ );
474
+ return {
475
+ isSuccess: true as const,
476
+ data: { duplicate: false, stale: true, subscriptionAggregateId: aggId },
477
+ };
478
+ }
479
+ const result = await appendSubscriptionEvent(
480
+ ctx,
481
+ event.user.tenantId,
482
+ payload,
483
+ now(),
484
+ admission.consentId,
485
+ stream,
486
+ );
321
487
  return { isSuccess: true as const, data: result };
322
488
  },
323
489
  };
@@ -6,7 +6,9 @@
6
6
  // 1. Idempotency-check: loads the payment-stream and scans for an
7
7
  // already-seen `metadata.providerEventId`. A provider-replay with
8
8
  // the same event-id → duplicate=true, no second append.
9
- // 2. ctx.events.unsafeAppend — inline-projection materializes a new
9
+ // 2. Ledger check: the payment must name a checkout the server opened itself
10
+ // (same provider, same price); anything else is ignored.
11
+ // 3. ctx.events.unsafeAppend — inline-projection materializes a new
10
12
  // `read_payments`-row (INSERT-once, not UPSERT — every payment is
11
13
  // its own fact, not a state-update).
12
14
 
@@ -17,23 +19,24 @@ import {
17
19
  import type { WriteHandlerDef } from "@cosmicdrift/kumiko-framework/engine";
18
20
  import * as z from "zod";
19
21
  import { paymentAggregateId } from "../aggregate-id.ts";
22
+ import { findCheckoutOpened, IgnoredEventReasons } from "../checkout-ledger.ts";
20
23
  import { PAYMENT_PII_FIELDS, paymentEntity } from "../entities.ts";
21
24
  import {
22
25
  PAYMENT_AGGREGATE_TYPE,
23
26
  PAYMENT_RECEIVED_EVENT_QN,
24
27
  type PaymentEventHeaders,
25
28
  type PaymentEventPayload,
29
+ PROVIDER_ID_MAX_CHARS,
26
30
  } from "../events.ts";
27
31
  import { hasSeenProviderEvent } from "../provider-event-seen.ts";
28
32
 
29
33
  export const processPaymentEventSchema = z.object({
30
34
  providerEventId: z.string().min(1).max(200),
31
35
  providerName: z.string().min(1).max(50),
32
- providerCheckoutId: z.string().min(1).max(200).optional(),
33
- providerCustomerId: z.string().min(1).max(200),
36
+ providerCheckoutId: z.string().min(1).max(200),
37
+ providerCustomerId: z.string().min(1).max(PROVIDER_ID_MAX_CHARS),
34
38
  priceId: z.string().min(1).max(200),
35
39
  quantity: z.number().int().positive().optional(),
36
- consentId: z.string().min(1).max(100).optional(),
37
40
  });
38
41
  type ProcessPaymentEventPayload = z.infer<typeof processPaymentEventSchema>;
39
42
 
@@ -66,7 +69,31 @@ export const processPaymentEventHandler: WriteHandlerDef = {
66
69
  }
67
70
 
68
71
  // ---------------------------------------------------------------
69
- // 2. Encrypt the provider-subject PII field before it touches storage
72
+ // 2. Ledger: only checkouts this server opened may produce a payment.
73
+ // ---------------------------------------------------------------
74
+ const entry = findCheckoutOpened(existingEvents, {
75
+ providerName: payload.providerName,
76
+ providerCheckoutId: payload.providerCheckoutId,
77
+ mode: "payment",
78
+ });
79
+ const rejection =
80
+ entry === undefined
81
+ ? IgnoredEventReasons.checkoutNotInLedger
82
+ : entry.priceId !== payload.priceId
83
+ ? IgnoredEventReasons.priceMismatch
84
+ : undefined;
85
+ if (rejection !== undefined) {
86
+ ctx.obs.log?.warn(
87
+ `[billing-foundation:process-payment-event] ignored ${payload.providerEventId} (${rejection}): checkout ${payload.providerCheckoutId} of provider ${payload.providerName}`,
88
+ );
89
+ return {
90
+ isSuccess: true as const,
91
+ data: { ignored: true as const, reason: rejection, paymentAggregateId: aggId },
92
+ };
93
+ }
94
+
95
+ // ---------------------------------------------------------------
96
+ // 3. Encrypt the provider-subject PII field before it touches storage
70
97
  // — same rationale as process-event.write.ts's step 3.
71
98
  // ---------------------------------------------------------------
72
99
  const piiKms = configuredPiiSubjectKms();
@@ -85,7 +112,7 @@ export const processPaymentEventHandler: WriteHandlerDef = {
85
112
  : { providerCustomerId: payload.providerCustomerId };
86
113
 
87
114
  // ---------------------------------------------------------------
88
- // 3. Append event on the payment-stream. Inline-projection
115
+ // 4. Append event on the payment-stream. Inline-projection
89
116
  // materializes a new read_payments-row in the same TX.
90
117
  // ---------------------------------------------------------------
91
118
  const eventPayload: PaymentEventPayload = {
@@ -93,14 +120,12 @@ export const processPaymentEventHandler: WriteHandlerDef = {
93
120
  providerCustomerId: encryptedFields.providerCustomerId,
94
121
  priceId: payload.priceId,
95
122
  ...(payload.quantity !== undefined && { quantity: payload.quantity }),
96
- ...(payload.consentId !== undefined && { consentId: payload.consentId }),
123
+ ...(entry?.consentId !== undefined && { consentId: entry.consentId }),
97
124
  };
98
125
  const headers: PaymentEventHeaders = {
99
126
  providerEventId: payload.providerEventId,
100
127
  providerName: payload.providerName,
101
- ...(payload.providerCheckoutId !== undefined && {
102
- providerCheckoutId: payload.providerCheckoutId,
103
- }),
128
+ providerCheckoutId: payload.providerCheckoutId,
104
129
  };
105
130
  await ctx.events.unsafeAppend({
106
131
  aggregateId: aggId,
@@ -0,0 +1,25 @@
1
+ // record-checkout-opened — ledgers a checkout that was opened before the
2
+ // ledger existed (provider migration jobs). Idempotent: an existing entry is
3
+ // left alone.
4
+
5
+ import type { WriteHandlerDef } from "@cosmicdrift/kumiko-framework/engine";
6
+ import { appendCheckoutOpened, findCheckoutOpened, ledgerAggregateId } from "../checkout-ledger.ts";
7
+ import { type CheckoutOpenedPayload, checkoutOpenedPayloadSchema } from "../events.ts";
8
+
9
+ export const recordCheckoutOpenedHandler: WriteHandlerDef = {
10
+ name: "record-checkout-opened",
11
+ agent: { expose: false },
12
+ schema: checkoutOpenedPayloadSchema,
13
+ access: { roles: ["SystemAdmin"] },
14
+ handler: async (event, ctx) => {
15
+ // @cast-boundary engine-payload — dispatcher-zod-validated payload
16
+ const entry = event.payload as CheckoutOpenedPayload;
17
+ const tenantId = event.user.tenantId;
18
+ const existing = await ctx.events.load(ledgerAggregateId(tenantId, entry.mode));
19
+ if (findCheckoutOpened(existing, entry) !== undefined) {
20
+ return { isSuccess: true as const, data: { recorded: false as const } };
21
+ }
22
+ await appendCheckoutOpened(ctx, tenantId, entry);
23
+ return { isSuccess: true as const, data: { recorded: true as const } };
24
+ },
25
+ };
@@ -9,6 +9,7 @@ import * as z from "zod";
9
9
  import {
10
10
  assertBillingEnabled,
11
11
  assertNoActiveSubscription,
12
+ CHECKOUT_START_RATE_LIMIT,
12
13
  isNonEmptyStringArray,
13
14
  joinBaseUrl,
14
15
  listOfferedCatalogProviders,
@@ -77,6 +78,7 @@ export function createStartPlanCheckoutHandler(
77
78
  "Starts a hosted checkout for a plan tier when the tenant has no active subscription; the server picks price and redirect URLs. Name the provider with providerName when the catalog offers several.",
78
79
  schema,
79
80
  access: { roles: purchaseRolesOf(catalog) },
81
+ rateLimit: CHECKOUT_START_RATE_LIMIT,
80
82
  handler: async (event, ctx) => {
81
83
  // @cast-boundary engine-payload — dispatcher-zod-validated payload
82
84
  const payload = event.payload as {
@@ -103,7 +105,13 @@ export function createStartPlanCheckoutHandler(
103
105
  }
104
106
 
105
107
  const consent = consumerProtection
106
- ? await prepareConsent(ctx, consumerProtection, payload.consent, "subscription")
108
+ ? await prepareConsent(
109
+ ctx,
110
+ consumerProtection,
111
+ payload.consent,
112
+ "subscription",
113
+ providerName,
114
+ )
107
115
  : undefined;
108
116
 
109
117
  const baseUrl = options.baseUrl ?? "";
@@ -14,6 +14,7 @@ import {
14
14
  prepareConsent,
15
15
  recordConsent,
16
16
  } from "../consumer-protection/consent-gate.ts";
17
+ import { assertNoPendingPlanSwitch, recordPlanSwitchRequested } from "../pending-plan-switch.ts";
17
18
  import { purchaseRolesOf } from "../plan-catalog.ts";
18
19
  import { type PreparedPlanSwitch, preparePlanSwitch } from "../plan-switch.ts";
19
20
  import type { BillingPlanCatalog, ResolvedBillingFoundationOptions } from "../types.ts";
@@ -64,8 +65,8 @@ export function createSwitchPlanHandler(
64
65
  };
65
66
  }
66
67
 
67
- // Consent is recorded before the provider call: the apply carries the consentId
68
- // as provider metadata, and a failing apply rolls the whole handler back.
68
+ // Consent and the pending marker are recorded before the provider call, and a failing apply rolls
69
+ // the whole handler back. The webhook later picks the consent up again through pendingSwitchConsentId.
69
70
  async function applyInApp(
70
71
  prepared: PreparedPlanSwitch,
71
72
  payload: { readonly tier: string; readonly consent?: ConsentPayload },
@@ -78,8 +79,15 @@ async function applyInApp(
78
79
  message: `billing-foundation: provider "${providerName}" has neither createPlanSwitchSession nor applyPlanSwitch`,
79
80
  });
80
81
  }
82
+ await assertNoPendingPlanSwitch(ctx, options.now());
81
83
  const consent = options.consumerProtection
82
- ? await prepareConsent(ctx, options.consumerProtection, payload.consent, "subscription")
84
+ ? await prepareConsent(
85
+ ctx,
86
+ options.consumerProtection,
87
+ payload.consent,
88
+ "subscription",
89
+ providerName,
90
+ )
83
91
  : undefined;
84
92
  if (consent) {
85
93
  await recordConsent(ctx, consent, {
@@ -89,11 +97,15 @@ async function applyInApp(
89
97
  providerName,
90
98
  });
91
99
  }
100
+ await recordPlanSwitchRequested(ctx, {
101
+ tier: payload.tier,
102
+ priceId: prepared.target.priceId,
103
+ now: options.now(),
104
+ });
92
105
  await plugin.applyPlanSwitch(ctx, {
93
106
  providerSubscriptionId: prepared.subscription.providerSubscriptionId,
94
107
  targetPriceId: prepared.target.priceId,
95
108
  tenantId: ctx.user.tenantId,
96
- ...(consent && { consentId: consent.consentId }),
97
109
  });
98
110
  return { isSuccess: true as const, data: { applied: true as const } };
99
111
  }
@@ -138,6 +138,9 @@ export const BILLING_FOUNDATION_I18N: Readonly<Record<string, LocalizedString>>
138
138
  en: "This subscription is scheduled to end. Reactivate it before switching plans.",
139
139
  },
140
140
  "billing-foundation.errors.alreadyOnPlan": { en: "This tenant is already on that plan." },
141
+ "billing-foundation.errors.planSwitchPending": {
142
+ en: "A plan switch is already being processed. Wait a moment for it to complete.",
143
+ },
141
144
  "billing-foundation.errors.planSwitchNotSupported": {
142
145
  en: "This provider does not support switching plans.",
143
146
  },
@@ -0,0 +1,80 @@
1
+ // An in-app plan switch changes the tier only when the provider's webhook arrives. Until then a
2
+ // second submit (double click, retry after a timeout) would pass the pre-checks and switch again.
3
+
4
+ import type { HandlerContext } from "@cosmicdrift/kumiko-framework/engine";
5
+ import { ConflictError } from "@cosmicdrift/kumiko-framework/errors";
6
+ import { subscriptionAggregateId } from "./aggregate-id.ts";
7
+ import {
8
+ PLAN_SWITCH_REQUESTED_EVENT_QN,
9
+ type PlanSwitchRequestedPayload,
10
+ planSwitchRequestedPayloadSchema,
11
+ SUBSCRIPTION_AGGREGATE_TYPE,
12
+ SUBSCRIPTION_CANCELED_EVENT_QN,
13
+ SUBSCRIPTION_CREATED_EVENT_QN,
14
+ SUBSCRIPTION_UPDATED_EVENT_QN,
15
+ } from "./events.ts";
16
+
17
+ // A webhook that never arrives must not block switching forever.
18
+ const PENDING_PLAN_SWITCH_WINDOW_SECONDS = 30 * 60;
19
+ // 'bfps': serializes the pending check and the append per tenant.
20
+ const PLAN_SWITCH_LOCK_NAMESPACE = 0x62667073;
21
+
22
+ const STATE_EVENT_QNS: ReadonlySet<string> = new Set([
23
+ SUBSCRIPTION_CREATED_EVENT_QN,
24
+ SUBSCRIPTION_UPDATED_EVENT_QN,
25
+ SUBSCRIPTION_CANCELED_EVENT_QN,
26
+ ]);
27
+
28
+ export function pendingPlanSwitchOf(
29
+ storedEvents: readonly { readonly type: string; readonly payload: unknown }[],
30
+ now: Temporal.Instant,
31
+ ): PlanSwitchRequestedPayload | undefined {
32
+ for (let index = storedEvents.length - 1; index >= 0; index--) {
33
+ const stored = storedEvents[index];
34
+ if (stored === undefined) continue;
35
+ if (STATE_EVENT_QNS.has(stored.type)) return undefined;
36
+ if (stored.type !== PLAN_SWITCH_REQUESTED_EVENT_QN) continue;
37
+ const parsed = planSwitchRequestedPayloadSchema.safeParse(stored.payload);
38
+ if (!parsed.success) continue;
39
+ const ageSeconds = now
40
+ .since(Temporal.Instant.from(parsed.data.requestedAtIso))
41
+ .total("seconds");
42
+ return ageSeconds < PENDING_PLAN_SWITCH_WINDOW_SECONDS ? parsed.data : undefined;
43
+ }
44
+ return undefined;
45
+ }
46
+
47
+ export async function assertNoPendingPlanSwitch(
48
+ ctx: HandlerContext,
49
+ now: Temporal.Instant,
50
+ ): Promise<void> {
51
+ const tenantId = ctx.user.tenantId;
52
+ await ctx.db.advisoryXactLock(PLAN_SWITCH_LOCK_NAMESPACE, tenantId);
53
+ const pending = pendingPlanSwitchOf(
54
+ await ctx.events.load(subscriptionAggregateId(tenantId)),
55
+ now,
56
+ );
57
+ if (pending !== undefined) {
58
+ throw new ConflictError({
59
+ i18nKey: "billing-foundation.errors.planSwitchPending",
60
+ message: `a switch to plan "${pending.tier}" is still waiting for the provider's confirmation`,
61
+ });
62
+ }
63
+ }
64
+
65
+ export async function recordPlanSwitchRequested(
66
+ ctx: HandlerContext,
67
+ request: { readonly tier: string; readonly priceId: string; readonly now: Temporal.Instant },
68
+ ): Promise<void> {
69
+ const payload: PlanSwitchRequestedPayload = {
70
+ tier: request.tier,
71
+ priceId: request.priceId,
72
+ requestedAtIso: request.now.toString(),
73
+ };
74
+ await ctx.events.unsafeAppend({
75
+ aggregateId: subscriptionAggregateId(ctx.user.tenantId),
76
+ aggregateType: SUBSCRIPTION_AGGREGATE_TYPE,
77
+ type: PLAN_SWITCH_REQUESTED_EVENT_QN,
78
+ payload,
79
+ });
80
+ }
@@ -0,0 +1,50 @@
1
+ import type { DbRunner } from "@cosmicdrift/kumiko-framework/db";
2
+ import type { FeatureRegistrar } from "@cosmicdrift/kumiko-framework/engine";
3
+ import { scrubEventHeaderKeys } from "@cosmicdrift/kumiko-framework/migrations";
4
+ import {
5
+ INVOICE_PAID_EVENT_QN,
6
+ INVOICE_PAYMENT_FAILED_EVENT_QN,
7
+ SUBSCRIPTION_CANCELED_EVENT_QN,
8
+ SUBSCRIPTION_CREATED_EVENT_QN,
9
+ SUBSCRIPTION_UPDATED_EVENT_QN,
10
+ } from "./events.ts";
11
+
12
+ const SCRUB_RAW_PAYLOAD_HEADERS_ESCAPE_HATCH_REASON =
13
+ "removes the legacy rawPayload header from billing events of every tenant";
14
+
15
+ const RAW_PAYLOAD_HEADER = "rawPayload";
16
+
17
+ const SCRUB_REASON =
18
+ "billing events written before the provider payload was dropped carry it as a plaintext header, which crypto-shredding cannot reach";
19
+
20
+ // Safe to repeat: only events that still carry the header are touched.
21
+ export async function scrubLegacyRawPayloadHeaders(db: DbRunner): Promise<number> {
22
+ const { removedKeys } = await scrubEventHeaderKeys(db, {
23
+ eventTypes: [
24
+ SUBSCRIPTION_CREATED_EVENT_QN,
25
+ SUBSCRIPTION_UPDATED_EVENT_QN,
26
+ SUBSCRIPTION_CANCELED_EVENT_QN,
27
+ INVOICE_PAID_EVENT_QN,
28
+ INVOICE_PAYMENT_FAILED_EVENT_QN,
29
+ ],
30
+ keys: [RAW_PAYLOAD_HEADER],
31
+ reason: SCRUB_REASON,
32
+ });
33
+ return removedKeys;
34
+ }
35
+
36
+ // Boot-time one-off (runOnBoot is marker-deduped per Redis dataset) and idempotent by itself.
37
+ export function registerScrubRawPayloadHeadersJob(r: FeatureRegistrar): void {
38
+ r.job({
39
+ name: "scrub-raw-payload-headers",
40
+ trigger: { manual: true },
41
+ runOnBoot: true,
42
+ escapeHatch: { reason: SCRUB_RAW_PAYLOAD_HEADERS_ESCAPE_HATCH_REASON },
43
+ handler: async (_payload, ctx) => {
44
+ const removedKeys = await scrubLegacyRawPayloadHeaders(ctx.db.unsafeRaw());
45
+ ctx.obs.log.info(
46
+ `[billing-foundation:scrub-raw-payload-headers] removed ${removedKeys} legacy rawPayload headers`,
47
+ );
48
+ },
49
+ });
50
+ }