@cosmicdrift/kumiko-bundled-features 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 (613) hide show
  1. package/dist/admin-shell/feature.js +2 -2
  2. package/dist/agent-tools/agent-doc-lint.js +2 -1
  3. package/dist/agent-tools/agent-manifest.js +33 -25
  4. package/dist/agent-tools/api-docs/collect-events.js +4 -1
  5. package/dist/agent-tools/api-docs/collect.js +3 -3
  6. package/dist/agent-tools/api-docs/generate.js +4 -1
  7. package/dist/agent-tools/api-docs/index.d.ts +1 -0
  8. package/dist/agent-tools/api-docs/index.js +1 -0
  9. package/dist/agent-tools/api-docs/problems.d.ts +21 -0
  10. package/dist/agent-tools/api-docs/problems.js +11 -1
  11. package/dist/agent-tools/api-docs/render-openapi.js +2 -0
  12. package/dist/agent-tools/api-docs/resolve-config.d.ts +9 -0
  13. package/dist/agent-tools/api-docs/resolve-config.js +11 -0
  14. package/dist/agent-tools/api-docs/scope-slug-collisions.d.ts +4 -0
  15. package/dist/agent-tools/api-docs/scope-slug-collisions.js +10 -0
  16. package/dist/agent-tools/api-docs/translation-gaps.d.ts +4 -0
  17. package/dist/agent-tools/api-docs/translation-gaps.js +29 -0
  18. package/dist/agent-tools/api-docs/webhook-example-problems.d.ts +6 -0
  19. package/dist/agent-tools/api-docs/webhook-example-problems.js +25 -0
  20. package/dist/agent-tools/index.d.ts +1 -1
  21. package/dist/agent-tools/index.js +1 -1
  22. package/dist/agent-tools/labels.d.ts +3 -2
  23. package/dist/agent-tools/labels.js +21 -4
  24. package/dist/agent-tools/tool-catalog.d.ts +5 -5
  25. package/dist/agent-tools/tool-catalog.js +12 -10
  26. package/dist/agent-tools/tool-dispatch.js +11 -1
  27. package/dist/agent-tools/types.d.ts +4 -0
  28. package/dist/audit/event-classification.js +6 -0
  29. package/dist/audit/web/i18n.js +1 -0
  30. package/dist/auth-email-password/errors.js +0 -13
  31. package/dist/auth-email-password/handlers/invite-signup-complete.write.js +101 -84
  32. package/dist/auth-email-password/handlers/login-options.query.js +1 -1
  33. package/dist/auth-email-password/handlers/request-account-unlock.write.js +1 -1
  34. package/dist/auth-email-password/handlers/request-email-verification.write.js +0 -1
  35. package/dist/auth-email-password/handlers/request-password-reset.write.js +0 -1
  36. package/dist/auth-email-password/handlers/self-registration-status.query.js +1 -1
  37. package/dist/auth-email-password/reset-token.js +0 -2
  38. package/dist/auth-email-password/seeding.js +34 -8
  39. package/dist/auth-email-password/signup-token-store.d.ts +2 -2
  40. package/dist/auth-email-password/signup-token-store.js +2 -4
  41. package/dist/auth-email-password/unlock-token.js +0 -2
  42. package/dist/auth-email-password/verification-token.js +0 -2
  43. package/dist/auth-email-password/web/auth-form-primitives.js +2 -2
  44. package/dist/auth-email-password/web/auth-gate.js +2 -2
  45. package/dist/auth-email-password/web/auth-redirect.d.ts +1 -0
  46. package/dist/auth-email-password/web/auth-redirect.js +4 -0
  47. package/dist/auth-email-password/web/forgot-password-screen.js +1 -5
  48. package/dist/auth-email-password/web/invite-accept-screen.js +1 -1
  49. package/dist/auth-email-password/web/return-path.d.ts +2 -1
  50. package/dist/auth-email-password/web/return-path.js +2 -1
  51. package/dist/auth-email-password/web/session.js +13 -13
  52. package/dist/auth-email-password/web/signup-screen.js +1 -5
  53. package/dist/auth-email-password/web/static-account.js +6 -2
  54. package/dist/auth-email-password/web/token-confirm-screen.js +4 -5
  55. package/dist/auth-mfa/web/mfa-code-or-recovery-field.d.ts +6 -1
  56. package/dist/auth-mfa/web/mfa-code-or-recovery-field.js +4 -2
  57. package/dist/auth-mfa/web/mfa-disable-dialog.js +1 -1
  58. package/dist/auth-mfa/web/mfa-regenerate-recovery-dialog.js +1 -1
  59. package/dist/auth-mfa/web/mfa-setup-preauth-screen.js +1 -1
  60. package/dist/auth-mfa/web/mfa-verify-screen.js +7 -11
  61. package/dist/auth-mfa-user-data/index.js +5 -6
  62. package/dist/billing-foundation/aggregate-id.js +0 -4
  63. package/dist/billing-foundation/checkout-core.d.ts +2 -0
  64. package/dist/billing-foundation/checkout-core.js +17 -1
  65. package/dist/billing-foundation/checkout-ledger.d.ts +22 -0
  66. package/dist/billing-foundation/checkout-ledger.js +38 -0
  67. package/dist/billing-foundation/consumer-protection/consent-gate.d.ts +1 -1
  68. package/dist/billing-foundation/consumer-protection/consent-gate.js +2 -2
  69. package/dist/billing-foundation/consumer-protection/consent-text.d.ts +6 -2
  70. package/dist/billing-foundation/consumer-protection/consent-text.js +29 -3
  71. package/dist/billing-foundation/consumer-protection/termination-open-cancels.d.ts +2 -1
  72. package/dist/billing-foundation/consumer-protection/termination-open-cancels.js +5 -1
  73. package/dist/billing-foundation/consumer-protection/termination-provider-timeout.d.ts +2 -0
  74. package/dist/billing-foundation/consumer-protection/termination-provider-timeout.js +17 -0
  75. package/dist/billing-foundation/consumer-protection/termination-record.js +5 -4
  76. package/dist/billing-foundation/consumer-protection/termination-revoke.js +1 -1
  77. package/dist/billing-foundation/events.d.ts +23 -0
  78. package/dist/billing-foundation/events.js +39 -10
  79. package/dist/billing-foundation/feature.js +12 -1
  80. package/dist/billing-foundation/handlers/billing-plans.query.js +25 -15
  81. package/dist/billing-foundation/handlers/create-checkout-session.write.js +3 -2
  82. package/dist/billing-foundation/handlers/process-event.write.d.ts +4 -2
  83. package/dist/billing-foundation/handlers/process-event.write.js +132 -25
  84. package/dist/billing-foundation/handlers/process-payment-event.write.d.ts +1 -2
  85. package/dist/billing-foundation/handlers/process-payment-event.write.js +31 -11
  86. package/dist/billing-foundation/handlers/record-checkout-opened.write.d.ts +2 -0
  87. package/dist/billing-foundation/handlers/record-checkout-opened.write.js +22 -0
  88. package/dist/billing-foundation/handlers/start-plan-checkout.write.js +3 -2
  89. package/dist/billing-foundation/handlers/switch-plan.write.js +10 -4
  90. package/dist/billing-foundation/i18n.js +3 -0
  91. package/dist/billing-foundation/pending-plan-switch.d.ts +12 -0
  92. package/dist/billing-foundation/pending-plan-switch.js +57 -0
  93. package/dist/billing-foundation/scrub-raw-payload-headers.d.ts +4 -0
  94. package/dist/billing-foundation/scrub-raw-payload-headers.js +33 -0
  95. package/dist/billing-foundation/types.d.ts +40 -24
  96. package/dist/billing-foundation/validate-options.js +14 -0
  97. package/dist/billing-foundation/web/billing-plans-panel.js +8 -3
  98. package/dist/billing-foundation/web/cancel-contract-dialog.js +1 -1
  99. package/dist/billing-foundation/web/checkout-consent-dialog.js +1 -1
  100. package/dist/billing-foundation/web/constants.d.ts +3 -0
  101. package/dist/billing-foundation/web/constants.js +5 -2
  102. package/dist/billing-foundation/web/plan-switch-confirm-dialog.js +1 -1
  103. package/dist/billing-foundation/webhook-handler.js +53 -11
  104. package/dist/cap-counter/aggregate-id.js +0 -2
  105. package/dist/cap-counter/stock-cap-guard.d.ts +1 -0
  106. package/dist/cap-counter/stock-cap-guard.js +18 -4
  107. package/dist/cap-overview/handlers/tenant-caps-list.query.js +18 -4
  108. package/dist/cap-overview/i18n.js +1 -0
  109. package/dist/cap-overview/index.d.ts +1 -1
  110. package/dist/cap-overview/types.d.ts +4 -0
  111. package/dist/cap-overview/web/cap-cards-panel.js +6 -2
  112. package/dist/cap-overview/web/cap-usage-bar.js +6 -1
  113. package/dist/cap-overview/web/usage-math.d.ts +1 -0
  114. package/dist/cap-overview/web/usage-math.js +4 -0
  115. package/dist/channel-in-app/handlers/read-state-by-keys.query.js +2 -2
  116. package/dist/channel-whatsapp/aggregate-id.d.ts +8 -0
  117. package/dist/channel-whatsapp/aggregate-id.js +18 -0
  118. package/dist/channel-whatsapp/constants.d.ts +25 -0
  119. package/dist/channel-whatsapp/constants.js +36 -0
  120. package/dist/channel-whatsapp/events.d.ts +90 -0
  121. package/dist/channel-whatsapp/events.js +71 -0
  122. package/dist/channel-whatsapp/feature.d.ts +3 -0
  123. package/dist/channel-whatsapp/feature.js +56 -0
  124. package/dist/channel-whatsapp/graph-client.d.ts +85 -0
  125. package/dist/channel-whatsapp/graph-client.js +272 -0
  126. package/dist/channel-whatsapp/in-memory-meta.d.ts +83 -0
  127. package/dist/channel-whatsapp/in-memory-meta.js +181 -0
  128. package/dist/channel-whatsapp/inbound-handlers.d.ts +39 -0
  129. package/dist/channel-whatsapp/inbound-handlers.js +148 -0
  130. package/dist/channel-whatsapp/index.d.ts +10 -0
  131. package/dist/channel-whatsapp/index.js +10 -0
  132. package/dist/channel-whatsapp/meta-signature.d.ts +5 -0
  133. package/dist/channel-whatsapp/meta-signature.js +19 -0
  134. package/dist/channel-whatsapp/options.d.ts +32 -0
  135. package/dist/channel-whatsapp/options.js +83 -0
  136. package/dist/channel-whatsapp/pii.d.ts +32 -0
  137. package/dist/channel-whatsapp/pii.js +61 -0
  138. package/dist/channel-whatsapp/webhook-normalize.d.ts +7 -0
  139. package/dist/channel-whatsapp/webhook-normalize.js +200 -0
  140. package/dist/channel-whatsapp/webhook-routes.d.ts +10 -0
  141. package/dist/channel-whatsapp/webhook-routes.js +118 -0
  142. package/dist/compliance-profiles/handlers/set-profile.write.js +2 -0
  143. package/dist/compliance-profiles/handlers/sub-processors.query.js +1 -1
  144. package/dist/config/handlers/set.write.js +7 -0
  145. package/dist/config/handlers/values.query.js +8 -1
  146. package/dist/config/index.d.ts +1 -1
  147. package/dist/config/index.js +1 -1
  148. package/dist/config/read-redaction.d.ts +1 -0
  149. package/dist/config/read-redaction.js +5 -2
  150. package/dist/config/table.js +1 -0
  151. package/dist/config/write-helpers.js +3 -2
  152. package/dist/crypto-shredding/constants.d.ts +1 -0
  153. package/dist/crypto-shredding/constants.js +1 -0
  154. package/dist/crypto-shredding/handlers/forget-subject.write.js +34 -13
  155. package/dist/crypto-shredding/index.d.ts +1 -0
  156. package/dist/crypto-shredding/index.js +1 -0
  157. package/dist/crypto-shredding/subject-forget-after-delete-hook.d.ts +12 -0
  158. package/dist/crypto-shredding/subject-forget-after-delete-hook.js +38 -0
  159. package/dist/custom-fields/aggregate-id.js +0 -1
  160. package/dist/custom-fields/entity.js +1 -0
  161. package/dist/custom-fields/wire-for-entity.js +0 -1
  162. package/dist/data-retention/erase-notes-of-deleted-row.d.ts +9 -0
  163. package/dist/data-retention/erase-notes-of-deleted-row.js +15 -0
  164. package/dist/data-retention/feature.js +2 -5
  165. package/dist/data-retention/run-retention-cleanup.d.ts +1 -0
  166. package/dist/data-retention/run-retention-cleanup.js +39 -19
  167. package/dist/data-retention/tenant-destruction-hold.js +7 -0
  168. package/dist/delivery/attempt-log-factory.d.ts +3 -0
  169. package/dist/delivery/attempt-log-factory.js +5 -0
  170. package/dist/delivery/attempt-log.d.ts +2 -2
  171. package/dist/delivery/channel-context.d.ts +1 -1
  172. package/dist/delivery/channel-context.js +5 -2
  173. package/dist/delivery/db/queries/preferences.js +0 -1
  174. package/dist/delivery/delivery-service.js +3 -0
  175. package/dist/delivery/feature.d.ts +1 -4
  176. package/dist/delivery/feature.js +3 -1
  177. package/dist/delivery/handlers/attempts-by-keys.query.d.ts +1 -1
  178. package/dist/delivery/handlers/opted-in-user-ids.query.d.ts +7 -0
  179. package/dist/delivery/handlers/opted-in-user-ids.query.js +50 -0
  180. package/dist/delivery/handlers/preferences.query.js +2 -20
  181. package/dist/delivery/handlers/resubscribe-user.write.d.ts +2 -2
  182. package/dist/delivery/handlers/resubscribe-user.write.js +2 -24
  183. package/dist/delivery/handlers/unsubscribe-page-chrome.query.js +2 -0
  184. package/dist/delivery/handlers/unsubscribe-user.write.d.ts +2 -2
  185. package/dist/delivery/handlers/unsubscribe-user.write.js +2 -26
  186. package/dist/delivery/index.d.ts +3 -1
  187. package/dist/delivery/index.js +1 -0
  188. package/dist/delivery/options.d.ts +4 -0
  189. package/dist/delivery/options.js +1 -0
  190. package/dist/delivery/preference-rows.d.ts +9 -0
  191. package/dist/delivery/preference-rows.js +22 -0
  192. package/dist/delivery/set-preference-enabled.d.ts +17 -0
  193. package/dist/delivery/set-preference-enabled.js +26 -0
  194. package/dist/delivery/tables.d.ts +2 -2
  195. package/dist/delivery/testing.d.ts +1 -1
  196. package/dist/delivery/testing.js +3 -1
  197. package/dist/delivery/types.d.ts +1 -0
  198. package/dist/delivery/unsubscribe-page.js +5 -1
  199. package/dist/delivery/upsert-preference.js +0 -1
  200. package/dist/delivery/web/public-names.d.ts +1 -0
  201. package/dist/delivery/web/public-names.js +1 -0
  202. package/dist/derivatives-sharp/render.js +9 -9
  203. package/dist/document-ingest-foundation/aggregate-id.js +0 -1
  204. package/dist/document-ingest-foundation/append-missing-extract-event.d.ts +0 -1
  205. package/dist/document-ingest-foundation/append-missing-extract-event.js +32 -21
  206. package/dist/document-ingest-foundation/feature.js +1 -0
  207. package/dist/document-ingest-foundation/report-ingest-progress.d.ts +1 -1
  208. package/dist/document-ingest-foundation/report-ingest-progress.js +32 -13
  209. package/dist/documents/aggregate-id.js +0 -2
  210. package/dist/documents/constants.d.ts +6 -0
  211. package/dist/documents/constants.js +8 -2
  212. package/dist/documents/ensure-link.d.ts +5 -8
  213. package/dist/documents/ensure-link.js +4 -2
  214. package/dist/documents/feature.d.ts +3 -1
  215. package/dist/documents/feature.js +29 -5
  216. package/dist/documents/handlers/import.write.js +2 -2
  217. package/dist/documents/queries/expiry-overview.query.js +2 -1
  218. package/dist/documents/queries/for-record.query.js +3 -4
  219. package/dist/documents/queries/list-page.js +11 -3
  220. package/dist/documents/queries/overview.query.js +2 -2
  221. package/dist/documents/screens.js +3 -3
  222. package/dist/documents/tab.js +1 -1
  223. package/dist/feature-toggles/toggle-sync-signal.d.ts +2 -2
  224. package/dist/feature-toggles/toggle-sync-signal.js +3 -2
  225. package/dist/file-derivatives/handlers/public-variant-by-file-ref.query.js +1 -1
  226. package/dist/file-derivatives/handlers/public-variant.query.js +1 -1
  227. package/dist/file-foundation/probe.js +9 -3
  228. package/dist/file-foundation/read-file-ref-content.js +23 -11
  229. package/dist/file-provider-inmemory/feature.js +1 -1
  230. package/dist/file-provider-s3/env-feature.js +1 -1
  231. package/dist/file-provider-s3/env-named-feature.js +1 -1
  232. package/dist/file-provider-s3/env-schema.d.ts +10 -1
  233. package/dist/file-provider-s3/env-schema.js +20 -7
  234. package/dist/file-provider-s3/feature.js +1 -1
  235. package/dist/file-provider-s3/index.d.ts +1 -1
  236. package/dist/file-provider-s3/index.js +1 -1
  237. package/dist/file-provider-s3/lib/env-helper.d.ts +3 -2
  238. package/dist/file-provider-s3/lib/env-helper.js +13 -12
  239. package/dist/file-provider-s3/lib/s3-provider.js +10 -2
  240. package/dist/folders/aggregate-id.js +0 -1
  241. package/dist/folders/web/folder-manager.js +1 -1
  242. package/dist/folders-user-data/index.js +12 -14
  243. package/dist/form-draft/feature.js +1 -0
  244. package/dist/helpdesk/entity.js +4 -1
  245. package/dist/helpdesk/feature.js +37 -0
  246. package/dist/helpdesk/handlers/access.d.ts +0 -1
  247. package/dist/helpdesk/handlers/access.js +0 -3
  248. package/dist/helpdesk/handlers/attempts.js +7 -13
  249. package/dist/helpdesk/handlers/challenge.query.js +1 -2
  250. package/dist/helpdesk/handlers/reply.write.js +7 -8
  251. package/dist/helpdesk/handlers/report.write.js +4 -7
  252. package/dist/helpdesk/handlers/submit.write.js +5 -9
  253. package/dist/helpdesk/index.d.ts +1 -1
  254. package/dist/helpdesk/index.js +1 -1
  255. package/dist/helpdesk/legacy-contact-config.d.ts +3 -0
  256. package/dist/helpdesk/legacy-contact-config.js +57 -0
  257. package/dist/helpdesk/legacy-contact-erasure.d.ts +9 -0
  258. package/dist/helpdesk/legacy-contact-erasure.js +19 -0
  259. package/dist/helpdesk/legacy-contact-retention.d.ts +2 -0
  260. package/dist/helpdesk/legacy-contact-retention.js +53 -0
  261. package/dist/helpdesk/legacy-contact-streams.d.ts +20 -0
  262. package/dist/helpdesk/legacy-contact-streams.js +124 -0
  263. package/dist/helpdesk/legacy-contact-user-data.d.ts +5 -0
  264. package/dist/helpdesk/legacy-contact-user-data.js +62 -0
  265. package/dist/helpdesk/lib.d.ts +8 -2
  266. package/dist/helpdesk/lib.js +32 -32
  267. package/dist/helpdesk/user-data-hooks.d.ts +10 -1
  268. package/dist/helpdesk/user-data-hooks.js +47 -36
  269. package/dist/helpdesk/web/constants.d.ts +0 -1
  270. package/dist/helpdesk/web/constants.js +0 -1
  271. package/dist/inbound-mail-foundation/account-health.js +1 -1
  272. package/dist/inbound-mail-foundation/account-poll.js +3 -1
  273. package/dist/inbound-mail-foundation/aggregate-id.js +0 -2
  274. package/dist/inbound-mail-foundation/constants.d.ts +6 -0
  275. package/dist/inbound-mail-foundation/constants.js +6 -0
  276. package/dist/inbound-mail-foundation/content-refetch.d.ts +4 -0
  277. package/dist/inbound-mail-foundation/content-refetch.js +13 -3
  278. package/dist/inbound-mail-foundation/entities.js +58 -15
  279. package/dist/inbound-mail-foundation/events.js +16 -16
  280. package/dist/inbound-mail-foundation/feature.js +3 -1
  281. package/dist/inbound-mail-foundation/handlers/account-address.d.ts +2 -2
  282. package/dist/inbound-mail-foundation/handlers/account-address.js +10 -2
  283. package/dist/inbound-mail-foundation/handlers/attach-message-content.write.js +8 -3
  284. package/dist/inbound-mail-foundation/handlers/connect-account.write.js +14 -8
  285. package/dist/inbound-mail-foundation/handlers/forget-message.write.d.ts +7 -0
  286. package/dist/inbound-mail-foundation/handlers/forget-message.write.js +58 -0
  287. package/dist/inbound-mail-foundation/handlers/ingest-message-schema.js +12 -5
  288. package/dist/inbound-mail-foundation/i18n.js +3 -0
  289. package/dist/inbound-mail-foundation/index.d.ts +1 -0
  290. package/dist/inbound-mail-foundation/index.js +1 -0
  291. package/dist/inbound-mail-foundation/normalize-inbound-message.d.ts +6 -0
  292. package/dist/inbound-mail-foundation/normalize-inbound-message.js +21 -8
  293. package/dist/inbound-mail-foundation/oauth-access-token.js +1 -1
  294. package/dist/inbound-mail-foundation/outbound-mail.d.ts +2 -0
  295. package/dist/inbound-mail-foundation/personal-address.d.ts +1 -0
  296. package/dist/inbound-mail-foundation/personal-address.js +16 -0
  297. package/dist/inbound-mail-foundation/purge-messages.d.ts +20 -0
  298. package/dist/inbound-mail-foundation/purge-messages.js +33 -0
  299. package/dist/inbound-mail-foundation/quarantine.d.ts +3 -2
  300. package/dist/inbound-mail-foundation/quarantine.js +9 -5
  301. package/dist/inbound-mail-foundation/retention-job.js +1 -5
  302. package/dist/inbound-mail-foundation/retention-sweep.js +17 -28
  303. package/dist/inbound-mail-foundation/sanitize-inbound-html.d.ts +0 -1
  304. package/dist/inbound-mail-foundation/sanitize-inbound-html.js +2 -4
  305. package/dist/inbound-mail-foundation/send-from-account.js +9 -1
  306. package/dist/inbound-mail-foundation/supervisor-ingest.js +4 -1
  307. package/dist/inbound-mail-foundation/sync-account-now.js +1 -1
  308. package/dist/inbound-mail-foundation/tenant-destroy-hook.js +3 -6
  309. package/dist/inbound-mail-foundation/watch-supervisor.js +1 -1
  310. package/dist/inbound-provider-imap/byte-budget.d.ts +14 -0
  311. package/dist/inbound-provider-imap/byte-budget.js +53 -0
  312. package/dist/inbound-provider-imap/connect-mailbox.d.ts +2 -4
  313. package/dist/inbound-provider-imap/connect-mailbox.js +8 -3
  314. package/dist/inbound-provider-imap/connect-my-mailbox.d.ts +1 -1
  315. package/dist/inbound-provider-imap/connect-my-mailbox.js +15 -4
  316. package/dist/inbound-provider-imap/connect-target-rate-limit.d.ts +3 -0
  317. package/dist/inbound-provider-imap/connect-target-rate-limit.js +37 -0
  318. package/dist/inbound-provider-imap/download-batch.d.ts +10 -0
  319. package/dist/inbound-provider-imap/download-batch.js +21 -6
  320. package/dist/inbound-provider-imap/feature.js +7 -4
  321. package/dist/inbound-provider-imap/fetch-content.js +35 -30
  322. package/dist/inbound-provider-imap/i18n.js +2 -2
  323. package/dist/inbound-provider-imap/parse-message.d.ts +7 -0
  324. package/dist/inbound-provider-imap/parse-message.js +8 -0
  325. package/dist/inbound-provider-imap/reconnect-mailbox.js +5 -4
  326. package/dist/inbound-provider-imap/send-mail.d.ts +2 -0
  327. package/dist/inbound-provider-imap/send-mail.js +32 -6
  328. package/dist/inbound-provider-imap/smtp-client.d.ts +9 -2
  329. package/dist/inbound-provider-imap/smtp-client.js +15 -3
  330. package/dist/inbound-provider-imap/watch-mailbox.js +3 -24
  331. package/dist/inbound-provider-inmemory/feature.js +1 -1
  332. package/dist/jobs/events.d.ts +13 -0
  333. package/dist/jobs/events.js +8 -0
  334. package/dist/jobs/feature.js +2 -0
  335. package/dist/jobs/handlers/consumer.write.js +31 -20
  336. package/dist/jobs/web/constants.d.ts +3 -0
  337. package/dist/jobs/web/constants.js +3 -0
  338. package/dist/mail-transport-inmemory/feature.js +1 -1
  339. package/dist/mail-transport-smtp/feature.js +3 -2
  340. package/dist/managed-pages/handlers/branding.query.js +1 -1
  341. package/dist/managed-pages/handlers/by-slug.query.js +1 -1
  342. package/dist/managed-pages/handlers/by-tenant-published.query.js +1 -1
  343. package/dist/managed-pages/render-page-body.d.ts +2 -0
  344. package/dist/managed-pages/render-page-body.js +12 -8
  345. package/dist/managed-pages/screens/page-screens.d.ts +3 -2
  346. package/dist/managed-pages/screens/page-screens.js +14 -33
  347. package/dist/managed-pages/table.js +1 -0
  348. package/dist/managed-pages/web/client-plugin.js +8 -6
  349. package/dist/managed-pages/web/constants.d.ts +5 -1
  350. package/dist/managed-pages/web/constants.js +6 -1
  351. package/dist/managed-pages/web/i18n.js +11 -3
  352. package/dist/managed-pages/web/markdown-to-document.js +1 -1
  353. package/dist/managed-pages/web/page-edit-draft.d.ts +32 -0
  354. package/dist/managed-pages/web/page-edit-draft.js +76 -0
  355. package/dist/managed-pages/web/page-edit-screen.d.ts +2 -0
  356. package/dist/managed-pages/web/page-edit-screen.js +113 -0
  357. package/dist/managed-pages/web/page-settings-rail.d.ts +11 -0
  358. package/dist/managed-pages/web/page-settings-rail.js +14 -0
  359. package/dist/notes-history-user-data/index.js +8 -14
  360. package/dist/personal-access-tokens/boot-rules.d.ts +5 -0
  361. package/dist/personal-access-tokens/boot-rules.js +5 -0
  362. package/dist/personal-access-tokens/handlers/create.write.js +0 -1
  363. package/dist/personal-access-tokens/scope-events-check.js +26 -6
  364. package/dist/presence/handlers/list.query.js +18 -8
  365. package/dist/presence/room.d.ts +2 -0
  366. package/dist/presence/room.js +8 -5
  367. package/dist/presence/store.d.ts +2 -0
  368. package/dist/presence/store.js +62 -26
  369. package/dist/readiness/handlers/latest-summary.query.js +10 -6
  370. package/dist/readiness/handlers/run-probes.write.js +24 -4
  371. package/dist/readiness/handlers/run-tone.js +3 -2
  372. package/dist/readiness/handlers/status.query.js +11 -3
  373. package/dist/readiness/probe-context.js +7 -10
  374. package/dist/readiness/screens.js +4 -4
  375. package/dist/readiness/visible-results.d.ts +1 -1
  376. package/dist/readiness/visible-results.js +5 -2
  377. package/dist/renderer-foundation/api.js +6 -12
  378. package/dist/renderer-foundation/types.d.ts +2 -2
  379. package/dist/secrets/db/queries/read.d.ts +2 -1
  380. package/dist/secrets/db/queries/read.js +10 -1
  381. package/dist/secrets/handlers/list.query.js +4 -2
  382. package/dist/secrets/secret-scope.d.ts +0 -1
  383. package/dist/secrets/secret-scope.js +2 -2
  384. package/dist/secrets/secrets-context.js +4 -4
  385. package/dist/secrets/table.d.ts +1 -1
  386. package/dist/secrets/write-gate.js +4 -2
  387. package/dist/seo/handlers/seo-config.query.js +1 -1
  388. package/dist/shared/acknowledged-system-db.d.ts +5 -0
  389. package/dist/shared/acknowledged-system-db.js +9 -0
  390. package/dist/shared/assert-billing-live.d.ts +1 -0
  391. package/dist/shared/assert-billing-live.js +5 -2
  392. package/dist/shared/hmac-signature.js +4 -2
  393. package/dist/shared/index.d.ts +7 -2
  394. package/dist/shared/index.js +7 -2
  395. package/dist/shared/normalize-email.d.ts +1 -0
  396. package/dist/shared/normalize-email.js +3 -0
  397. package/dist/shared/parent-visibility.d.ts +1 -0
  398. package/dist/shared/parent-visibility.js +16 -1
  399. package/dist/shared/password-hashing.js +0 -1
  400. package/dist/shared/price-env-shape.js +1 -1
  401. package/dist/shared/register-user-data-hooks.d.ts +11 -0
  402. package/dist/shared/register-user-data-hooks.js +11 -0
  403. package/dist/shared/require-bootstrap-extension.d.ts +9 -0
  404. package/dist/shared/require-bootstrap-extension.js +16 -0
  405. package/dist/shared/send-best-effort.d.ts +3 -0
  406. package/dist/shared/send-best-effort.js +19 -0
  407. package/dist/shared/stream-tenant-backfill.d.ts +1 -0
  408. package/dist/shared/stream-tenant-backfill.js +17 -1
  409. package/dist/shared/stream-tenant-derived-state.d.ts +5 -1
  410. package/dist/shared/stream-tenant-derived-state.js +19 -2
  411. package/dist/step-dispatcher/constants.d.ts +4 -0
  412. package/dist/step-dispatcher/constants.js +11 -0
  413. package/dist/step-dispatcher/deliver-dispatch-request.d.ts +1 -0
  414. package/dist/step-dispatcher/deliver-dispatch-request.js +41 -3
  415. package/dist/step-dispatcher/feature.js +31 -2
  416. package/dist/step-dispatcher/mail-runner.js +0 -1
  417. package/dist/step-dispatcher/sweep-abandoned.d.ts +11 -0
  418. package/dist/step-dispatcher/sweep-abandoned.js +46 -0
  419. package/dist/subscription-mollie/plugin-methods.d.ts +1 -0
  420. package/dist/subscription-mollie/plugin-methods.js +1 -2
  421. package/dist/subscription-mollie/verify-webhook.js +5 -5
  422. package/dist/subscription-paddle/backfill-checkout-ledger.d.ts +9 -0
  423. package/dist/subscription-paddle/backfill-checkout-ledger.js +112 -0
  424. package/dist/subscription-paddle/checkout-config.query.js +1 -1
  425. package/dist/subscription-paddle/checkout-methods.js +2 -8
  426. package/dist/subscription-paddle/constants.d.ts +0 -1
  427. package/dist/subscription-paddle/constants.js +1 -2
  428. package/dist/subscription-paddle/feature.d.ts +0 -4
  429. package/dist/subscription-paddle/feature.js +21 -20
  430. package/dist/subscription-paddle/ledger-backfill-marker.d.ts +17 -0
  431. package/dist/subscription-paddle/ledger-backfill-marker.js +53 -0
  432. package/dist/subscription-paddle/plan-switch-methods.js +2 -8
  433. package/dist/subscription-paddle/redeliver-legacy-checkout.d.ts +11 -0
  434. package/dist/subscription-paddle/redeliver-legacy-checkout.js +43 -0
  435. package/dist/subscription-paddle/runtime.d.ts +3 -5
  436. package/dist/subscription-paddle/runtime.js +4 -7
  437. package/dist/subscription-paddle/subscription-state.d.ts +1 -0
  438. package/dist/subscription-paddle/subscription-state.js +1 -0
  439. package/dist/subscription-paddle/webhook-events.d.ts +4 -0
  440. package/dist/subscription-paddle/webhook-events.js +40 -22
  441. package/dist/subscription-stripe/feature.d.ts +4 -0
  442. package/dist/subscription-stripe/feature.js +1 -0
  443. package/dist/subscription-stripe/plugin-methods.d.ts +1 -0
  444. package/dist/subscription-stripe/plugin-methods.js +2 -5
  445. package/dist/subscription-stripe/runtime.d.ts +2 -1
  446. package/dist/subscription-stripe/runtime.js +5 -7
  447. package/dist/subscription-stripe/verify-webhook.js +31 -6
  448. package/dist/tags/aggregate-id.js +0 -1
  449. package/dist/tags/web/tag-chip.js +0 -1
  450. package/dist/tags/web/tag-manager.js +3 -1
  451. package/dist/template-resolver/api.js +6 -12
  452. package/dist/template-resolver/document-sanitizer.d.ts +1 -1
  453. package/dist/template-resolver/document-sanitizer.js +18 -0
  454. package/dist/template-resolver/feature.d.ts +1 -0
  455. package/dist/template-resolver/feature.js +2 -0
  456. package/dist/template-resolver/handlers/body-preview.query.d.ts +11 -0
  457. package/dist/template-resolver/handlers/body-preview.query.js +41 -0
  458. package/dist/template-resolver/handlers/by-slug.query.js +1 -1
  459. package/dist/template-resolver/handlers/by-tenant.query.js +1 -1
  460. package/dist/template-resolver/handlers/collection-shared.js +5 -8
  461. package/dist/template-resolver/handlers/overview.query.d.ts +1 -0
  462. package/dist/template-resolver/handlers/overview.query.js +2 -1
  463. package/dist/template-resolver/handlers/send-test.write.js +27 -8
  464. package/dist/template-resolver/linked-resources.js +2 -6
  465. package/dist/template-resolver/seeding.js +92 -1
  466. package/dist/template-resolver/table.js +1 -0
  467. package/dist/template-resolver/template-draft.js +2 -1
  468. package/dist/template-resolver/template-preview.js +12 -3
  469. package/dist/template-resolver/testing.js +0 -2
  470. package/dist/template-resolver/web/client-plugin.js +3 -0
  471. package/dist/template-resolver/web/collection-entry-create-form.js +19 -9
  472. package/dist/template-resolver/web/constants.d.ts +2 -0
  473. package/dist/template-resolver/web/constants.js +2 -0
  474. package/dist/template-resolver/web/content-tree-provider.js +0 -1
  475. package/dist/template-resolver/web/content-workbench.d.ts +22 -0
  476. package/dist/template-resolver/web/content-workbench.js +32 -0
  477. package/dist/template-resolver/web/document-insert-model.d.ts +2 -4
  478. package/dist/template-resolver/web/document-insert-model.js +1 -2
  479. package/dist/template-resolver/web/document-link-policy.d.ts +3 -0
  480. package/dist/template-resolver/web/document-link-policy.js +53 -0
  481. package/dist/template-resolver/web/document-schema.d.ts +2 -4
  482. package/dist/template-resolver/web/document-schema.js +2 -53
  483. package/dist/template-resolver/web/document-tiptap-context.d.ts +2 -5
  484. package/dist/template-resolver/web/document-tiptap-context.js +2 -2
  485. package/dist/template-resolver/web/document-tiptap-editor.js +2 -2
  486. package/dist/template-resolver/web/document-tiptap-helpers.d.ts +7 -4
  487. package/dist/template-resolver/web/document-tiptap-toolbar-groups.js +3 -3
  488. package/dist/template-resolver/web/editor-handle.js +1 -0
  489. package/dist/template-resolver/web/fill-document-variables.d.ts +1 -0
  490. package/dist/template-resolver/web/fill-document-variables.js +22 -0
  491. package/dist/template-resolver/web/i18n.js +10 -0
  492. package/dist/template-resolver/web/index.d.ts +3 -0
  493. package/dist/template-resolver/web/index.js +2 -0
  494. package/dist/template-resolver/web/preview-targets.d.ts +5 -0
  495. package/dist/template-resolver/web/preview-targets.js +21 -0
  496. package/dist/template-resolver/web/qualified-names.d.ts +1 -0
  497. package/dist/template-resolver/web/qualified-names.js +1 -0
  498. package/dist/template-resolver/web/snippet-preview-renderer.d.ts +2 -0
  499. package/dist/template-resolver/web/snippet-preview-renderer.js +15 -0
  500. package/dist/template-resolver/web/string-values.d.ts +1 -0
  501. package/dist/template-resolver/web/string-values.js +8 -0
  502. package/dist/template-resolver/web/text-block-editor.js +18 -11
  503. package/dist/template-resolver/web/use-collection-entry-create.d.ts +1 -0
  504. package/dist/template-resolver/web/use-collection-entry-create.js +6 -0
  505. package/dist/template-resolver/web/use-document-tiptap-model.d.ts +2 -6
  506. package/dist/template-resolver/web/use-text-block-editor.d.ts +3 -0
  507. package/dist/template-resolver/web/use-text-block-editor.js +26 -5
  508. package/dist/template-resolver/web/web-preview-renderer.d.ts +12 -0
  509. package/dist/template-resolver/web/web-preview-renderer.js +45 -0
  510. package/dist/template-resolver-user-data/index.js +11 -10
  511. package/dist/tenant/handlers/create.write.js +3 -7
  512. package/dist/tenant/handlers/list.query.js +3 -8
  513. package/dist/tenant/handlers/member-directory.query.js +10 -5
  514. package/dist/tenant/handlers/toggle-enabled.write.js +1 -1
  515. package/dist/tenant/invited-membership.js +9 -1
  516. package/dist/tenant/seeding.d.ts +3 -0
  517. package/dist/tenant/seeding.js +3 -1
  518. package/dist/tenant/stream-tenant-backfill.js +5 -1
  519. package/dist/tenant/testing.js +1 -1
  520. package/dist/tenant-inactivity/check-inactive-tenants.js +29 -18
  521. package/dist/tenant-inactivity/constants.js +1 -2
  522. package/dist/tenant-inactivity/handlers/keep-account.write.js +8 -2
  523. package/dist/tenant-inactivity/state-store.d.ts +3 -1
  524. package/dist/tenant-inactivity/state-store.js +16 -1
  525. package/dist/tenant-lifecycle/constants.d.ts +1 -0
  526. package/dist/tenant-lifecycle/constants.js +3 -0
  527. package/dist/tenant-lifecycle/feature.js +1 -0
  528. package/dist/tenant-lifecycle/run-tenant-destroy.js +38 -5
  529. package/dist/tenant-lifecycle/stages.js +14 -2
  530. package/dist/tier-engine/aggregate-id.js +0 -1
  531. package/dist/tier-engine/feature.js +9 -2
  532. package/dist/user/db/queries/stream-tenant-backfill.js +2 -1
  533. package/dist/user/handlers/me.query.js +4 -1
  534. package/dist/user/index.d.ts +1 -0
  535. package/dist/user/index.js +1 -0
  536. package/dist/user/resolve-verified-user-email.d.ts +2 -0
  537. package/dist/user/resolve-verified-user-email.js +14 -0
  538. package/dist/user-data-rights/db/queries/export-jobs.js +0 -1
  539. package/dist/user-data-rights/feature.js +1 -0
  540. package/dist/user-data-rights/handlers/confirm-deletion-by-token.write.js +1 -1
  541. package/dist/user-data-rights/handlers/download-by-token.query.js +1 -1
  542. package/dist/user-data-rights/handlers/request-deletion-by-email.write.js +1 -1
  543. package/dist/user-data-rights/run-export-jobs.js +0 -2
  544. package/dist/user-data-rights/run-forget-cleanup.js +2 -2
  545. package/dist/user-data-rights/schema/download-attempt.js +3 -2
  546. package/dist/user-data-rights/web/confirm-deletion-screen.js +2 -2
  547. package/dist/user-data-rights/web/privacy-center-screen.js +1 -1
  548. package/dist/user-data-rights/web/request-deletion-screen.js +2 -2
  549. package/dist/user-data-rights-defaults/hooks/api-token.userdata-hook.js +5 -6
  550. package/dist/user-data-rights-defaults/hooks/hard-delete-own-rows-hook.d.ts +7 -0
  551. package/dist/user-data-rights-defaults/hooks/hard-delete-own-rows-hook.js +11 -0
  552. package/dist/user-data-rights-defaults/hooks/in-app-message.userdata-hook.js +5 -6
  553. package/dist/user-data-rights-defaults/hooks/job-run.userdata-hook.js +2 -1
  554. package/dist/user-data-rights-defaults/hooks/user-session.userdata-hook.js +5 -6
  555. package/dist/user-profile/handlers/change-email.write.js +0 -1
  556. package/dist/waitlist/handlers/reject.write.js +2 -1
  557. package/dist/waitlist/handlers/submit.write.js +6 -19
  558. package/dist/waitlist/import.js +2 -1
  559. package/dist/waitlist/lib.d.ts +0 -1
  560. package/dist/waitlist/lib.js +2 -10
  561. package/dist/waitlist/link-on-signup.js +2 -2
  562. package/dist/waitlist/user-data-hooks.js +6 -20
  563. package/dist/workflow-runner/aggregate-id.js +0 -1
  564. package/dist/workflow-runner/event-trigger.js +6 -2
  565. package/dist/workflow-runner/feature.js +1 -5
  566. package/dist/workflow-runner/handlers/resume-run.write.js +6 -4
  567. package/dist/workflow-runner/runner.d.ts +1 -0
  568. package/package.json +35 -11
  569. package/src/admin-shell/changes.json +6 -0
  570. package/src/agent-tools/changes.json +12 -0
  571. package/src/auth-email-password/changes.json +18 -0
  572. package/src/auth-mfa/changes.json +6 -0
  573. package/src/billing-foundation/changes.json +61 -0
  574. package/src/cap-counter/changes.json +6 -0
  575. package/src/cap-overview/changes.json +6 -0
  576. package/src/channel-in-app/changes.json +6 -0
  577. package/src/channel-whatsapp/changes.json +32 -0
  578. package/src/compliance-profiles/changes.json +5 -0
  579. package/src/config/changes.json +12 -0
  580. package/src/crypto-shredding/changes.json +18 -0
  581. package/src/data-retention/changes.json +12 -0
  582. package/src/delivery/changes.json +12 -0
  583. package/src/document-ingest-foundation/changes.json +6 -0
  584. package/src/documents/changes.json +24 -0
  585. package/src/file-provider-s3/changes.json +14 -0
  586. package/src/files/changes.json +7 -0
  587. package/src/helpdesk/changes.json +56 -0
  588. package/src/inbound-mail-foundation/changes.json +54 -0
  589. package/src/inbound-provider-imap/changes.json +13 -0
  590. package/src/mail-foundation/changes.json +6 -0
  591. package/src/managed-pages/changes.json +12 -0
  592. package/src/presence/changes.json +6 -0
  593. package/src/readiness/changes.json +25 -0
  594. package/src/secrets/changes.json +7 -0
  595. package/src/shared/changes.json +12 -0
  596. package/src/step-dispatcher/changes.json +18 -0
  597. package/src/subscription-mollie/changes.json +7 -0
  598. package/src/subscription-paddle/changes.json +19 -0
  599. package/src/subscription-stripe/changes.json +13 -0
  600. package/src/template-resolver/changes.json +48 -0
  601. package/src/tenant/changes.json +6 -0
  602. package/src/tenant-inactivity/changes.json +6 -0
  603. package/src/tenant-lifecycle/changes.json +24 -0
  604. package/src/tier-engine/changes.json +6 -0
  605. package/src/user/changes.json +6 -0
  606. package/src/waitlist/changes.json +6 -0
  607. package/src/workflow-runner/changes.json +6 -0
  608. package/dist/managed-pages/web/page-body-section.d.ts +0 -3
  609. package/dist/managed-pages/web/page-body-section.js +0 -40
  610. package/dist/subscription-paddle/tenant-binding.d.ts +0 -8
  611. package/dist/subscription-paddle/tenant-binding.js +0 -26
  612. package/dist/template-resolver/web/content-field.d.ts +0 -9
  613. package/dist/template-resolver/web/content-field.js +0 -14
@@ -9,9 +9,11 @@
9
9
  // bucket — events are business facts: future consumers (billing-history,
10
10
  // accounting-export, churn-analytics) listen directly for the event type
11
11
  // without a payload discriminator.
12
+ import { piiCiphertextMaxLengthFor } from "@cosmicdrift/kumiko-framework/crypto";
12
13
  import * as z from "zod";
13
14
  import { BILLING_FOUNDATION_FEATURE, SubscriptionStatuses } from "./web/constants.js";
14
15
  import { CONSENT_LOCALES } from "./web/consumer-protection/consent-locale.js";
16
+ export const PROVIDER_ID_MAX_CHARS = 200;
15
17
  // Aggregate type for the event store. One subscription per tenant is
16
18
  // one stream; the subscriptionAggregateId helper provides the stream ID.
17
19
  export const SUBSCRIPTION_AGGREGATE_TYPE = "subscription";
@@ -42,12 +44,9 @@ const statusEnum = z.enum([
42
44
  // PII, and event headers cannot be crypto-shredded.
43
45
  export const subscriptionEventPayloadSchema = z.object({
44
46
  providerName: z.string().min(1).max(50),
45
- // 1000, not 200: these two are `tenantOwned: true` on the entity (see
46
- // entities.ts — crypto-shreds on tenant-destroy, unlike `encrypted`).
47
- // process-event.write.ts stores the PII-ciphertext here, not the raw
48
- // provider id. A 200-char plaintext id becomes ~300+ chars of ciphertext.
49
- providerCustomerId: z.string().min(1).max(1000),
50
- providerSubscriptionId: z.string().min(1).max(1000),
47
+ // Ciphertext, not the raw id: the plaintext id is limited to PROVIDER_ID_MAX_CHARS.
48
+ providerCustomerId: z.string().min(1).max(piiCiphertextMaxLengthFor(PROVIDER_ID_MAX_CHARS)),
49
+ providerSubscriptionId: z.string().min(1).max(piiCiphertextMaxLengthFor(PROVIDER_ID_MAX_CHARS)),
51
50
  status: statusEnum,
52
51
  tier: z.string().min(1).max(50),
53
52
  currentPeriodEndIso: z.string().min(1),
@@ -74,16 +73,46 @@ export const PAYMENT_RECEIVED_EVENT_SHORT = "payment-received";
74
73
  export const PAYMENT_RECEIVED_EVENT_QN = `${BILLING_FOUNDATION_FEATURE}:event:${PAYMENT_RECEIVED_EVENT_SHORT}`;
75
74
  export const paymentEventPayloadSchema = z.object({
76
75
  providerName: z.string().min(1).max(50),
77
- // 1000, not 200: `tenantOwned: true` on paymentEntity (see entities.ts) —
78
- // this stores the PII-ciphertext, not the raw provider id. Mirrors
79
- // subscriptionEventPayloadSchema's same rationale.
80
- providerCustomerId: z.string().min(1).max(1000),
76
+ // Ciphertext, not the raw id (plaintext limit PROVIDER_ID_MAX_CHARS).
77
+ providerCustomerId: z.string().min(1).max(piiCiphertextMaxLengthFor(PROVIDER_ID_MAX_CHARS)),
81
78
  priceId: z.string().min(1).max(200),
82
79
  // Optional so payloads stored before quantity existed still parse; absent = 1.
83
80
  quantity: z.number().int().positive().optional(),
84
81
  consentId: z.string().min(1).max(100).optional(),
85
82
  });
86
83
  // =============================================================================
84
+ // checkout-opened — the server's checkout ledger
85
+ // =============================================================================
86
+ //
87
+ // Appended onto the subscription- or payment-stream (by checkout mode) right
88
+ // after the provider handed out a checkout. Webhooks are only accepted for
89
+ // checkouts listed here, so a checkout opened client-side (public provider
90
+ // tokens) cannot mint payments or subscriptions. No projection applies it.
91
+ export const CHECKOUT_OPENED_EVENT_SHORT = "checkout-opened";
92
+ export const CHECKOUT_OPENED_EVENT_QN = `${BILLING_FOUNDATION_FEATURE}:event:${CHECKOUT_OPENED_EVENT_SHORT}`;
93
+ export const CHECKOUT_MODES = ["subscription", "payment"];
94
+ export const checkoutOpenedPayloadSchema = z.object({
95
+ providerName: z.string().min(1).max(50),
96
+ providerCheckoutId: z.string().min(1).max(200),
97
+ priceId: z.string().min(1).max(200),
98
+ mode: z.enum(CHECKOUT_MODES),
99
+ consentId: z.string().min(1).max(100).optional(),
100
+ });
101
+ // =============================================================================
102
+ // plan-switch-requested — in-app plan switch in flight
103
+ // =============================================================================
104
+ //
105
+ // Appended onto the subscription stream when switch-plan applied a switch at the provider; the
106
+ // tier only changes once the provider's webhook arrives. No projection applies it. It blocks a
107
+ // second switch until a state event follows or the window runs out.
108
+ export const PLAN_SWITCH_REQUESTED_EVENT_SHORT = "plan-switch-requested";
109
+ export const PLAN_SWITCH_REQUESTED_EVENT_QN = `${BILLING_FOUNDATION_FEATURE}:event:${PLAN_SWITCH_REQUESTED_EVENT_SHORT}`;
110
+ export const planSwitchRequestedPayloadSchema = z.object({
111
+ tier: z.string().min(1).max(50),
112
+ priceId: z.string().min(1).max(200),
113
+ requestedAtIso: z.iso.datetime(),
114
+ });
115
+ // =============================================================================
87
116
  // checkout-consent-recorded — consumer-protection consent
88
117
  // =============================================================================
89
118
  //
@@ -52,7 +52,7 @@ import { defineFeature, EXT_TENANT_DATA, } from "@cosmicdrift/kumiko-framework/e
52
52
  import { Temporal } from "@cosmicdrift/kumiko-types/temporal";
53
53
  import { registerConsumerProtection } from "./consumer-protection/register-consent.js";
54
54
  import { paymentEntity, subscriptionEntity } from "./entities.js";
55
- import { INVOICE_PAID_EVENT_QN, INVOICE_PAID_EVENT_SHORT, INVOICE_PAYMENT_FAILED_EVENT_QN, INVOICE_PAYMENT_FAILED_EVENT_SHORT, PAYMENT_AGGREGATE_TYPE, PAYMENT_RECEIVED_EVENT_QN, PAYMENT_RECEIVED_EVENT_SHORT, paymentEventPayloadSchema, SUBSCRIPTION_AGGREGATE_TYPE, SUBSCRIPTION_CANCELED_EVENT_QN, SUBSCRIPTION_CANCELED_EVENT_SHORT, SUBSCRIPTION_CREATED_EVENT_QN, SUBSCRIPTION_CREATED_EVENT_SHORT, SUBSCRIPTION_UPDATED_EVENT_QN, SUBSCRIPTION_UPDATED_EVENT_SHORT, subscriptionEventPayloadSchema, } from "./events.js";
55
+ import { CHECKOUT_OPENED_EVENT_SHORT, checkoutOpenedPayloadSchema, INVOICE_PAID_EVENT_QN, INVOICE_PAID_EVENT_SHORT, INVOICE_PAYMENT_FAILED_EVENT_QN, INVOICE_PAYMENT_FAILED_EVENT_SHORT, PAYMENT_AGGREGATE_TYPE, PAYMENT_RECEIVED_EVENT_QN, PAYMENT_RECEIVED_EVENT_SHORT, PLAN_SWITCH_REQUESTED_EVENT_SHORT, paymentEventPayloadSchema, planSwitchRequestedPayloadSchema, SUBSCRIPTION_AGGREGATE_TYPE, SUBSCRIPTION_CANCELED_EVENT_QN, SUBSCRIPTION_CANCELED_EVENT_SHORT, SUBSCRIPTION_CREATED_EVENT_QN, SUBSCRIPTION_CREATED_EVENT_SHORT, SUBSCRIPTION_UPDATED_EVENT_QN, SUBSCRIPTION_UPDATED_EVENT_SHORT, subscriptionEventPayloadSchema, } from "./events.js";
56
56
  import { createBillingPlansQuery } from "./handlers/billing-plans.query.js";
57
57
  import { createCheckoutSessionHandler } from "./handlers/create-checkout-session.write.js";
58
58
  import { createPortalSessionHandler } from "./handlers/create-portal-session.write.js";
@@ -60,12 +60,14 @@ import { listSubscriptionsQuery } from "./handlers/list-subscriptions.query.js";
60
60
  import { createPlanSwitchPreviewQuery } from "./handlers/plan-switch-preview.query.js";
61
61
  import { createProcessEventHandler } from "./handlers/process-event.write.js";
62
62
  import { processPaymentEventHandler } from "./handlers/process-payment-event.write.js";
63
+ import { recordCheckoutOpenedHandler } from "./handlers/record-checkout-opened.write.js";
63
64
  import { createStartPlanCheckoutHandler } from "./handlers/start-plan-checkout.write.js";
64
65
  import { createSwitchPlanHandler } from "./handlers/switch-plan.write.js";
65
66
  import { syncSubscriptionHandler } from "./handlers/sync-subscription.write.js";
66
67
  import { BILLING_FOUNDATION_I18N } from "./i18n.js";
67
68
  import { applyInvoicePaid, applyInvoicePaymentFailed, applyPaymentReceived, applySubscriptionCanceled, applySubscriptionCreated, applySubscriptionUpdated, paymentsProjectionTable, subscriptionsProjectionTable, } from "./projection.js";
68
69
  import { createBillingPlansScreen } from "./screens.js";
70
+ import { registerScrubRawPayloadHeadersJob } from "./scrub-raw-payload-headers.js";
69
71
  import { PAYMENT_TENANT_DESTROY_ARCHIVE_REASON, paymentTenantDestroyHook, SUBSCRIPTION_TENANT_DESTROY_ARCHIVE_REASON, subscriptionTenantDestroyHook, } from "./tenant-destroy-hook.js";
70
72
  import { validateOptions } from "./validate-options.js";
71
73
  import { BILLING_FOUNDATION_FEATURE, SUBSCRIPTION_PROVIDER_EXTENSION, SubscriptionFoundationHandlers, } from "./web/constants.js";
@@ -121,6 +123,10 @@ export function createBillingFoundationFeature(options = {}) {
121
123
  // state transition. piiFields: "none" for the same reason as the 5 above:
122
124
  // providerCustomerId is tenantOwned ciphertext, not plaintext personal data.
123
125
  r.defineEvent(PAYMENT_RECEIVED_EVENT_SHORT, paymentEventPayloadSchema, { piiFields: "none" });
126
+ // Checkout ledger: registered unconditionally, webhook acceptance depends on it.
127
+ r.defineEvent(CHECKOUT_OPENED_EVENT_SHORT, checkoutOpenedPayloadSchema, {
128
+ piiFields: "none",
129
+ });
124
130
  // Inline projection: materialized current state in `read_subscriptions`.
125
131
  // Apply runs in the same TX as ctx.events.unsafeAppend — read-your-own-
126
132
  // write without a dispatcher tick.
@@ -161,6 +167,7 @@ export function createBillingFoundationFeature(options = {}) {
161
167
  // - process-payment-event: programmatic entry-point from the webhook-
162
168
  // handler for one-off-payments; appends onto the payment-aggregate
163
169
  r.writeHandler(processPaymentEventHandler);
170
+ r.writeHandler(recordCheckoutOpenedHandler);
164
171
  // - sync-subscription: backfill entry-point for the sync-subscriptions
165
172
  // job below; pulls the live provider state and appends drift as a
166
173
  // subscription.updated event. Registered unconditionally (not
@@ -182,6 +189,9 @@ export function createBillingFoundationFeature(options = {}) {
182
189
  r.queryHandler(createBillingPlansQuery(widened, catalog));
183
190
  r.queryHandler(createPlanSwitchPreviewQuery(catalog));
184
191
  r.writeHandler(createStartPlanCheckoutHandler(widened, catalog));
192
+ r.defineEvent(PLAN_SWITCH_REQUESTED_EVENT_SHORT, planSwitchRequestedPayloadSchema, {
193
+ piiFields: "none",
194
+ });
185
195
  r.writeHandler(createSwitchPlanHandler(widened, catalog));
186
196
  r.screen(createBillingPlansScreen(catalog.viewRoles));
187
197
  }
@@ -206,6 +216,7 @@ export function createBillingFoundationFeature(options = {}) {
206
216
  ctx.obs.log.info(`[billing-foundation:sync-subscriptions] ${JSON.stringify(result.data)}`);
207
217
  },
208
218
  });
219
+ registerScrubRawPayloadHeadersJob(r);
209
220
  r.useExtension(EXT_TENANT_DATA, "subscription", {
210
221
  destroy: subscriptionTenantDestroyHook,
211
222
  escapeHatch: { reason: SUBSCRIPTION_TENANT_DESTROY_ARCHIVE_REASON },
@@ -3,7 +3,7 @@
3
3
  // when `createBillingFoundationFeature` gets a `catalog`.
4
4
  import * as z from "zod";
5
5
  import { filterOfferedProviders, listCatalogProviders, } from "../checkout-core.js";
6
- import { CONSENT_TEXTS, consentTextVersion, documentsAcknowledgementTextFor, legalLinksPerLocale, } from "../consumer-protection/consent-text.js";
6
+ import { CONSENT_TEXTS, consentTextVersion, documentsAcknowledgementTextFor, hasProviderRefundLink, legalLinksFor, } from "../consumer-protection/consent-text.js";
7
7
  import { buildProviderPlanViews, loadBillingPlansBase, toBillingPlansResult, } from "../plan-catalog.js";
8
8
  const billingPlansSchema = z.object({}).strict();
9
9
  export function createBillingPlansQuery(options, catalog) {
@@ -20,13 +20,7 @@ export function createBillingPlansQuery(options, catalog) {
20
20
  return result;
21
21
  return {
22
22
  ...result,
23
- consumerProtection: {
24
- consentTexts: {
25
- de: consentTextView(consumerProtection, "de"),
26
- en: consentTextView(consumerProtection, "en"),
27
- },
28
- legalLinks: legalLinksPerLocale(consumerProtection.legalLinks),
29
- },
23
+ consumerProtection: consumerProtectionView(consumerProtection, base.blockingSubscription ? base.subscriptionView?.providerName : undefined),
30
24
  };
31
25
  },
32
26
  };
@@ -45,25 +39,41 @@ async function resolveProviderPlans(ctx, options, catalog, base) {
45
39
  const firstViews = await buildProviderPlanViews(ctx, first?.plugin ?? null, catalog, base);
46
40
  const result = toBillingPlansResult(catalog, base, firstViews);
47
41
  const providerTexts = options.consumerProtection?.providerTexts;
48
- const hasNote = first !== null && providerTexts?.[first.name]?.checkoutNote !== undefined;
49
- if (offered.length <= 1 && !(offered.length === 1 && hasNote))
42
+ const hasProviderSpecifics = first !== null &&
43
+ (providerTexts?.[first.name]?.checkoutNote !== undefined ||
44
+ (options.consumerProtection !== undefined &&
45
+ hasProviderRefundLink(options.consumerProtection, first.name)));
46
+ if (offered.length <= 1 && !(offered.length === 1 && hasProviderSpecifics))
50
47
  return result;
51
- const providers = await Promise.all(offered.map((provider, index) => providerView(ctx, catalog, base, provider, providerTexts, index === 0 ? firstViews : null)));
48
+ const providers = await Promise.all(offered.map((provider, index) => providerView(ctx, catalog, base, provider, options.consumerProtection, index === 0 ? firstViews : null)));
52
49
  return { ...result, providers };
53
50
  }
54
- async function providerView(ctx, catalog, base, provider, providerTexts, known) {
51
+ async function providerView(ctx, catalog, base, provider, consumerProtection, known) {
55
52
  const views = known ?? (await buildProviderPlanViews(ctx, provider.plugin, catalog, base));
56
- const note = providerTexts?.[provider.name]?.checkoutNote;
53
+ const note = consumerProtection?.providerTexts?.[provider.name]?.checkoutNote;
54
+ const ownConsumerProtection = consumerProtection !== undefined && hasProviderRefundLink(consumerProtection, provider.name)
55
+ ? consumerProtectionView(consumerProtection, provider.name)
56
+ : undefined;
57
57
  return {
58
58
  name: provider.name,
59
59
  displayName: provider.plugin.displayName ?? provider.name,
60
60
  ...(note !== undefined && { note }),
61
+ ...(ownConsumerProtection !== undefined && { consumerProtection: ownConsumerProtection }),
61
62
  plans: views.plans,
62
63
  };
63
64
  }
64
- function consentTextView(consumerProtection, locale) {
65
+ function consumerProtectionView(consumerProtection, providerName) {
66
+ return {
67
+ consentTexts: {
68
+ de: consentTextView(consumerProtection, "de", providerName),
69
+ en: consentTextView(consumerProtection, "en", providerName),
70
+ },
71
+ legalLinks: legalLinksFor(consumerProtection, providerName),
72
+ };
73
+ }
74
+ function consentTextView(consumerProtection, locale, providerName) {
65
75
  const { earlyPerformance, withdrawalLoss } = CONSENT_TEXTS[locale];
66
- const documentsAcknowledgement = documentsAcknowledgementTextFor(consumerProtection, locale);
76
+ const documentsAcknowledgement = documentsAcknowledgementTextFor(consumerProtection, locale, providerName);
67
77
  return {
68
78
  earlyPerformance,
69
79
  withdrawalLoss,
@@ -23,7 +23,7 @@
23
23
  // hand-picked priceId.
24
24
  import { InternalError, UnprocessableError } from "@cosmicdrift/kumiko-framework/errors";
25
25
  import * as z from "zod";
26
- import { assertCheckoutAllowed, openCheckout, startProviderCheckout, } from "../checkout-core.js";
26
+ import { assertCheckoutAllowed, CHECKOUT_START_RATE_LIMIT, openCheckout, startProviderCheckout, } from "../checkout-core.js";
27
27
  import { assertValidOrderItem, consentCheckoutFields, consentPayloadSchema, prepareConsent, recordConsent, } from "../consumer-protection/consent-gate.js";
28
28
  import { withOwnProviderCustomer } from "../one-off-customer.js";
29
29
  const createCheckoutSessionSchema = z.object({
@@ -56,6 +56,7 @@ export function createCheckoutSessionHandler(options) {
56
56
  // Tenant-Admin-only — the tenant must deliberately configure its own
57
57
  // subscription. SystemAdmin as a fallback for operator-initiated flows.
58
58
  access: { roles: ["TenantAdmin", "SystemAdmin"] },
59
+ rateLimit: CHECKOUT_START_RATE_LIMIT,
59
60
  handler: async (event, ctx) => {
60
61
  // @cast-boundary engine-payload — dispatcher-zod-validated payload
61
62
  const payload = event.payload;
@@ -88,7 +89,7 @@ export function createCheckoutSessionHandler(options) {
88
89
  ? await consumerProtection.oneOffItemLabel?.(ctx, payload.priceId)
89
90
  : undefined;
90
91
  assertValidOrderItem(orderItem, payload.priceId);
91
- const consent = await prepareConsent(ctx, consumerProtection, payload.consent, mode);
92
+ const consent = await prepareConsent(ctx, consumerProtection, payload.consent, mode, payload.providerName);
92
93
  const result = await startProviderCheckout(ctx, plugin, {
93
94
  ...checkoutInput,
94
95
  ...consentCheckoutFields(consent),
@@ -24,7 +24,7 @@ export declare const processEventSchema: z.ZodObject<{
24
24
  currentPeriodEndIso: z.ZodString;
25
25
  cancelAtIso: z.ZodOptional<z.ZodNullable<z.ZodString>>;
26
26
  providerEventAtIso: z.ZodOptional<z.ZodISODateTime>;
27
- consentId: z.ZodOptional<z.ZodString>;
27
+ providerCheckoutId: z.ZodOptional<z.ZodString>;
28
28
  }, z.core.$strip>;
29
29
  export type ProcessEventPayload = z.infer<typeof processEventSchema>;
30
30
  export declare function isLateStateEvent(storedEvents: readonly {
@@ -33,10 +33,12 @@ export declare function isLateStateEvent(storedEvents: readonly {
33
33
  readonly headers?: Record<string, unknown>;
34
34
  };
35
35
  }[], payload: ProcessEventPayload): boolean;
36
+ type SubscriptionStreamEvent = Awaited<ReturnType<HandlerContext["events"]["load"]>>[number];
36
37
  export declare function clampProviderEventAt(payload: ProcessEventPayload, now: Temporal.Instant): ProcessEventPayload;
37
- export declare function appendSubscriptionEvent(ctx: HandlerContext, tenantId: string, rawPayload: ProcessEventPayload, now?: Temporal.Instant): Promise<{
38
+ export declare function appendSubscriptionEvent(ctx: HandlerContext, tenantId: string, rawPayload: ProcessEventPayload, now?: Temporal.Instant, consentId?: string, lockedStream?: readonly SubscriptionStreamEvent[]): Promise<{
38
39
  readonly duplicate: boolean;
39
40
  readonly stale?: true;
40
41
  readonly subscriptionAggregateId: string;
41
42
  }>;
42
43
  export declare function createProcessEventHandler(now: () => Temporal.Instant): WriteHandlerDef;
44
+ export {};
@@ -7,17 +7,22 @@
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
  import { configuredPiiSubjectKms, encryptPiiFieldValues, } from "@cosmicdrift/kumiko-framework/crypto";
15
18
  import { Temporal } from "@cosmicdrift/kumiko-types/temporal";
16
19
  import { propertyOf } from "@cosmicdrift/kumiko-types/type-guards";
17
20
  import * as z from "zod";
18
21
  import { subscriptionAggregateId } from "../aggregate-id.js";
22
+ import { findProviderPlugin } from "../checkout-core.js";
23
+ import { findCheckoutOpened, IgnoredEventReasons, } from "../checkout-ledger.js";
19
24
  import { SUBSCRIPTION_PII_FIELDS, subscriptionEntity } from "../entities.js";
20
- import { INVOICE_PAID_EVENT_QN, INVOICE_PAYMENT_FAILED_EVENT_QN, SUBSCRIPTION_AGGREGATE_TYPE, SUBSCRIPTION_CANCELED_EVENT_QN, SUBSCRIPTION_CREATED_EVENT_QN, SUBSCRIPTION_UPDATED_EVENT_QN, } from "../events.js";
25
+ import { CHECKOUT_CONSENT_RECORDED_EVENT_QN, checkoutConsentRecordedPayloadSchema, INVOICE_PAID_EVENT_QN, INVOICE_PAYMENT_FAILED_EVENT_QN, PROVIDER_ID_MAX_CHARS, SUBSCRIPTION_AGGREGATE_TYPE, SUBSCRIPTION_CANCELED_EVENT_QN, SUBSCRIPTION_CREATED_EVENT_QN, SUBSCRIPTION_UPDATED_EVENT_QN, } from "../events.js";
21
26
  import { getSubscriptionForTenant } from "../get-subscription-for-tenant.js";
22
27
  import { hasSeenProviderEvent } from "../provider-event-seen.js";
23
28
  import { BILLING_SUBSCRIPTION_LOCK_NAMESPACE, isSubscriptionBlockingCheckout, isSwitchableSubscriptionStatus, SubscriptionEventTypes, SubscriptionStatuses, } from "../web/constants.js";
@@ -44,14 +49,14 @@ export const processEventSchema = z.object({
44
49
  providerEventId: z.string().min(1).max(200),
45
50
  providerName: z.string().min(1).max(50),
46
51
  type: eventTypeSchema,
47
- providerCustomerId: z.string().min(1).max(200),
48
- providerSubscriptionId: z.string().min(1).max(200),
52
+ providerCustomerId: z.string().min(1).max(PROVIDER_ID_MAX_CHARS),
53
+ providerSubscriptionId: z.string().min(1).max(PROVIDER_ID_MAX_CHARS),
49
54
  status: statusSchema,
50
55
  tier: z.string().min(1).max(50),
51
56
  currentPeriodEndIso: z.string().min(1),
52
57
  cancelAtIso: z.string().min(1).nullable().optional(),
53
58
  providerEventAtIso: z.iso.datetime().optional(),
54
- consentId: z.string().min(1).max(100).optional(),
59
+ providerCheckoutId: z.string().min(1).max(200).optional(),
55
60
  });
56
61
  // Map normalized SubscriptionEventType → fully-qualified ES event-name.
57
62
  const NORMALIZED_TO_ES_EVENT = {
@@ -61,6 +66,11 @@ const NORMALIZED_TO_ES_EVENT = {
61
66
  [SubscriptionEventTypes.invoicePaid]: INVOICE_PAID_EVENT_QN,
62
67
  [SubscriptionEventTypes.invoicePaymentFailed]: INVOICE_PAYMENT_FAILED_EVENT_QN,
63
68
  };
69
+ const STATE_EVENT_QNS = new Set([
70
+ SUBSCRIPTION_CREATED_EVENT_QN,
71
+ SUBSCRIPTION_UPDATED_EVENT_QN,
72
+ SUBSCRIPTION_CANCELED_EVENT_QN,
73
+ ]);
64
74
  const STATE_EVENT_TYPES = new Set([
65
75
  SubscriptionEventTypes.created,
66
76
  SubscriptionEventTypes.updated,
@@ -93,12 +103,10 @@ export function isLateStateEvent(storedEvents, payload) {
93
103
  }
94
104
  });
95
105
  }
96
- // =============================================================================
97
- // appendSubscriptionEvent — the append-body, shared by processEventHandler
98
- // (webhook path) and sync-subscription.write.ts (backfill path). Both call
99
- // this with the same normalized payload shape; the difference is only in
100
- // who constructs `payload` and what `providerEventId` they use.
101
- // =============================================================================
106
+ async function lockAndLoadSubscriptionStream(ctx, aggId) {
107
+ await ctx.db.advisoryXactLock(BILLING_SUBSCRIPTION_LOCK_NAMESPACE, aggId);
108
+ return ctx.events.load(aggId);
109
+ }
102
110
  // A provider timestamp far in the future would make every later, genuine event look late.
103
111
  const PROVIDER_EVENT_CLOCK_SKEW_SECONDS = 300;
104
112
  export function clampProviderEventAt(payload, now) {
@@ -109,13 +117,12 @@ export function clampProviderEventAt(payload, now) {
109
117
  ? { ...payload, providerEventAtIso: ceiling.toString() }
110
118
  : payload;
111
119
  }
112
- export async function appendSubscriptionEvent(ctx, tenantId, rawPayload, now = Temporal.Now.instant()) {
120
+ export async function appendSubscriptionEvent(ctx, tenantId, rawPayload, now = Temporal.Now.instant(), consentId, lockedStream) {
113
121
  const aggId = subscriptionAggregateId(tenantId);
114
122
  const payload = clampProviderEventAt(rawPayload, now);
115
- // Serialises the read (idempotency + late check) with the append: the append re-reads the
116
- // stream version itself, so without the lock a concurrent delivery could slip in between and
117
- // the late check would have judged an outdated stream.
118
- await ctx.db.advisoryXactLock(BILLING_SUBSCRIPTION_LOCK_NAMESPACE, aggId);
123
+ // The lock serialises the read (idempotency + late check) with the append: the append re-reads the
124
+ // stream version itself, so without it a concurrent delivery could slip in between and the late
125
+ // check would have judged an outdated stream. A caller that already holds it passes its stream.
119
126
  // ---------------------------------------------------------------
120
127
  // 1. Idempotency: load the subscription stream and check whether this
121
128
  // providerEventId was already seen. A provider retry storm (Stripe
@@ -127,7 +134,7 @@ export async function appendSubscriptionEvent(ctx, tenantId, rawPayload, now = T
127
134
  // streams, optimize via snapshot or a per-tenant dedup table as the
128
135
  // idempotency anchor (like cap-counter).
129
136
  // ---------------------------------------------------------------
130
- const existingEvents = await ctx.events.load(aggId);
137
+ const existingEvents = lockedStream ?? (await lockAndLoadSubscriptionStream(ctx, aggId));
131
138
  if (hasSeenProviderEvent(existingEvents, payload)) {
132
139
  return { duplicate: true, subscriptionAggregateId: aggId };
133
140
  }
@@ -183,7 +190,7 @@ export async function appendSubscriptionEvent(ctx, tenantId, rawPayload, now = T
183
190
  tier: payload.tier,
184
191
  currentPeriodEndIso: payload.currentPeriodEndIso,
185
192
  ...(payload.cancelAtIso !== undefined && { cancelAtIso: payload.cancelAtIso }),
186
- ...(payload.consentId !== undefined && { consentId: payload.consentId }),
193
+ ...(consentId !== undefined && { consentId }),
187
194
  ...(payload.providerEventAtIso !== undefined && {
188
195
  providerEventAtIso: payload.providerEventAtIso,
189
196
  }),
@@ -225,6 +232,93 @@ function isStaleSubscriptionEvent(current, payload, now) {
225
232
  isSwitchableSubscriptionStatus(payload.status);
226
233
  return !supersedesCurrent;
227
234
  }
235
+ function isBoundToLedgerEntry(ctx, entry, payload) {
236
+ const plugin = findProviderPlugin(ctx, payload.providerName)?.plugin;
237
+ return plugin?.priceToTier?.[entry.priceId] === payload.tier;
238
+ }
239
+ // A plan switch has no checkout of its own: its consent is the newest one recorded for the target
240
+ // tier, as long as no stored subscription event carries it yet. No window by state events: another
241
+ // state event (renewal, status change) may arrive between the consent and the tier change. The age
242
+ // limit keeps an abandoned consent from being attached to a portal switch months later.
243
+ const SWITCH_CONSENT_MAX_AGE_HOURS = 24;
244
+ function providerEventInstant(payload, now) {
245
+ const iso = clampProviderEventAt(payload, now).providerEventAtIso;
246
+ return iso === undefined ? now : Temporal.Instant.from(iso);
247
+ }
248
+ function pendingSwitchConsentId(storedEvents, payload, now) {
249
+ const referenceAt = providerEventInstant(payload, now);
250
+ const oldestAcceptedAt = referenceAt.subtract({ hours: SWITCH_CONSENT_MAX_AGE_HOURS });
251
+ const carried = new Set();
252
+ for (const stored of storedEvents) {
253
+ // skip: only subscription state events can carry a consent
254
+ if (!STATE_EVENT_QNS.has(stored.type))
255
+ continue;
256
+ const consentId = propertyOf(stored.payload, "consentId");
257
+ if (typeof consentId === "string")
258
+ carried.add(consentId);
259
+ }
260
+ for (let index = storedEvents.length - 1; index >= 0; index--) {
261
+ const stored = storedEvents[index];
262
+ if (stored?.type !== CHECKOUT_CONSENT_RECORDED_EVENT_QN)
263
+ continue;
264
+ if (Temporal.Instant.compare(stored.createdAt, oldestAcceptedAt) < 0)
265
+ continue;
266
+ const parsed = checkoutConsentRecordedPayloadSchema.safeParse(stored.payload);
267
+ if (!parsed.success)
268
+ continue;
269
+ const consent = parsed.data;
270
+ if (consent.mode === "subscription" &&
271
+ consent.tier === payload.tier &&
272
+ (consent.providerName === undefined || consent.providerName === payload.providerName) &&
273
+ !carried.has(consent.consentId)) {
274
+ return consent.consentId;
275
+ }
276
+ }
277
+ return undefined;
278
+ }
279
+ // A `created` that never comes (subscription from before the ledger, foreign custom_data, deleted
280
+ // subscription) would otherwise answer 503 until the provider gives up, and Stripe disables an
281
+ // endpoint that keeps failing. Only a young event may still be overtaken by its `created`.
282
+ // A provider that sends no event time (mollie) cannot be aged and keeps retrying.
283
+ const MISSING_SUBSCRIPTION_RETRY_WINDOW_MINUTES = 60;
284
+ function isWithinMissingSubscriptionRetryWindow(payload, now) {
285
+ if (payload.providerEventAtIso === undefined)
286
+ return true;
287
+ const oldestRetriedAt = now.subtract({ minutes: MISSING_SUBSCRIPTION_RETRY_WINDOW_MINUTES });
288
+ return Temporal.Instant.compare(providerEventInstant(payload, now), oldestRetriedAt) >= 0;
289
+ }
290
+ function admitProviderEvent(ctx, storedEvents, current, payload, now) {
291
+ const entry = payload.providerCheckoutId === undefined
292
+ ? undefined
293
+ : findCheckoutOpened(storedEvents, {
294
+ providerName: payload.providerName,
295
+ providerCheckoutId: payload.providerCheckoutId,
296
+ mode: "subscription",
297
+ });
298
+ if (entry !== undefined && isBoundToLedgerEntry(ctx, entry, payload)) {
299
+ return { admitted: true, ...(entry.consentId !== undefined && { consentId: entry.consentId }) };
300
+ }
301
+ if (payload.type === SubscriptionEventTypes.created) {
302
+ return { admitted: false, reason: IgnoredEventReasons.checkoutNotInLedger };
303
+ }
304
+ // The provider does not guarantee order: an update that beats the `created` of its
305
+ // subscription must be redelivered, not dropped.
306
+ if (current === null) {
307
+ return {
308
+ admitted: false,
309
+ reason: IgnoredEventReasons.subscriptionNotYetCreated,
310
+ ...(isWithinMissingSubscriptionRetryWindow(payload, now) && { retry: true }),
311
+ };
312
+ }
313
+ const isCurrentSubscription = current.providerName === payload.providerName &&
314
+ current.providerSubscriptionId === payload.providerSubscriptionId;
315
+ if (!isCurrentSubscription)
316
+ return { admitted: false, reason: IgnoredEventReasons.foreignSubscription };
317
+ const switchConsentId = payload.type === SubscriptionEventTypes.updated && current.tier !== payload.tier
318
+ ? pendingSwitchConsentId(storedEvents, payload, now)
319
+ : undefined;
320
+ return { admitted: true, ...(switchConsentId !== undefined && { consentId: switchConsentId }) };
321
+ }
228
322
  export function createProcessEventHandler(now) {
229
323
  return {
230
324
  name: "process-event",
@@ -234,19 +328,32 @@ export function createProcessEventHandler(now) {
234
328
  handler: async (event, ctx) => {
235
329
  // @cast-boundary engine-payload — dispatcher-zod-validated payload
236
330
  const payload = event.payload;
331
+ const aggId = subscriptionAggregateId(event.user.tenantId);
332
+ // One locked load serves admission and the append; the stream grows with every opened checkout.
333
+ // The lock comes first so the stream and `current` are both read under it.
334
+ const stream = await lockAndLoadSubscriptionStream(ctx, aggId);
237
335
  const current = await getSubscriptionForTenant(ctx, event.user.tenantId);
238
- if (isStaleSubscriptionEvent(current, payload, now())) {
239
- ctx.obs.log?.warn(`[billing-foundation:process-event] dropped stale ${payload.type} ${payload.providerEventId}: tenant already tracks another subscription`);
336
+ const admission = admitProviderEvent(ctx, stream, current, payload, now());
337
+ if (!admission.admitted) {
338
+ ctx.obs.log?.warn(`[billing-foundation:process-event] ignored ${payload.type} ${payload.providerEventId} (${admission.reason}): provider ${payload.providerName}`);
240
339
  return {
241
340
  isSuccess: true,
242
341
  data: {
243
- duplicate: false,
244
- stale: true,
245
- subscriptionAggregateId: subscriptionAggregateId(event.user.tenantId),
342
+ ignored: true,
343
+ reason: admission.reason,
344
+ ...(admission.retry === true && { retry: true }),
345
+ subscriptionAggregateId: aggId,
246
346
  },
247
347
  };
248
348
  }
249
- const result = await appendSubscriptionEvent(ctx, event.user.tenantId, payload, now());
349
+ if (isStaleSubscriptionEvent(current, payload, now())) {
350
+ ctx.obs.log?.warn(`[billing-foundation:process-event] dropped stale ${payload.type} ${payload.providerEventId}: tenant already tracks another subscription`);
351
+ return {
352
+ isSuccess: true,
353
+ data: { duplicate: false, stale: true, subscriptionAggregateId: aggId },
354
+ };
355
+ }
356
+ const result = await appendSubscriptionEvent(ctx, event.user.tenantId, payload, now(), admission.consentId, stream);
250
357
  return { isSuccess: true, data: result };
251
358
  },
252
359
  };
@@ -3,10 +3,9 @@ import * as z from "zod";
3
3
  export declare const processPaymentEventSchema: z.ZodObject<{
4
4
  providerEventId: z.ZodString;
5
5
  providerName: z.ZodString;
6
- providerCheckoutId: z.ZodOptional<z.ZodString>;
6
+ providerCheckoutId: z.ZodString;
7
7
  providerCustomerId: z.ZodString;
8
8
  priceId: z.ZodString;
9
9
  quantity: z.ZodOptional<z.ZodNumber>;
10
- consentId: z.ZodOptional<z.ZodString>;
11
10
  }, z.core.$strip>;
12
11
  export declare const processPaymentEventHandler: WriteHandlerDef;
@@ -6,23 +6,25 @@
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
  import { configuredPiiSubjectKms, encryptPiiFieldValues, } from "@cosmicdrift/kumiko-framework/crypto";
13
15
  import * as z from "zod";
14
16
  import { paymentAggregateId } from "../aggregate-id.js";
17
+ import { findCheckoutOpened, IgnoredEventReasons } from "../checkout-ledger.js";
15
18
  import { PAYMENT_PII_FIELDS, paymentEntity } from "../entities.js";
16
- import { PAYMENT_AGGREGATE_TYPE, PAYMENT_RECEIVED_EVENT_QN, } from "../events.js";
19
+ import { PAYMENT_AGGREGATE_TYPE, PAYMENT_RECEIVED_EVENT_QN, PROVIDER_ID_MAX_CHARS, } from "../events.js";
17
20
  import { hasSeenProviderEvent } from "../provider-event-seen.js";
18
21
  export const processPaymentEventSchema = z.object({
19
22
  providerEventId: z.string().min(1).max(200),
20
23
  providerName: z.string().min(1).max(50),
21
- providerCheckoutId: z.string().min(1).max(200).optional(),
22
- providerCustomerId: z.string().min(1).max(200),
24
+ providerCheckoutId: z.string().min(1).max(200),
25
+ providerCustomerId: z.string().min(1).max(PROVIDER_ID_MAX_CHARS),
23
26
  priceId: z.string().min(1).max(200),
24
27
  quantity: z.number().int().positive().optional(),
25
- consentId: z.string().min(1).max(100).optional(),
26
28
  });
27
29
  // SystemAdmin-only: this handler is called exclusively by the programmatic
28
30
  // webhook-handler (with an internal SystemUser), never directly by the
@@ -51,7 +53,27 @@ export const processPaymentEventHandler = {
51
53
  };
52
54
  }
53
55
  // ---------------------------------------------------------------
54
- // 2. Encrypt the provider-subject PII field before it touches storage
56
+ // 2. Ledger: only checkouts this server opened may produce a payment.
57
+ // ---------------------------------------------------------------
58
+ const entry = findCheckoutOpened(existingEvents, {
59
+ providerName: payload.providerName,
60
+ providerCheckoutId: payload.providerCheckoutId,
61
+ mode: "payment",
62
+ });
63
+ const rejection = entry === undefined
64
+ ? IgnoredEventReasons.checkoutNotInLedger
65
+ : entry.priceId !== payload.priceId
66
+ ? IgnoredEventReasons.priceMismatch
67
+ : undefined;
68
+ if (rejection !== undefined) {
69
+ ctx.obs.log?.warn(`[billing-foundation:process-payment-event] ignored ${payload.providerEventId} (${rejection}): checkout ${payload.providerCheckoutId} of provider ${payload.providerName}`);
70
+ return {
71
+ isSuccess: true,
72
+ data: { ignored: true, reason: rejection, paymentAggregateId: aggId },
73
+ };
74
+ }
75
+ // ---------------------------------------------------------------
76
+ // 3. Encrypt the provider-subject PII field before it touches storage
55
77
  // — same rationale as process-event.write.ts's step 3.
56
78
  // ---------------------------------------------------------------
57
79
  const piiKms = configuredPiiSubjectKms();
@@ -62,7 +84,7 @@ export const processPaymentEventHandler = {
62
84
  }, { tenantId, entityName: PAYMENT_AGGREGATE_TYPE })
63
85
  : { providerCustomerId: payload.providerCustomerId };
64
86
  // ---------------------------------------------------------------
65
- // 3. Append event on the payment-stream. Inline-projection
87
+ // 4. Append event on the payment-stream. Inline-projection
66
88
  // materializes a new read_payments-row in the same TX.
67
89
  // ---------------------------------------------------------------
68
90
  const eventPayload = {
@@ -70,14 +92,12 @@ export const processPaymentEventHandler = {
70
92
  providerCustomerId: encryptedFields.providerCustomerId,
71
93
  priceId: payload.priceId,
72
94
  ...(payload.quantity !== undefined && { quantity: payload.quantity }),
73
- ...(payload.consentId !== undefined && { consentId: payload.consentId }),
95
+ ...(entry?.consentId !== undefined && { consentId: entry.consentId }),
74
96
  };
75
97
  const headers = {
76
98
  providerEventId: payload.providerEventId,
77
99
  providerName: payload.providerName,
78
- ...(payload.providerCheckoutId !== undefined && {
79
- providerCheckoutId: payload.providerCheckoutId,
80
- }),
100
+ providerCheckoutId: payload.providerCheckoutId,
81
101
  };
82
102
  await ctx.events.unsafeAppend({
83
103
  aggregateId: aggId,
@@ -0,0 +1,2 @@
1
+ import type { WriteHandlerDef } from "@cosmicdrift/kumiko-framework/engine";
2
+ export declare const recordCheckoutOpenedHandler: WriteHandlerDef;
@@ -0,0 +1,22 @@
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
+ import { appendCheckoutOpened, findCheckoutOpened, ledgerAggregateId } from "../checkout-ledger.js";
5
+ import { checkoutOpenedPayloadSchema } from "../events.js";
6
+ export const recordCheckoutOpenedHandler = {
7
+ name: "record-checkout-opened",
8
+ agent: { expose: false },
9
+ schema: checkoutOpenedPayloadSchema,
10
+ access: { roles: ["SystemAdmin"] },
11
+ handler: async (event, ctx) => {
12
+ // @cast-boundary engine-payload — dispatcher-zod-validated payload
13
+ const entry = event.payload;
14
+ const tenantId = event.user.tenantId;
15
+ const existing = await ctx.events.load(ledgerAggregateId(tenantId, entry.mode));
16
+ if (findCheckoutOpened(existing, entry) !== undefined) {
17
+ return { isSuccess: true, data: { recorded: false } };
18
+ }
19
+ await appendCheckoutOpened(ctx, tenantId, entry);
20
+ return { isSuccess: true, data: { recorded: true } };
21
+ },
22
+ };