create-ailk 0.23.0 → 0.25.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (604) hide show
  1. package/README.md +68 -33
  2. package/component-catalog.json +3 -3
  3. package/component-catalog.md +3 -3
  4. package/dist/add-module.js +10 -3
  5. package/dist/add-route.d.ts +12 -1
  6. package/dist/add-route.js +38 -4
  7. package/dist/cli.js +12 -7
  8. package/dist/derive-architecture.d.ts +3 -4
  9. package/dist/derive-architecture.js +75 -22
  10. package/dist/lib/design-checks.d.ts +9 -4
  11. package/dist/lib/design-checks.js +13 -7
  12. package/dist/lib/extract-module-bundle.js +29 -2
  13. package/dist/lib/fetch-template-snapshot.d.ts +1 -1
  14. package/dist/lib/fetch-template-snapshot.js +7 -3
  15. package/dist/lib/import-graph.d.ts +1 -1
  16. package/dist/lib/import-graph.js +4 -4
  17. package/dist/lib/module-license-gate.d.ts +12 -1
  18. package/dist/lib/module-license-gate.js +34 -12
  19. package/dist/lib/scaffold-render-sweep.d.ts +33 -0
  20. package/dist/lib/scaffold-render-sweep.js +45 -0
  21. package/dist/module-architecture.d.ts +20 -3
  22. package/dist/module-architecture.js +122 -538
  23. package/dist/paid-sections.d.ts +25 -1
  24. package/dist/paid-sections.js +88 -3
  25. package/dist/surfaces.js +10 -2
  26. package/dist/sync-routes.d.ts +30 -4
  27. package/dist/sync-routes.js +271 -18
  28. package/dist/template-record.d.ts +14 -4
  29. package/dist/template-record.js +23 -5
  30. package/dist/topology.d.ts +16 -3
  31. package/dist/topology.js +31 -19
  32. package/dist/update.d.ts +10 -1
  33. package/dist/update.js +540 -16
  34. package/package.json +3 -3
  35. package/release-scope.json +1 -1
  36. package/templates/.claude/cloudparity-repo-hooks.json +5 -0
  37. package/templates/.claude/hooks/template-guard.sh +137 -0
  38. package/templates/.claude/rules/extending.md +106 -0
  39. package/templates/.claude/rules/loop-contract.md +2 -2
  40. package/templates/.claude/settings.json +11 -0
  41. package/templates/.env.example +9 -5
  42. package/templates/.github/workflows/ci.yml +7 -4
  43. package/templates/CLAUDE.md +15 -3
  44. package/templates/CONVENTIONS.md +8 -10
  45. package/templates/README.md +14 -13
  46. package/templates/apps/api/.env.example +9 -2
  47. package/templates/apps/api/CLAUDE.md +122 -82
  48. package/templates/apps/api/jest.config.cjs +15 -5
  49. package/templates/apps/api/package.json +16 -20
  50. package/templates/apps/api/src/__tests__/trusted-origins.server.test.ts +2 -2
  51. package/templates/apps/api/src/__tests__/vercel-handler.test.ts +4 -4
  52. package/templates/apps/api/src/index.ts +1 -1
  53. package/templates/apps/api/src/lib/__mocks__/prisma.ts +7 -4
  54. package/templates/apps/api/src/modules/commerce.ts +10 -0
  55. package/templates/apps/api/src/modules/content-write.ts +10 -0
  56. package/templates/apps/api/src/modules/multi-tenant.ts +10 -0
  57. package/templates/apps/api/src/modules/scheduling.ts +10 -0
  58. package/templates/apps/api/src/modules/signal-collectors.ts +10 -0
  59. package/templates/apps/api/src/modules/workspace.ts +10 -0
  60. package/templates/apps/api/src/server.ts +117 -1857
  61. package/templates/apps/api/vercel.json +2 -2
  62. package/templates/apps/mcp/CLAUDE.md +77 -24
  63. package/templates/apps/mcp/__tests__/app-entry.test.ts +4 -254
  64. package/templates/apps/mcp/__tests__/boot-file.test.ts +92 -0
  65. package/templates/apps/mcp/jest.config.cjs +6 -1
  66. package/templates/apps/mcp/package.json +5 -12
  67. package/templates/apps/mcp/src/app.ts +8 -7
  68. package/templates/apps/mcp/src/index.ts +6 -34
  69. package/templates/apps/mcp/src/lib/paid-tools.generated.ts +10 -0
  70. package/templates/apps/mcp/src/lib/topology.generated.ts +2 -2
  71. package/templates/apps/mcp/src/site.ts +12 -0
  72. package/templates/apps/web/.env.example +1 -1
  73. package/templates/apps/web/CLAUDE.md +21 -5
  74. package/templates/apps/web/app/.well-known/mcp.json/route.ts +9 -3
  75. package/templates/apps/web/app/[locale]/contact/__tests__/ConversationalIntakeWrapper.test.tsx +1 -1
  76. package/templates/apps/web/app/[locale]/contact/contact.actions.ts +14 -4
  77. package/templates/apps/web/app/[locale]/contact/intake-analytics.ts +1 -1
  78. package/templates/apps/web/app/[locale]/contact/intake-script.ts +1 -1
  79. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/magnet-page.test.tsx +22 -1
  80. package/templates/apps/web/app/[locale]/flows/[slug]/magnet-page.tsx +28 -7
  81. package/templates/apps/web/app/[locale]/pricing/__tests__/unconnected.test.tsx +43 -0
  82. package/templates/apps/web/app/[locale]/pricing/page.tsx +7 -3
  83. package/templates/apps/web/app/api/offerings/checkout/[lookupKey]/__tests__/route.test.ts +222 -0
  84. package/templates/apps/web/app/api/offerings/checkout/[lookupKey]/route.ts +10 -3
  85. package/templates/apps/web/app/api/revalidate/route.ts +3 -3
  86. package/templates/apps/web/auth.ts +2 -2
  87. package/templates/apps/web/jest.config.cjs +1 -0
  88. package/templates/apps/web/lib/__tests__/magnet-routes.test.ts +7 -0
  89. package/templates/apps/web/lib/auth-email.ts +1 -1
  90. package/templates/apps/web/lib/magnet-routes.ts +3 -1
  91. package/templates/apps/web/lib/newsletter.actions.ts +9 -6
  92. package/templates/apps/web/lib/relay.ts +2 -2
  93. package/templates/apps/web/lib/release-scope.ts +47 -0
  94. package/templates/apps/web/lib/server-api.ts +1 -1
  95. package/templates/apps/web/src/lib/commerce-claim.ts +1 -1
  96. package/templates/customizations.yaml +37 -0
  97. package/templates/database/prisma.config.ts +10 -14
  98. package/templates/database/seed-test.ts +2 -2
  99. package/templates/database/seed.ts +32 -5
  100. package/templates/package.json +12 -6
  101. package/templates/pnpm-workspace.yaml +0 -1
  102. package/templates/project.yaml +16 -8
  103. package/templates/tools/jest/reporters.cjs +65 -0
  104. package/templates/tools/lint-architecture.ts +757 -7
  105. package/templates/tsconfig.json +1 -2
  106. package/versions.json +48 -35
  107. package/templates/apps/api/src/__tests__/commerce-claim-registration.test.ts +0 -409
  108. package/templates/apps/api/src/__tests__/factories/agent-caller.ts +0 -102
  109. package/templates/apps/api/src/__tests__/factories/content-fixture.ts +0 -138
  110. package/templates/apps/api/src/__tests__/factories/in-memory-prisma.ts +0 -441
  111. package/templates/apps/api/src/__tests__/factories/index.ts +0 -70
  112. package/templates/apps/api/src/__tests__/factories/lead-fixture.ts +0 -82
  113. package/templates/apps/api/src/__tests__/leads-forwarded-rate-limit.test.ts +0 -135
  114. package/templates/apps/api/src/__tests__/services/enrichment-shim.test.ts +0 -126
  115. package/templates/apps/api/src/__tests__/stripe-boot.test.ts +0 -132
  116. package/templates/apps/api/src/__tests__/support/hub-sign-in-fake-db.ts +0 -362
  117. package/templates/apps/api/src/bin/__tests__/rate-limit-probe.test.ts +0 -184
  118. package/templates/apps/api/src/bin/abandon-sweep.ts +0 -42
  119. package/templates/apps/api/src/bin/rate-limit-probe.ts +0 -53
  120. package/templates/apps/api/src/bin/spokes.ts +0 -198
  121. package/templates/apps/api/src/bin/stripe-connections-rekey.ts +0 -45
  122. package/templates/apps/api/src/config/__tests__/hub-require-spoke-key.test.ts +0 -196
  123. package/templates/apps/api/src/config/__tests__/index.test.ts +0 -233
  124. package/templates/apps/api/src/config/__tests__/modules.test.ts +0 -76
  125. package/templates/apps/api/src/config/__tests__/stripe-connection-key.test.ts +0 -185
  126. package/templates/apps/api/src/config/__tests__/trusted-origins.test.ts +0 -238
  127. package/templates/apps/api/src/config/index.ts +0 -596
  128. package/templates/apps/api/src/config/modules.ts +0 -83
  129. package/templates/apps/api/src/lib/__tests__/agent-store.test.ts +0 -581
  130. package/templates/apps/api/src/lib/__tests__/auth-email-budget.test.ts +0 -143
  131. package/templates/apps/api/src/lib/__tests__/consent-ledger-double.ts +0 -237
  132. package/templates/apps/api/src/lib/__tests__/consent-store.test.ts +0 -353
  133. package/templates/apps/api/src/lib/__tests__/content-adapter.test.ts +0 -201
  134. package/templates/apps/api/src/lib/__tests__/deliverable-asset-store.test.ts +0 -224
  135. package/templates/apps/api/src/lib/__tests__/error-serializer.test.ts +0 -120
  136. package/templates/apps/api/src/lib/__tests__/errors.test.ts +0 -94
  137. package/templates/apps/api/src/lib/__tests__/file-fallback.test.ts +0 -144
  138. package/templates/apps/api/src/lib/__tests__/fixtures/HomePage/home.mdx +0 -8
  139. package/templates/apps/api/src/lib/__tests__/flow-completion-store.test.ts +0 -149
  140. package/templates/apps/api/src/lib/__tests__/flow-rename-race.db.test.ts +0 -116
  141. package/templates/apps/api/src/lib/__tests__/hub-sign-in-store.test.ts +0 -209
  142. package/templates/apps/api/src/lib/__tests__/lead-capture-store.test.ts +0 -257
  143. package/templates/apps/api/src/lib/__tests__/lead-delivery.test.ts +0 -96
  144. package/templates/apps/api/src/lib/__tests__/outbound-http.test.ts +0 -125
  145. package/templates/apps/api/src/lib/__tests__/prisma.test.ts +0 -165
  146. package/templates/apps/api/src/lib/__tests__/require-commerce-claim.test.ts +0 -317
  147. package/templates/apps/api/src/lib/__tests__/require-paid-tier.test.ts +0 -129
  148. package/templates/apps/api/src/lib/__tests__/site.test.ts +0 -292
  149. package/templates/apps/api/src/lib/__tests__/slice-load.test.ts +0 -89
  150. package/templates/apps/api/src/lib/__tests__/spoke-store.test.ts +0 -202
  151. package/templates/apps/api/src/lib/__tests__/stripe-admission.test.ts +0 -217
  152. package/templates/apps/api/src/lib/__tests__/stripe.test.ts +0 -82
  153. package/templates/apps/api/src/lib/agent-store.ts +0 -613
  154. package/templates/apps/api/src/lib/auth-email-budget.ts +0 -161
  155. package/templates/apps/api/src/lib/consent-store.ts +0 -363
  156. package/templates/apps/api/src/lib/content-adapter.ts +0 -112
  157. package/templates/apps/api/src/lib/deliverable-asset-store.ts +0 -96
  158. package/templates/apps/api/src/lib/error-serializer.ts +0 -164
  159. package/templates/apps/api/src/lib/errors.ts +0 -95
  160. package/templates/apps/api/src/lib/file-fallback.ts +0 -87
  161. package/templates/apps/api/src/lib/flow-completion-store.ts +0 -136
  162. package/templates/apps/api/src/lib/hub-sign-in-store.ts +0 -455
  163. package/templates/apps/api/src/lib/lead-capture-store.ts +0 -122
  164. package/templates/apps/api/src/lib/lead-delivery.ts +0 -52
  165. package/templates/apps/api/src/lib/license-key-store.ts +0 -45
  166. package/templates/apps/api/src/lib/locales.ts +0 -201
  167. package/templates/apps/api/src/lib/outbound-http.ts +0 -127
  168. package/templates/apps/api/src/lib/prisma.ts +0 -21
  169. package/templates/apps/api/src/lib/proposal-paid-store.ts +0 -66
  170. package/templates/apps/api/src/lib/rate-limit-probe.ts +0 -165
  171. package/templates/apps/api/src/lib/rate-limit-store.ts +0 -142
  172. package/templates/apps/api/src/lib/require-commerce-claim.ts +0 -250
  173. package/templates/apps/api/src/lib/require-paid-tier.ts +0 -53
  174. package/templates/apps/api/src/lib/site.ts +0 -254
  175. package/templates/apps/api/src/lib/slice-load.ts +0 -90
  176. package/templates/apps/api/src/lib/spoke-store.ts +0 -180
  177. package/templates/apps/api/src/lib/stripe.ts +0 -318
  178. package/templates/apps/api/src/lib/webhook-idempotency.ts +0 -156
  179. package/templates/apps/api/src/middleware/__tests__/adversarial/bearer-token-format.test.ts +0 -111
  180. package/templates/apps/api/src/middleware/__tests__/adversarial/cookie-or-bearer-precedence.test.ts +0 -172
  181. package/templates/apps/api/src/middleware/__tests__/adversarial/csrf-bearer-skip.test.ts +0 -119
  182. package/templates/apps/api/src/middleware/__tests__/adversarial/csrf-cookie-path.test.ts +0 -138
  183. package/templates/apps/api/src/middleware/__tests__/adversarial/csrf-trusted-origins.test.ts +0 -142
  184. package/templates/apps/api/src/middleware/__tests__/adversarial/session-fixation.test.ts +0 -155
  185. package/templates/apps/api/src/middleware/__tests__/adversarial/session-timeout.test.ts +0 -139
  186. package/templates/apps/api/src/middleware/__tests__/auth.bearer-path.test.ts +0 -562
  187. package/templates/apps/api/src/middleware/__tests__/auth.both-present-precedence.test.ts +0 -76
  188. package/templates/apps/api/src/middleware/__tests__/auth.cookie-path.test.ts +0 -220
  189. package/templates/apps/api/src/middleware/__tests__/auth.database-not-configured.test.ts +0 -97
  190. package/templates/apps/api/src/middleware/__tests__/auth.hub-session-path.test.ts +0 -557
  191. package/templates/apps/api/src/middleware/__tests__/auth.neither-present.test.ts +0 -72
  192. package/templates/apps/api/src/middleware/__tests__/auth.optional-cookie.test.ts +0 -140
  193. package/templates/apps/api/src/middleware/__tests__/default-tenant.test.ts +0 -721
  194. package/templates/apps/api/src/middleware/__tests__/rate-limit-cross-isolate.db.test.ts +0 -220
  195. package/templates/apps/api/src/middleware/__tests__/rate-limit-store.test.ts +0 -430
  196. package/templates/apps/api/src/middleware/__tests__/rate-limit.test.ts +0 -1409
  197. package/templates/apps/api/src/middleware/__tests__/write-budget.test.ts +0 -174
  198. package/templates/apps/api/src/middleware/auth.ts +0 -864
  199. package/templates/apps/api/src/middleware/default-tenant.ts +0 -166
  200. package/templates/apps/api/src/middleware/rate-limit.ts +0 -983
  201. package/templates/apps/api/src/openapi/__tests__/openapi.test.ts +0 -264
  202. package/templates/apps/api/src/openapi/__tests__/spec-identity.test.ts +0 -182
  203. package/templates/apps/api/src/openapi/index.ts +0 -18
  204. package/templates/apps/api/src/openapi/spec.ts +0 -1815
  205. package/templates/apps/api/src/openapi/surface-drift.ts +0 -195
  206. package/templates/apps/api/src/routes/aeo/__tests__/index.test.ts +0 -175
  207. package/templates/apps/api/src/routes/aeo/index.ts +0 -107
  208. package/templates/apps/api/src/routes/auth/__tests__/auth-tokens.functional.test.ts +0 -196
  209. package/templates/apps/api/src/routes/auth/__tests__/auth-user.functional.test.ts +0 -249
  210. package/templates/apps/api/src/routes/auth/__tests__/hub-sign-in.test.ts +0 -532
  211. package/templates/apps/api/src/routes/auth/__tests__/tokens.test.ts +0 -313
  212. package/templates/apps/api/src/routes/auth/__tests__/transactional-email.test.ts +0 -413
  213. package/templates/apps/api/src/routes/auth/__tests__/user.test.ts +0 -609
  214. package/templates/apps/api/src/routes/auth/hub-sign-in.ts +0 -242
  215. package/templates/apps/api/src/routes/auth/tokens.ts +0 -211
  216. package/templates/apps/api/src/routes/auth/transactional-email.ts +0 -301
  217. package/templates/apps/api/src/routes/auth/user.ts +0 -305
  218. package/templates/apps/api/src/routes/billing/plan-checkout.ts +0 -325
  219. package/templates/apps/api/src/routes/checkout/__tests__/live-key.test.ts +0 -178
  220. package/templates/apps/api/src/routes/checkout/__tests__/offerings-authorization.test.ts +0 -1300
  221. package/templates/apps/api/src/routes/checkout/__tests__/session.test.ts +0 -448
  222. package/templates/apps/api/src/routes/checkout/__tests__/sessions.test.ts +0 -1742
  223. package/templates/apps/api/src/routes/checkout/index.ts +0 -34
  224. package/templates/apps/api/src/routes/checkout/session.ts +0 -171
  225. package/templates/apps/api/src/routes/checkout/sessions.ts +0 -540
  226. package/templates/apps/api/src/routes/consent/__tests__/account.test.ts +0 -386
  227. package/templates/apps/api/src/routes/consent/__tests__/sign-up-rate-limit.test.ts +0 -160
  228. package/templates/apps/api/src/routes/consent/account.ts +0 -268
  229. package/templates/apps/api/src/routes/consent/cookie.ts +0 -90
  230. package/templates/apps/api/src/routes/consent/index.ts +0 -26
  231. package/templates/apps/api/src/routes/consent/unsubscribe.ts +0 -127
  232. package/templates/apps/api/src/routes/content/__tests__/get-page.test.ts +0 -853
  233. package/templates/apps/api/src/routes/content/__tests__/list-pages.test.ts +0 -230
  234. package/templates/apps/api/src/routes/content/__tests__/list-types.test.ts +0 -44
  235. package/templates/apps/api/src/routes/content/__tests__/locale.test.ts +0 -118
  236. package/templates/apps/api/src/routes/content/__tests__/offerings.test.ts +0 -731
  237. package/templates/apps/api/src/routes/content/__tests__/pricing.test.ts +0 -753
  238. package/templates/apps/api/src/routes/content/__tests__/rate-limit.test.ts +0 -51
  239. package/templates/apps/api/src/routes/content/__tests__/search.test.ts +0 -450
  240. package/templates/apps/api/src/routes/content/__tests__/shown-offerings.test.ts +0 -762
  241. package/templates/apps/api/src/routes/content/get-page.ts +0 -268
  242. package/templates/apps/api/src/routes/content/index.ts +0 -49
  243. package/templates/apps/api/src/routes/content/list-pages.ts +0 -95
  244. package/templates/apps/api/src/routes/content/list-types.ts +0 -19
  245. package/templates/apps/api/src/routes/content/offerings.ts +0 -184
  246. package/templates/apps/api/src/routes/content/pricing.ts +0 -176
  247. package/templates/apps/api/src/routes/content/rate-limit.ts +0 -22
  248. package/templates/apps/api/src/routes/content/search.ts +0 -129
  249. package/templates/apps/api/src/routes/content/shown-offerings.ts +0 -229
  250. package/templates/apps/api/src/routes/content/slug.ts +0 -9
  251. package/templates/apps/api/src/routes/leads/__tests__/capture.test.ts +0 -88
  252. package/templates/apps/api/src/routes/leads/__tests__/list.test.ts +0 -171
  253. package/templates/apps/api/src/routes/leads/__tests__/magnet-completion.test.ts +0 -515
  254. package/templates/apps/api/src/routes/leads/__tests__/spoke.test.ts +0 -392
  255. package/templates/apps/api/src/routes/leads/__tests__/track.test.ts +0 -165
  256. package/templates/apps/api/src/routes/leads/index.ts +0 -573
  257. package/templates/apps/api/src/routes/leads/list.ts +0 -104
  258. package/templates/apps/api/src/routes/project-listings/__tests__/configured-application.test.ts +0 -626
  259. package/templates/apps/api/src/routes/project-listings/__tests__/drafts.test.ts +0 -1268
  260. package/templates/apps/api/src/routes/project-listings/__tests__/founder-identity.test.ts +0 -847
  261. package/templates/apps/api/src/routes/project-listings/__tests__/me.test.ts +0 -480
  262. package/templates/apps/api/src/routes/project-listings/__tests__/public.test.ts +0 -465
  263. package/templates/apps/api/src/routes/project-listings/__tests__/resume-email.test.ts +0 -872
  264. package/templates/apps/api/src/routes/project-listings/__tests__/site-answers.test.ts +0 -1022
  265. package/templates/apps/api/src/routes/project-listings/__tests__/site-key.test.ts +0 -484
  266. package/templates/apps/api/src/routes/project-listings/__tests__/structured-address.test.ts +0 -535
  267. package/templates/apps/api/src/routes/project-listings/index.ts +0 -164
  268. package/templates/apps/api/src/routes/project-listings/me.ts +0 -87
  269. package/templates/apps/api/src/routes/project-listings/patch-copy.ts +0 -224
  270. package/templates/apps/api/src/routes/project-listings/patch-draft.ts +0 -102
  271. package/templates/apps/api/src/routes/project-listings/public.ts +0 -98
  272. package/templates/apps/api/src/routes/project-listings/respond.ts +0 -48
  273. package/templates/apps/api/src/routes/project-listings/resume-token.ts +0 -27
  274. package/templates/apps/api/src/routes/project-listings/start.ts +0 -140
  275. package/templates/apps/api/src/routes/project-listings/submit.ts +0 -130
  276. package/templates/apps/api/src/routes/project-listings/verify-email.ts +0 -150
  277. package/templates/apps/api/src/routes/requests/__tests__/confirm.test.ts +0 -686
  278. package/templates/apps/api/src/routes/requests/confirm.ts +0 -601
  279. package/templates/apps/api/src/routes/requests/index.ts +0 -54
  280. package/templates/apps/api/src/routes/test/auth/__tests__/session.test.ts +0 -306
  281. package/templates/apps/api/src/routes/test/auth/session.ts +0 -143
  282. package/templates/apps/api/src/routes/webhooks/README.md +0 -398
  283. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-checkout-consent.test.ts +0 -649
  284. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-dunning.test.ts +0 -749
  285. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-flow-checkout.test.ts +0 -448
  286. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-idempotency.test.ts +0 -264
  287. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-livemode-live.test.ts +0 -159
  288. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-livemode.test.ts +0 -158
  289. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-offerings.test.ts +0 -814
  290. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-org-billing.test.ts +0 -301
  291. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-proposal-paid.test.ts +0 -369
  292. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-rate-limit.test.ts +0 -215
  293. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-request-paid.test.ts +0 -301
  294. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-site-filter.test.ts +0 -808
  295. package/templates/apps/api/src/routes/webhooks/__tests__/stripe.test.ts +0 -1155
  296. package/templates/apps/api/src/routes/webhooks/index.ts +0 -141
  297. package/templates/apps/api/src/routes/webhooks/stripe-offerings.ts +0 -384
  298. package/templates/apps/api/src/routes/webhooks/stripe.ts +0 -2026
  299. package/templates/apps/api/src/services/__tests__/abandon-email.test.ts +0 -528
  300. package/templates/apps/api/src/services/__tests__/answer-distributions.test.ts +0 -132
  301. package/templates/apps/api/src/services/__tests__/audit-log.test.ts +0 -1028
  302. package/templates/apps/api/src/services/__tests__/checkout-plan.test.ts +0 -313
  303. package/templates/apps/api/src/services/__tests__/consent-ledger.test.ts +0 -503
  304. package/templates/apps/api/src/services/__tests__/consent-migration.test.ts +0 -65
  305. package/templates/apps/api/src/services/__tests__/consent.test.ts +0 -299
  306. package/templates/apps/api/src/services/__tests__/default-tenant.test.ts +0 -147
  307. package/templates/apps/api/src/services/__tests__/deliverable-fulfillment.test.ts +0 -867
  308. package/templates/apps/api/src/services/__tests__/deliverable-resend.test.ts +0 -379
  309. package/templates/apps/api/src/services/__tests__/dunning-policy.test.ts +0 -368
  310. package/templates/apps/api/src/services/__tests__/entitlements.test.ts +0 -142
  311. package/templates/apps/api/src/services/__tests__/hub-sign-in.test.ts +0 -854
  312. package/templates/apps/api/src/services/__tests__/keyless-workspace-predicate.test.ts +0 -234
  313. package/templates/apps/api/src/services/__tests__/lead-accept-user.test.ts +0 -251
  314. package/templates/apps/api/src/services/__tests__/lead-routing.test.ts +0 -2660
  315. package/templates/apps/api/src/services/__tests__/listing-config.test.ts +0 -166
  316. package/templates/apps/api/src/services/__tests__/magnet-completion.test.ts +0 -389
  317. package/templates/apps/api/src/services/__tests__/person.test.ts +0 -1176
  318. package/templates/apps/api/src/services/__tests__/plan-offerings.test.ts +0 -444
  319. package/templates/apps/api/src/services/__tests__/project-listings.fence.test.ts +0 -154
  320. package/templates/apps/api/src/services/__tests__/public-site-resolver.test.ts +0 -137
  321. package/templates/apps/api/src/services/__tests__/request-confirm.test.ts +0 -531
  322. package/templates/apps/api/src/services/__tests__/revalidation.test.ts +0 -372
  323. package/templates/apps/api/src/services/__tests__/slack-notify.test.ts +0 -348
  324. package/templates/apps/api/src/services/__tests__/spoke-resolution.test.ts +0 -660
  325. package/templates/apps/api/src/services/__tests__/usage-aggregation.test.ts +0 -941
  326. package/templates/apps/api/src/services/__tests__/usage-credits.test.ts +0 -588
  327. package/templates/apps/api/src/services/__tests__/verified-email.test.ts +0 -78
  328. package/templates/apps/api/src/services/abandon-email.ts +0 -313
  329. package/templates/apps/api/src/services/aeo-score.ts +0 -325
  330. package/templates/apps/api/src/services/answer-distributions.ts +0 -138
  331. package/templates/apps/api/src/services/audit-log.ts +0 -961
  332. package/templates/apps/api/src/services/checkout-buyer.ts +0 -168
  333. package/templates/apps/api/src/services/consent.ts +0 -834
  334. package/templates/apps/api/src/services/default-tenant.ts +0 -416
  335. package/templates/apps/api/src/services/deliverable-fulfillment.ts +0 -755
  336. package/templates/apps/api/src/services/dunning-policy.ts +0 -294
  337. package/templates/apps/api/src/services/enrichment-shim.ts +0 -53
  338. package/templates/apps/api/src/services/entitlements.ts +0 -338
  339. package/templates/apps/api/src/services/hub-sign-in.ts +0 -472
  340. package/templates/apps/api/src/services/lead-accept-user.ts +0 -126
  341. package/templates/apps/api/src/services/lead-promotion.ts +0 -160
  342. package/templates/apps/api/src/services/lead-routing.ts +0 -1372
  343. package/templates/apps/api/src/services/leads-inbox.ts +0 -312
  344. package/templates/apps/api/src/services/listing-config.ts +0 -178
  345. package/templates/apps/api/src/services/magnet-completion.ts +0 -242
  346. package/templates/apps/api/src/services/offerings/__tests__/catalog.test.ts +0 -295
  347. package/templates/apps/api/src/services/offerings/__tests__/checkout-session-record.test.ts +0 -268
  348. package/templates/apps/api/src/services/offerings/__tests__/connection.test.ts +0 -868
  349. package/templates/apps/api/src/services/offerings/__tests__/fixtures.ts +0 -416
  350. package/templates/apps/api/src/services/offerings/__tests__/org-products.test.ts +0 -396
  351. package/templates/apps/api/src/services/offerings/__tests__/readers.test.ts +0 -681
  352. package/templates/apps/api/src/services/offerings/__tests__/source.test.ts +0 -231
  353. package/templates/apps/api/src/services/offerings/catalog.ts +0 -308
  354. package/templates/apps/api/src/services/offerings/checkout-authorization.ts +0 -385
  355. package/templates/apps/api/src/services/offerings/checkout-session-record.ts +0 -192
  356. package/templates/apps/api/src/services/offerings/connection.ts +0 -1003
  357. package/templates/apps/api/src/services/offerings/index.ts +0 -614
  358. package/templates/apps/api/src/services/offerings/source.ts +0 -140
  359. package/templates/apps/api/src/services/offerings/store.ts +0 -150
  360. package/templates/apps/api/src/services/owner-workspaces.ts +0 -132
  361. package/templates/apps/api/src/services/person.ts +0 -1188
  362. package/templates/apps/api/src/services/plan-offerings.ts +0 -125
  363. package/templates/apps/api/src/services/project-listing-resume-email.ts +0 -326
  364. package/templates/apps/api/src/services/project-listings.ts +0 -2073
  365. package/templates/apps/api/src/services/public-site-resolver.ts +0 -396
  366. package/templates/apps/api/src/services/request-confirm.ts +0 -698
  367. package/templates/apps/api/src/services/revalidation.ts +0 -235
  368. package/templates/apps/api/src/services/slack-notify.ts +0 -291
  369. package/templates/apps/api/src/services/usage-aggregation.ts +0 -516
  370. package/templates/apps/api/src/services/usage-credits.ts +0 -340
  371. package/templates/apps/api/src/services/verified-email.ts +0 -71
  372. package/templates/apps/mcp/__tests__/abuse/daily-cap.test.ts +0 -52
  373. package/templates/apps/mcp/__tests__/abuse/email-validator.test.ts +0 -46
  374. package/templates/apps/mcp/__tests__/abuse/guard.test.ts +0 -198
  375. package/templates/apps/mcp/__tests__/abuse/honeypot.test.ts +0 -36
  376. package/templates/apps/mcp/__tests__/abuse/user-agent-deny.test.ts +0 -54
  377. package/templates/apps/mcp/__tests__/aeo-cli-parity.test.ts +0 -116
  378. package/templates/apps/mcp/__tests__/audit-single-page.test.ts +0 -299
  379. package/templates/apps/mcp/__tests__/boot.test.ts +0 -280
  380. package/templates/apps/mcp/__tests__/catalog-drift.test.ts +0 -359
  381. package/templates/apps/mcp/__tests__/config/modules.test.ts +0 -78
  382. package/templates/apps/mcp/__tests__/get_business_hours.test.ts +0 -82
  383. package/templates/apps/mcp/__tests__/get_faq.test.ts +0 -80
  384. package/templates/apps/mcp/__tests__/get_locations.test.ts +0 -65
  385. package/templates/apps/mcp/__tests__/get_offerings.test.ts +0 -557
  386. package/templates/apps/mcp/__tests__/get_pricing.test.ts +0 -524
  387. package/templates/apps/mcp/__tests__/get_site_info.test.ts +0 -81
  388. package/templates/apps/mcp/__tests__/http-transport.test.ts +0 -1151
  389. package/templates/apps/mcp/__tests__/index.test.ts +0 -195
  390. package/templates/apps/mcp/__tests__/lib/audit-single-page-readiness-scan.test.ts +0 -191
  391. package/templates/apps/mcp/__tests__/lib/commerce-claim.test.ts +0 -531
  392. package/templates/apps/mcp/__tests__/lib/content-adapter-parity.test.ts +0 -65
  393. package/templates/apps/mcp/__tests__/lib/content-adapter.test.ts +0 -187
  394. package/templates/apps/mcp/__tests__/lib/content-root.test.ts +0 -93
  395. package/templates/apps/mcp/__tests__/lib/errors.test.ts +0 -75
  396. package/templates/apps/mcp/__tests__/lib/fail-closed-tools.test.ts +0 -165
  397. package/templates/apps/mcp/__tests__/lib/public-workspace.test.ts +0 -124
  398. package/templates/apps/mcp/__tests__/list_pages.test.ts +0 -228
  399. package/templates/apps/mcp/__tests__/locale.test.ts +0 -135
  400. package/templates/apps/mcp/__tests__/module-exclusion.test.ts +0 -175
  401. package/templates/apps/mcp/__tests__/purchase-disabled.test.ts +0 -101
  402. package/templates/apps/mcp/__tests__/read_content.test.ts +0 -474
  403. package/templates/apps/mcp/__tests__/request_callback.test.ts +0 -225
  404. package/templates/apps/mcp/__tests__/search_content.test.ts +0 -256
  405. package/templates/apps/mcp/__tests__/server.test.ts +0 -388
  406. package/templates/apps/mcp/__tests__/start_purchase.test.ts +0 -448
  407. package/templates/apps/mcp/__tests__/submit_lead.test.ts +0 -307
  408. package/templates/apps/mcp/__tests__/subscribe_newsletter.test.ts +0 -223
  409. package/templates/apps/mcp/__tests__/tools/create_project.test.ts +0 -243
  410. package/templates/apps/mcp/__tests__/tools/purchase.test.ts +0 -451
  411. package/templates/apps/mcp/src/abuse/daily-cap.ts +0 -47
  412. package/templates/apps/mcp/src/abuse/email-validator.ts +0 -25
  413. package/templates/apps/mcp/src/abuse/honeypot.ts +0 -21
  414. package/templates/apps/mcp/src/abuse/index.ts +0 -342
  415. package/templates/apps/mcp/src/abuse/user-agent-deny.ts +0 -58
  416. package/templates/apps/mcp/src/boot.ts +0 -167
  417. package/templates/apps/mcp/src/config/modules.ts +0 -43
  418. package/templates/apps/mcp/src/http-transport.ts +0 -526
  419. package/templates/apps/mcp/src/lib/audit-single-page.ts +0 -308
  420. package/templates/apps/mcp/src/lib/commerce-claim.ts +0 -263
  421. package/templates/apps/mcp/src/lib/content-adapter.ts +0 -142
  422. package/templates/apps/mcp/src/lib/empty-content-adapter.ts +0 -139
  423. package/templates/apps/mcp/src/lib/errors.ts +0 -61
  424. package/templates/apps/mcp/src/lib/license-key-store.ts +0 -45
  425. package/templates/apps/mcp/src/lib/locales.ts +0 -171
  426. package/templates/apps/mcp/src/lib/prisma.ts +0 -39
  427. package/templates/apps/mcp/src/lib/public-workspace.ts +0 -133
  428. package/templates/apps/mcp/src/lib/resolve-locale.ts +0 -30
  429. package/templates/apps/mcp/src/lib/shown-offerings.ts +0 -105
  430. package/templates/apps/mcp/src/lib/stripe-tax-signal.ts +0 -59
  431. package/templates/apps/mcp/src/request-context.ts +0 -52
  432. package/templates/apps/mcp/src/server.ts +0 -343
  433. package/templates/apps/mcp/src/serverless-app.ts +0 -88
  434. package/templates/apps/mcp/src/tools/audit.ts +0 -127
  435. package/templates/apps/mcp/src/tools/capture_lead.ts +0 -64
  436. package/templates/apps/mcp/src/tools/create_project.ts +0 -134
  437. package/templates/apps/mcp/src/tools/get_business_hours.ts +0 -68
  438. package/templates/apps/mcp/src/tools/get_faq.ts +0 -71
  439. package/templates/apps/mcp/src/tools/get_locations.ts +0 -88
  440. package/templates/apps/mcp/src/tools/get_offerings.ts +0 -96
  441. package/templates/apps/mcp/src/tools/get_pricing.ts +0 -94
  442. package/templates/apps/mcp/src/tools/get_site_info.ts +0 -86
  443. package/templates/apps/mcp/src/tools/index.ts +0 -137
  444. package/templates/apps/mcp/src/tools/list_pages.ts +0 -74
  445. package/templates/apps/mcp/src/tools/person_notes.ts +0 -25
  446. package/templates/apps/mcp/src/tools/proposals.ts +0 -27
  447. package/templates/apps/mcp/src/tools/purchase.ts +0 -205
  448. package/templates/apps/mcp/src/tools/read_content.ts +0 -75
  449. package/templates/apps/mcp/src/tools/request_callback.ts +0 -59
  450. package/templates/apps/mcp/src/tools/search_content.ts +0 -67
  451. package/templates/apps/mcp/src/tools/subscribe_newsletter.ts +0 -57
  452. package/templates/apps/mcp/src/workspace-server.ts +0 -224
  453. package/templates/database/CHANGELOG.md +0 -961
  454. package/templates/database/LICENSE +0 -202
  455. package/templates/database/NOTICE +0 -2
  456. package/templates/database/README.md +0 -243
  457. package/templates/database/__tests__/agents.db.test.ts +0 -320
  458. package/templates/database/__tests__/appointment.db.test.ts +0 -106
  459. package/templates/database/__tests__/artifact-content-store.db.test.ts +0 -316
  460. package/templates/database/__tests__/composite-fence.db.test.ts +0 -206
  461. package/templates/database/__tests__/consent-ledger.db.test.ts +0 -345
  462. package/templates/database/__tests__/consent-source-checkout-migration.test.ts +0 -79
  463. package/templates/database/__tests__/fence-fan-out.db.test.ts +0 -715
  464. package/templates/database/__tests__/fixtures/appointment-create-probe.ts +0 -79
  465. package/templates/database/__tests__/fixtures/person-backfill.json +0 -264
  466. package/templates/database/__tests__/fixtures/person-contact-backfill.json +0 -182
  467. package/templates/database/__tests__/fixtures/project-listing-consent-probe.ts +0 -100
  468. package/templates/database/__tests__/flow-completion-migration.test.ts +0 -115
  469. package/templates/database/__tests__/flow-completion.db.test.ts +0 -136
  470. package/templates/database/__tests__/flow-workspace-key.db.test.ts +0 -263
  471. package/templates/database/__tests__/flows-listing-diagnostic.test.ts +0 -392
  472. package/templates/database/__tests__/flows-presets.test.ts +0 -173
  473. package/templates/database/__tests__/in-page-magnets-migration.test.ts +0 -161
  474. package/templates/database/__tests__/lead-idempotency-key.db.test.ts +0 -92
  475. package/templates/database/__tests__/member-area.db.test.ts +0 -257
  476. package/templates/database/__tests__/member-contract-migration.test.ts +0 -85
  477. package/templates/database/__tests__/member-contract.db.test.ts +0 -413
  478. package/templates/database/__tests__/offerings-checkout-session.db.test.ts +0 -270
  479. package/templates/database/__tests__/offerings-migration.test.ts +0 -197
  480. package/templates/database/__tests__/offerings-shown-price-ids-migration.test.ts +0 -86
  481. package/templates/database/__tests__/offerings.db.test.ts +0 -303
  482. package/templates/database/__tests__/outbound-message-action.db.test.ts +0 -80
  483. package/templates/database/__tests__/person-contact.db.test.ts +0 -563
  484. package/templates/database/__tests__/person-notes.db.test.ts +0 -249
  485. package/templates/database/__tests__/person.db.test.ts +0 -586
  486. package/templates/database/__tests__/piece-kind-migration.test.ts +0 -67
  487. package/templates/database/__tests__/piece-kind.db.test.ts +0 -208
  488. package/templates/database/__tests__/prefixed-ids.db.test.ts +0 -222
  489. package/templates/database/__tests__/project-listing-consent-at.db.test.ts +0 -111
  490. package/templates/database/__tests__/seed.test.ts +0 -240
  491. package/templates/database/__tests__/spoke-registry.db.test.ts +0 -191
  492. package/templates/database/__tests__/tenancy.test.ts +0 -141
  493. package/templates/database/__tests__/user-cascade.test.ts +0 -140
  494. package/templates/database/_gitignore +0 -8
  495. package/templates/database/auth/.gitkeep +0 -0
  496. package/templates/database/auth/schema.prisma +0 -641
  497. package/templates/database/config/.gitkeep +0 -0
  498. package/templates/database/config/schema.prisma +0 -441
  499. package/templates/database/content/.gitkeep +0 -0
  500. package/templates/database/content/schema.prisma +0 -339
  501. package/templates/database/eslint.config.mjs +0 -69
  502. package/templates/database/flows/listing-diagnostic.ts +0 -182
  503. package/templates/database/flows/presets.ts +0 -315
  504. package/templates/database/inbox/.gitkeep +0 -0
  505. package/templates/database/inbox/README.md +0 -3
  506. package/templates/database/inbox/__tests__/schema.test.ts +0 -44
  507. package/templates/database/inbox/schema.prisma +0 -1447
  508. package/templates/database/jest.config.cjs +0 -36
  509. package/templates/database/migrations/20260508000000_add_inbox_namespace/migration.sql +0 -328
  510. package/templates/database/migrations/20260513000000_better_auth_migration/migration.sql +0 -100
  511. package/templates/database/migrations/20260515000000_add_user_billing_fields/migration.sql +0 -28
  512. package/templates/database/migrations/20260516000000_add_user_tier_care_plan_seat/migration.sql +0 -25
  513. package/templates/database/migrations/20260518000000_add_telemetry_records/migration.sql +0 -42
  514. package/templates/database/migrations/20260525000000_theme_wiring/migration.sql +0 -67
  515. package/templates/database/migrations/20260710000000_retire_commercial_tier/migration.sql +0 -21
  516. package/templates/database/migrations/20260712215647_add_multi_tenant_tenancy/migration.sql +0 -201
  517. package/templates/database/migrations/20260713143320_reanchor_site_config_to_workspace/migration.sql +0 -67
  518. package/templates/database/migrations/20260713174000_add_audit_logs/migration.sql +0 -46
  519. package/templates/database/migrations/20260713190000_drop_telemetry_records/migration.sql +0 -25
  520. package/templates/database/migrations/20260713192000_add_uuidv7_function/migration.sql +0 -49
  521. package/templates/database/migrations/20260713192429_prefixed_uuid_entity_ids/migration.sql +0 -197
  522. package/templates/database/migrations/20260713200000_add_org_billing/migration.sql +0 -32
  523. package/templates/database/migrations/20260714000000_add_lead_promotion_fields/migration.sql +0 -22
  524. package/templates/database/migrations/20260714010000_add_usage_billing_content_models/migration.sql +0 -151
  525. package/templates/database/migrations/20260714020000_add_usage_billing_auth_config_models/migration.sql +0 -223
  526. package/templates/database/migrations/20260714030000_credit_balance_non_negative/migration.sql +0 -22
  527. package/templates/database/migrations/20260714030000_widen_usage_billing_report_aggregates/migration.sql +0 -32
  528. package/templates/database/migrations/20260810233516_add_flow_engine_models/migration.sql +0 -40
  529. package/templates/database/migrations/20260811020000_add_flow_session_abandon_email_columns/migration.sql +0 -4
  530. package/templates/database/migrations/20260811030000_add_flow_session_abandon_email_index/migration.sql +0 -2
  531. package/templates/database/migrations/20260811040000_add_flow_session_segment/migration.sql +0 -2
  532. package/templates/database/migrations/20260811050000_add_deliverable_models/migration.sql +0 -29
  533. package/templates/database/migrations/20260812000000_add_deliverable_grant_send_columns/migration.sql +0 -6
  534. package/templates/database/migrations/20260902222948_add_waitlist_experiment_models/migration.sql +0 -39
  535. package/templates/database/migrations/20260902224500_add_waitlist_id_format_checks/migration.sql +0 -24
  536. package/templates/database/migrations/20260903004112_add_flow_session_flags_aeo_score/migration.sql +0 -3
  537. package/templates/database/migrations/20260903010000_add_playbook_instance/migration.sql +0 -33
  538. package/templates/database/migrations/20260904000000_add_waitlist_followup_send/migration.sql +0 -30
  539. package/templates/database/migrations/20260905230000_add_flow_checkout/migration.sql +0 -47
  540. package/templates/database/migrations/20260906000000_add_flow_checkout_idempotency/migration.sql +0 -16
  541. package/templates/database/migrations/20260907120000_add_project_listing/migration.sql +0 -47
  542. package/templates/database/migrations/20260907130000_add_project_listing_slack_columns/migration.sql +0 -10
  543. package/templates/database/migrations/20260907180000_add_listing_csv_send/migration.sql +0 -26
  544. package/templates/database/migrations/20260909120000_project_listings_platform/migration.sql +0 -90
  545. package/templates/database/migrations/20260909180000_listing_draft_and_fields/migration.sql +0 -174
  546. package/templates/database/migrations/20260910120000_listing_public_site_key/migration.sql +0 -14
  547. package/templates/database/migrations/20260911120000_listing_copy_edit_audit/migration.sql +0 -25
  548. package/templates/database/migrations/20260911140000_listing_structured_address/migration.sql +0 -32
  549. package/templates/database/migrations/20260911180000_consent_grants/migration.sql +0 -71
  550. package/templates/database/migrations/20260911200000_listing_site_answers/migration.sql +0 -30
  551. package/templates/database/migrations/20260912120000_listing_owner_link/migration.sql +0 -49
  552. package/templates/database/migrations/20260914120000_listing_founder_identity/migration.sql +0 -123
  553. package/templates/database/migrations/20260915120000_project_listing_solution/migration.sql +0 -15
  554. package/templates/database/migrations/20260916120000_artifact_content_store/migration.sql +0 -158
  555. package/templates/database/migrations/20260917120000_callback_request_confirm/migration.sql +0 -40
  556. package/templates/database/migrations/20260918120000_add_appointment/migration.sql +0 -67
  557. package/templates/database/migrations/20260918120000_asset_metadata_columns/migration.sql +0 -70
  558. package/templates/database/migrations/20260919120000_flow_workspace_key/migration.sql +0 -181
  559. package/templates/database/migrations/20260919130000_flow_definition_admin_columns/migration.sql +0 -172
  560. package/templates/database/migrations/20260919130000_workspace_meetings/migration.sql +0 -41
  561. package/templates/database/migrations/20260919140000_inbox_workspace_key/migration.sql +0 -185
  562. package/templates/database/migrations/20260920120000_lead_handled_at/migration.sql +0 -70
  563. package/templates/database/migrations/20260920130000_lead_workspace_source_index/migration.sql +0 -57
  564. package/templates/database/migrations/20260921120000_deliverable_grant_workspace_key/migration.sql +0 -68
  565. package/templates/database/migrations/20260922120000_tenancy_fence/migration.sql +0 -1067
  566. package/templates/database/migrations/20260923120000_listing_capturing_magnet/migration.sql +0 -210
  567. package/templates/database/migrations/20261003120000_spoke_registry/migration.sql +0 -80
  568. package/templates/database/migrations/20261003130000_scheduling_connection/migration.sql +0 -49
  569. package/templates/database/migrations/20261005120000_agents/migration.sql +0 -84
  570. package/templates/database/migrations/20261008120000_user_last_workspace/migration.sql +0 -35
  571. package/templates/database/migrations/20261008130000_lead_idempotency_key/migration.sql +0 -20
  572. package/templates/database/migrations/20261009120000_agent_grants/migration.sql +0 -33
  573. package/templates/database/migrations/20261010120000_person/migration.sql +0 -106
  574. package/templates/database/migrations/20261010121000_person_backfill/migration.sql +0 -132
  575. package/templates/database/migrations/20261010130000_agent_grants_people_read/migration.sql +0 -20
  576. package/templates/database/migrations/20261011120000_member_area/migration.sql +0 -158
  577. package/templates/database/migrations/20261011130000_agent_grants_member_pieces_manage/migration.sql +0 -21
  578. package/templates/database/migrations/20261012120000_member_contract/migration.sql +0 -192
  579. package/templates/database/migrations/20261013120000_lead_spoke_checkout/migration.sql +0 -20
  580. package/templates/database/migrations/20261014120000_consent_ledger/migration.sql +0 -122
  581. package/templates/database/migrations/20261014120000_person_contact/migration.sql +0 -231
  582. package/templates/database/migrations/20261015120000_person_notes/migration.sql +0 -77
  583. package/templates/database/migrations/20261015120000_rate_limit_counters/migration.sql +0 -43
  584. package/templates/database/migrations/20261016120000_piece_kind/migration.sql +0 -95
  585. package/templates/database/migrations/20261017120000_outbound_message_action/migration.sql +0 -30
  586. package/templates/database/migrations/20261018120000_flow_completion/migration.sql +0 -52
  587. package/templates/database/migrations/20261019120000_consent_source_checkout/migration.sql +0 -27
  588. package/templates/database/migrations/20261020120000_offerings_data_model/migration.sql +0 -146
  589. package/templates/database/migrations/20261021120000_offerings_checkout_session/migration.sql +0 -77
  590. package/templates/database/migrations/20261022120000_in_page_magnets/migration.sql +0 -45
  591. package/templates/database/migrations/20261023120000_offerings_shown_price_ids/migration.sql +0 -47
  592. package/templates/database/migrations/20261024120000_organization_plan_checkout_session/migration.sql +0 -16
  593. package/templates/database/migrations/migration_lock.toml +0 -3
  594. package/templates/database/ops/.gitkeep +0 -0
  595. package/templates/database/ops/schema.prisma +0 -43
  596. package/templates/database/package.json +0 -89
  597. package/templates/database/schema.prisma +0 -71
  598. package/templates/database/scripts/db-generate-locked.sh +0 -80
  599. package/templates/database/scripts/person-backfill.sql +0 -132
  600. package/templates/database/tenancy.ts +0 -183
  601. package/templates/database/tsconfig.build.json +0 -16
  602. package/templates/database/tsconfig.flows.json +0 -15
  603. package/templates/database/tsconfig.json +0 -16
  604. package/templates/database/tsconfig.tenancy.json +0 -14
@@ -1,2026 +0,0 @@
1
- /**
2
- * POST /api/webhooks/stripe
3
- *
4
- * Receives Stripe webhook events. Verifies the signature on the raw
5
- * request body using the secret from STRIPE_WEBHOOK_SECRET. Dispatches
6
- * verified events through a `switch (event.type)` statement.
7
- *
8
- * Error mapping (in priority order):
9
- * 1. STRIPE_WEBHOOK_SECRET missing → 503 webhook-not-configured
10
- * 2. Body is not a Buffer (parser miss) → 400 invalid-request
11
- * 3. Stripe-Signature header missing → 400 signature-missing
12
- * 4. Signature verification fails → 400 signature-invalid
13
- *
14
- * Commerce claim (D-64, #5796): the receiver is a base-tree primitive, so it
15
- * registers on every build and gates on the JWT `commerce` claim at call time.
16
- * The signature is settled FIRST (D3), then the claim is read as a TRI-STATE:
17
- * - claimed → every mapping below is byte-for-byte what it was
18
- * - unclaimed → a SIGNED event is acked 200 and dropped with a `warn`
19
- * log line so Stripe stops retrying; an unsigned or
20
- * unverifiable body gets the module-disabled 404,
21
- * indistinguishable from a build without commerce
22
- * - undetermined → 503 + `Retry-After: 300`, so Stripe QUEUES and
23
- * redelivers. The read established no "no" (it threw, the
24
- * licence is revoked mid-window, or one is configured yet
25
- * no longer verifies), so this may be a live commerce site
26
- * whose buyer was already charged; dropping on such a read
27
- * loses the event permanently (security review 2026-09-16,
28
- * High, widened by the operator in round 2).
29
- * See README.md § Commerce claim.
30
- *
31
- * Successful dispatch always 200s — including unknown event types.
32
- * Telemetry failures are caught, logged, and do NOT change the response.
33
- *
34
- * Site filter (#7868):
35
- * The Stripe account is shared with spoke sites, so this endpoint receives
36
- * their Checkout sessions too. A `checkout.session.completed` or `.expired`
37
- * whose `metadata.site` is a non-empty string naming another site
38
- * (`isForeignSiteStamp`, lib/site.ts) takes no action: it logs
39
- * `outcome: "foreign_site"` and answers 200. An unstamped session is the
40
- * hub's own (roadmap D4) and is handled as before. The hub stamps its own
41
- * sessions through `siteStamp()`. See README.md § Site filter (#7868).
42
- * Since #8024 one gate before the switch does the same for every
43
- * `customer.*`, `customer.subscription.*` and `invoice.*` event, reading the
44
- * stamp from the Customer's or Subscription's own metadata — for an invoice,
45
- * its own metadata and then the subscription snapshot under
46
- * `parent.subscription_details` or (pre-`basil`) `subscription_details` —
47
- * and only when `data.object.object` is the family's own type.
48
- *
49
- * Billing upsert (customer.created / checkout.session.completed):
50
- * Billing-entity routing (org-scoped billing, #3601, spec D2): a checkout
51
- * carrying metadata.organizationId takes the Organization path (multi-tenant
52
- * module); absent → the User path (single-tenant).
53
- *
54
- * Organization path (metadata.organizationId present) — proof-based since
55
- * #9067 D13: the metadata names the target, the recorded session proves it.
56
- * 1. Typed composite match already pointing at this org → idempotent no-op
57
- * 2. A checkout.session.completed binds only when the Organization's
58
- * `planCheckoutSessionId` is this session's id and no customer is
59
- * bound yet (one guarded updateMany, which also clears the session)
60
- * 3. Anything else — an unrecorded session, a bound customer, any
61
- * customer.created — logs org_bind_unproven and writes nothing
62
- *
63
- * User path (no organizationId):
64
- * 1. Typed composite match: (billingProvider="stripe", billingCustomerId=customer)
65
- * 2. Verified user signal: metadata.ailk_user_id →
66
- * User.findUnique({ where: { id } }) → bind only when the row's
67
- * billingCustomerId is empty; otherwise log billing_identity_conflict
68
- * and write nothing (#6113). No signal → log billing_identity_unverified,
69
- * write nothing (#6852) — the payer-typed Checkout email never binds.
70
- * 3. Signal names no User → warn billing_identity_unknown_user; no row created
71
- *
72
- * Recommender purchase stamp (checkout.session.completed / .expired, #4838):
73
- * A session carrying metadata.flowCheckoutId (the FlowCheckout buyer row
74
- * #4841 opened it with) is stamped `completed` / `expired` by ONE guarded
75
- * `updateMany` on `{ id, status: "created" }` — the durable idempotency key
76
- * (D1): a replay, a restart between deliveries, or a late `expired` after a
77
- * `completed` all match zero rows and log `stale_or_unknown`. Runs BESIDE the
78
- * telemetry + billing tasks (D4), never instead of them; a charged/quoted
79
- * mismatch is logged, never reconciled by overwrite (D2). Always 200. A
80
- * `completed` session stamps only when `payment_status` is `"paid"` or
81
- * `"no_payment_required"` (a 100%-off promo code, #4862) — anything else
82
- * logs `outcome: "unpaid"` and leaves the row `created`.
83
- *
84
- * Proposal paid stamp (checkout.session.completed, #8516 D13):
85
- * A session carrying the server-written `metadata.ailk_proposal` and
86
- * `ailk_workspace` (the client's proposal Checkout,
87
- * `services/proposal-payments.ts`) stamps that proposal's `paid_at` and
88
- * `paid_session_id` once, through the base-tree boundary
89
- * `lib/proposal-paid-store.ts` (this file names no `piece` delegate), and
90
- * writes one `people.proposal.paid` audit row as the Stripe system actor
91
- * keyed by the event id: `succeeded` when stamped, `failed`
92
- * (`already_paid`) when a different session already paid it, none on a
93
- * same-session replay, a `warn` when no such proposal exists, and `failed`
94
- * (`not_paid`) with no stamp for a session that is not paid. A session
95
- * without both keys makes no query. Runs BESIDE the other stamps; never
96
- * throws; logs an 8-character prefix and the outcome only.
97
- *
98
- * Checkout Person (checkout.session.completed, #852 D6):
99
- * Chained after that stamp, `recordFlowCheckoutPerson` finds or creates the
100
- * Person of the checkout row THIS session completed (matched on its own
101
- * `stripeSessionId`), with `session.customer` as the customer id only on a
102
- * live-mode event. Logs an outcome kind only; never fails the 200.
103
- *
104
- * Checkout terms grant (checkout.session.completed, #8765 D14):
105
- * Chained after the Person step, `recordCheckoutTermsGrant` records the
106
- * buyer's acceptance of the session's terms box as one `checkout` row of
107
- * the consent ledger — only for a session whose `consent.terms_of_service`
108
- * is `accepted` and whose server-written `metadata.ailk_terms` names
109
- * `account_terms` at its current version (a Payment Link, invoice or older
110
- * session carries none), for the Person `checkoutBuyerPerson` resolves.
111
- * Logs `{ event: "checkout-consent", outcome, eventIdPrefix }` only; never
112
- * fails the 200.
113
- *
114
- * Dunning (invoice.payment_failed / customer.subscription.updated, #6034):
115
- * Records a per-subscriber lifecycle state in a `UserData` row behind a
116
- * reserved-key guard (routes/auth/user.ts). `invoice.payment_failed` arms
117
- * dunning (`status: "past_due"`) and never revokes; `customer.subscription
118
- * .updated` maps the narrowed status onto the same record, and `canceled`
119
- * revokes access only once a per-tenant grace period (SiteSetting-backed,
120
- * `services/dunning-policy.ts`) has lazily expired. See README.md
121
- * § Dunning for the full state machine.
122
- */
123
- import { track } from "@working-theory/analytics/server";
124
- import type { Prisma } from "@working-theory/database";
125
- import { isId } from "@working-theory/ids";
126
- import {
127
- ACCOUNT_TERMS_PURPOSE_ID,
128
- consentPurposeById,
129
- SITE_CONSENT_CONFIG_DEFAULTS,
130
- } from "@working-theory/validation";
131
- import type { FastifyReply, FastifyRequest } from "fastify";
132
-
133
- import { config } from "../../config/index.js";
134
- import { prisma } from "../../lib/prisma.js";
135
- import { stampProposalPaid as writeProposalPaid } from "../../lib/proposal-paid-store.js";
136
- import {
137
- resolveCommerceClaim,
138
- commerceDisabledResponse,
139
- LICENSE_UNDETERMINED_BODY,
140
- LICENSE_UNDETERMINED_RETRY_AFTER_SECONDS,
141
- LICENSE_UNDETERMINED_STATUS,
142
- } from "../../lib/require-commerce-claim.js";
143
- import {
144
- currentSiteId,
145
- isForeignSiteStamp,
146
- SITE_STAMP_KEY,
147
- } from "../../lib/site.js";
148
- import {
149
- stripeKeyMode,
150
- StripeWebhookSignatureError,
151
- toSubscriptionLifecycleStatus,
152
- verifyWebhookSignature,
153
- } from "../../lib/stripe.js";
154
- import { hasSeen, markSeen } from "../../lib/webhook-idempotency.js";
155
- import { recordWorkspaceAuditAction } from "../../services/audit-log.js";
156
- import { checkoutBuyerPerson } from "../../services/checkout-buyer.js";
157
- import { recordCheckoutConsent } from "../../services/consent.js";
158
- import { isUniqueViolation } from "../../services/default-tenant.js";
159
- import {
160
- DUNNING_MAX_SUBSCRIPTIONS,
161
- DUNNING_USER_DATA_KEY,
162
- dunningPolicyFor,
163
- type DunningEntry,
164
- type DunningRecord,
165
- } from "../../services/dunning-policy.js";
166
- import {
167
- resolveCheckoutPerson,
168
- type CheckoutPersonResult,
169
- } from "../../services/person.js";
170
-
171
- const TELEMETRY_TIMEOUT_MS = 2000;
172
- const DUNNING_WRITE_MAX_ATTEMPTS = 3;
173
-
174
- /**
175
- * Everything that must be true before an event is dispatched, evaluated as a
176
- * value rather than as an early `reply.send` — so the caller can settle the
177
- * signature BEFORE consulting the commerce claim (D3, #5796) without
178
- * duplicating any of the four rejections. The log lines ride along so a
179
- * held rejection still logs exactly what it logged before, and only when it
180
- * is the response actually sent.
181
- */
182
- type SettledSignature =
183
- | { ok: true; event: ReturnType<typeof verifyWebhookSignature> }
184
- | {
185
- ok: false;
186
- status: number;
187
- body: { error: string };
188
- log: (request: FastifyRequest) => void;
189
- };
190
-
191
- function settleSignature(request: FastifyRequest): SettledSignature {
192
- const secret = config.STRIPE_WEBHOOK_SECRET;
193
- if (!secret) {
194
- return {
195
- ok: false,
196
- status: 503,
197
- body: { error: "webhook-not-configured" },
198
- log: (req) =>
199
- req.log.warn("stripe webhook hit but STRIPE_WEBHOOK_SECRET is not set"),
200
- };
201
- }
202
-
203
- const rawBody = request.body;
204
- if (!Buffer.isBuffer(rawBody)) {
205
- return {
206
- ok: false,
207
- status: 400,
208
- body: { error: "invalid-request" },
209
- log: (req) =>
210
- req.log.error(
211
- "stripe webhook body is not a Buffer — content-type parser misconfigured",
212
- ),
213
- };
214
- }
215
-
216
- const signature = request.headers["stripe-signature"];
217
- if (typeof signature !== "string" || signature.length === 0) {
218
- return {
219
- ok: false,
220
- status: 400,
221
- body: { error: "signature-missing" },
222
- log: () => undefined,
223
- };
224
- }
225
-
226
- try {
227
- return {
228
- ok: true,
229
- event: verifyWebhookSignature(rawBody, signature, secret),
230
- };
231
- } catch (err) {
232
- if (err instanceof StripeWebhookSignatureError) {
233
- const reason = err.message;
234
- return {
235
- ok: false,
236
- status: 400,
237
- body: { error: "signature-invalid" },
238
- log: (req) =>
239
- req.log.warn(
240
- { reason },
241
- "stripe webhook signature verification failed",
242
- ),
243
- };
244
- }
245
- throw err;
246
- }
247
- }
248
-
249
- export const stripeWebhookHandler = async (
250
- request: FastifyRequest,
251
- reply: FastifyReply,
252
- ): Promise<void> => {
253
- // ── Signature first, claim second (D3, #5796) ────────────────────────────
254
- //
255
- // The four pre-dispatch rejections above are SETTLED before the licence is
256
- // consulted, so an unsigned or unverifiable body never decides anything on
257
- // the strength of the claim. Their replies are held rather than sent, so
258
- // the unclaimed branch below can answer the module-disabled 404 instead of
259
- // leaking a configured-but-off shape.
260
- const settled = settleSignature(request);
261
- const claim = await resolveCommerceClaim();
262
-
263
- if (claim === "undetermined") {
264
- // The licence read established no "no" — it threw, the licence is revoked
265
- // mid-window, or one IS configured yet no longer verifies. Any of those
266
- // may be a live commerce site whose buyer was already charged. Never drop
267
- // on a guess: 503 + `Retry-After` so Stripe QUEUES the event and
268
- // redelivers it once the read succeeds (security review 2026-09-16, High,
269
- // widened by the operator in round 2). Applies to a signed event and an
270
- // unsigned body alike; the unsigned one was going to be refused either way.
271
- request.log.warn(
272
- {
273
- outcome: "license_undetermined",
274
- signatureVerified: settled.ok,
275
- ...(settled.ok
276
- ? {
277
- eventType: settled.event.type,
278
- eventIdPrefix: settled.event.id.substring(0, 8),
279
- }
280
- : {}),
281
- },
282
- "stripe webhook held — commerce licence could not be read; asking Stripe to retry",
283
- );
284
- await reply
285
- .code(LICENSE_UNDETERMINED_STATUS)
286
- .header("Retry-After", String(LICENSE_UNDETERMINED_RETRY_AFTER_SECONDS))
287
- .send(LICENSE_UNDETERMINED_BODY);
288
- return;
289
- }
290
-
291
- if (claim === "unclaimed") {
292
- if (settled.ok) {
293
- // The licence was READ and positively does not carry `commerce`. Ack
294
- // 200 and DROP: a 4xx here would have Stripe retry this event for days
295
- // against a site that will never handle it. `warn`, not `info` — a
296
- // discarded Stripe event is never routine.
297
- request.log.warn(
298
- {
299
- eventType: settled.event.type,
300
- eventIdPrefix: settled.event.id.substring(0, 8),
301
- outcome: "dropped_no_commerce_claim",
302
- },
303
- "stripe webhook event dropped — deployment licence carries no commerce claim",
304
- );
305
- await reply.code(200).send({ received: true });
306
- return;
307
- }
308
- // Unsigned / unverifiable AND unclaimed: answer exactly as a build
309
- // without the commerce module did — the module-disabled 404.
310
- const err = commerceDisabledResponse();
311
- await reply.code(err.status).send(err.body);
312
- return;
313
- }
314
-
315
- if (!settled.ok) {
316
- settled.log(request);
317
- await reply.code(settled.status).send(settled.body);
318
- return;
319
- }
320
-
321
- const event = settled.event;
322
- const eventIdPrefix = event.id.substring(0, 8);
323
-
324
- // #8450 D10 (#6852 SEC-03) — an event whose livemode is not the key class
325
- // this process admitted is never one of its own: a live hub must not act on
326
- // a test-mode event anyone with the test key can forge, nor a test hub on a
327
- // live one. Dropped before the idempotency check and any write; 200 so
328
- // Stripe stops retrying, and NOT marked seen, so a corrected deployment
329
- // still accepts a redelivery.
330
- if ((event.livemode === true) !== (stripeKeyMode() === "live")) {
331
- request.log.warn(
332
- { eventType: event.type, eventIdPrefix, outcome: "livemode_mismatch" },
333
- "stripe webhook event dropped — livemode differs from the admitted key class",
334
- );
335
- await reply.code(200).send({ received: true });
336
- return;
337
- }
338
-
339
- // #8932 D9 (contract W8) — an Offerings-stamped event belongs to the
340
- // per-Organization endpoint, which must still be able to act on it, so it
341
- // is acked here BEFORE `markSeen` and nothing is written. Presence decides,
342
- // whatever the value; any other event takes the path below unchanged.
343
- if (
344
- offeringsStampSourcesOf(event).some((source) =>
345
- Object.hasOwn(source, OFFERINGS_STAMP_KEY),
346
- )
347
- ) {
348
- request.log.info(
349
- { eventType: event.type, eventIdPrefix, outcome: "offerings_path" },
350
- "stripe webhook event left to the per-Organization endpoint",
351
- );
352
- await reply.code(200).send({ received: true });
353
- return;
354
- }
355
-
356
- request.log.info(
357
- { eventType: event.type, eventIdPrefix },
358
- "stripe webhook event received",
359
- );
360
-
361
- // AILK-layer idempotency. Stripe guarantees at-least-once delivery and
362
- // dashboard "resend" replays a previously-delivered event verbatim. Skip
363
- // side effects on the second arrival; still 200 so Stripe stops retrying.
364
- if (hasSeen(event.id)) {
365
- request.log.info(
366
- { eventType: event.type, eventIdPrefix },
367
- "duplicate stripe webhook event — idempotent short-circuit",
368
- );
369
- await reply.code(200).send({ received: true });
370
- return;
371
- }
372
- markSeen(event.id);
373
-
374
- // #8024 — the billing families' site filter, after `markSeen` as #7868's
375
- // in-arm check is, so a foreign redelivery is a duplicate. One gate rather
376
- // than a check per arm: the `default` arm's types are filtered too.
377
- const foreignStamp = siteStampSourcesOf(event).find(isForeignSiteStamp);
378
- if (foreignStamp) {
379
- logForeignSiteSkip(request, {
380
- stamp: foreignStamp[SITE_STAMP_KEY],
381
- eventType: event.type,
382
- eventIdPrefix,
383
- });
384
- await reply.code(200).send({ received: true });
385
- return;
386
- }
387
-
388
- switch (event.type) {
389
- case "customer.created": {
390
- const customer = event.data.object as {
391
- id: string;
392
- email?: string | null;
393
- metadata?: Record<string, string> | null;
394
- };
395
- // Billing-entity routing (spec D2): metadata.organizationId present →
396
- // the Organization path, which a customer's own metadata can never
397
- // prove (#9067 D13: only a recorded plan session binds), so it writes
398
- // nothing; absent → the User path (single-tenant, degrade-clean).
399
- const organizationId = customer.metadata?.["organizationId"] ?? null;
400
- if (organizationId) {
401
- await upsertOrgBillingIdentity(request, {
402
- organizationId,
403
- customerId: customer.id,
404
- sessionId: null,
405
- eventIdPrefix,
406
- });
407
- } else {
408
- await upsertBillingIdentity(request, {
409
- customerId: customer.id,
410
- userId: signalOf(customer.metadata),
411
- eventType: event.type,
412
- eventIdPrefix,
413
- });
414
- }
415
- break;
416
- }
417
- case "checkout.session.completed": {
418
- const session = event.data.object as CheckoutSessionObject;
419
- if (isForeignSiteStamp(session.metadata)) {
420
- logForeignSiteSkip(request, {
421
- stamp: session.metadata?.[SITE_STAMP_KEY],
422
- eventType: event.type,
423
- eventIdPrefix,
424
- });
425
- break;
426
- }
427
- const props = {
428
- amount: session.amount_total ?? undefined,
429
- currency: session.currency ?? undefined,
430
- productId:
431
- session.metadata?.["productId"] ??
432
- session.metadata?.["product_id"] ??
433
- undefined,
434
- eventType: event.type,
435
- eventIdPrefix,
436
- };
437
-
438
- // Billing-entity routing (spec D2): metadata.organizationId → Organization
439
- // path; absent → the User path (single-tenant).
440
- const organizationId = session.metadata?.["organizationId"] ?? null;
441
- let billingTask: Promise<void> = Promise.resolve();
442
- if (session.customer) {
443
- billingTask = organizationId
444
- ? upsertOrgBillingIdentity(request, {
445
- organizationId,
446
- customerId: session.customer,
447
- sessionId: session.id ?? null,
448
- eventIdPrefix,
449
- })
450
- : upsertBillingIdentity(request, {
451
- customerId: session.customer,
452
- userId: signalOf(session.metadata),
453
- eventType: event.type,
454
- eventIdPrefix,
455
- });
456
- }
457
-
458
- // Telemetry, billing upsert and the recommender stamp are independent —
459
- // run in parallel (the stamp is a no-op without metadata.flowCheckoutId).
460
- // Telemetry, billing upsert, the recommender stamp and the
461
- // request-and-confirm stamp are independent — run in parallel. The
462
- // request stamp is BESIDE the existing three, never instead of them,
463
- // and is a no-op without `session.payment_link` (#5970).
464
- await Promise.all([
465
- fireTelemetryWithTimeout(request, "purchase-completed", props),
466
- billingTask,
467
- // #852 D6 — the Person step runs only after the stamp has settled,
468
- // so it reads the row this very session completed.
469
- stampFlowCheckout(request, {
470
- session,
471
- eventIdPrefix,
472
- outcome: "completed",
473
- })
474
- .then(() =>
475
- recordFlowCheckoutPerson(request, {
476
- session,
477
- livemode: event.livemode === true,
478
- eventIdPrefix,
479
- }),
480
- )
481
- // #8765 D14 — after the Person step, whose Person is a flow
482
- // checkout's grant subject.
483
- .then((flowPerson) =>
484
- recordCheckoutTermsGrant(request, {
485
- session,
486
- livemode: event.livemode === true,
487
- eventIdPrefix,
488
- flowPerson,
489
- }),
490
- ),
491
- stampRequestPaid(request, { session, eventIdPrefix }),
492
- stampProposalPaid(request, { session, eventId: event.id, eventIdPrefix }),
493
- ]);
494
- break;
495
- }
496
- case "invoice.paid": {
497
- // #5970 — the hosted-invoice rung of request-and-confirm. Nothing writes
498
- // `stripeInvoiceId` at this issue's boundary (the invoice path needs a
499
- // `createCustomer` export the stripe-client does not have), so this arm
500
- // is INERT today and exists so that rung lands additively: no second
501
- // migration, no second webhook change. It carries the same guarded
502
- // stamp, so it is already correct when a writer appears.
503
- const invoice = event.data.object as { id?: string };
504
- await stampRequestPaidByInvoice(request, {
505
- invoiceId: invoice.id ?? null,
506
- eventIdPrefix,
507
- });
508
- break;
509
- }
510
- case "checkout.session.expired": {
511
- const session = event.data.object as CheckoutSessionObject;
512
- if (isForeignSiteStamp(session.metadata)) {
513
- logForeignSiteSkip(request, {
514
- stamp: session.metadata?.[SITE_STAMP_KEY],
515
- eventType: event.type,
516
- eventIdPrefix,
517
- });
518
- break;
519
- }
520
- if (!session.metadata?.["flowCheckoutId"]) {
521
- // Not a recommender session — the same low-noise line the default
522
- // arm emitted for this event before #4838 handled it.
523
- request.log.info(
524
- { eventType: event.type, eventIdPrefix },
525
- "unhandled webhook event",
526
- );
527
- break;
528
- }
529
- await stampFlowCheckout(request, {
530
- session,
531
- eventIdPrefix,
532
- outcome: "expired",
533
- });
534
- break;
535
- }
536
- case "invoice.payment_failed": {
537
- // Dunning arm 1 of 2 (#6034 FR-1) — arms dunning for the matched
538
- // subscriber; never revokes on its own. See README.md § Dunning.
539
- const invoice = event.data.object as InvoiceObject;
540
- await armDunning(request, {
541
- invoice,
542
- eventId: event.id,
543
- eventCreated: event.created,
544
- eventIdPrefix,
545
- });
546
- break;
547
- }
548
- case "customer.subscription.updated": {
549
- // Dunning arm 2 of 2 (#6034 FR-2/FR-4) — maps the narrowed Stripe
550
- // status onto the recorded lifecycle state; `canceled` revokes access
551
- // only once the tenant's grace period has expired. See README.md
552
- // § Dunning.
553
- const subscription = event.data.object as SubscriptionObject;
554
- await applySubscriptionStatus(request, {
555
- subscription,
556
- eventId: event.id,
557
- eventCreated: event.created,
558
- eventIdPrefix,
559
- });
560
- break;
561
- }
562
- default:
563
- request.log.info(
564
- { eventType: event.type, eventIdPrefix },
565
- "unhandled webhook event",
566
- );
567
- break;
568
- }
569
-
570
- await reply.code(200).send({ received: true });
571
- };
572
-
573
- type CheckoutSessionObject = {
574
- id?: string;
575
- /**
576
- * Set when the session was opened UNDER a Payment Link — which is how a
577
- * request-and-confirm purchase arrives (#5970 D8). It is the artifact id
578
- * AC-3 matches on, and it is absent on an ordinary checkout.
579
- */
580
- payment_link?: string | null;
581
- payment_status?: string | null;
582
- amount_total?: number | null;
583
- currency?: string | null;
584
- customer?: string | null;
585
- customer_details?: { email?: string | null } | null;
586
- /** The terms box's answer (#8765 D14): `accepted` when the buyer ticked it. */
587
- consent?: { terms_of_service?: string | null } | null;
588
- metadata?: Record<string, string> | null;
589
- };
590
-
591
- /**
592
- * The one log line for an event another site stamped (#7868 D3, #8024 D3).
593
- * Carries the foreign stamp (first 64 characters) and this site's own alias,
594
- * so a spoke event correctly skipped can be told from a hub event whose alias
595
- * drifted — site labels only: it takes the stamp, never the object, so no
596
- * buyer field, customer id or amount can reach it.
597
- */
598
- function logForeignSiteSkip(
599
- request: FastifyRequest,
600
- {
601
- stamp,
602
- eventType,
603
- eventIdPrefix,
604
- }: {
605
- stamp: string | undefined;
606
- eventType: string;
607
- eventIdPrefix: string;
608
- },
609
- ): void {
610
- request.log.info(
611
- {
612
- eventType,
613
- eventIdPrefix,
614
- outcome: "foreign_site",
615
- stamp: stamp?.slice(0, 64),
616
- ownSite: currentSiteId(),
617
- },
618
- "stripe event stamped for another site — skipped",
619
- );
620
- }
621
-
622
- /** The object type whose metadata carries the site for each billing family (#8024 D2). */
623
- function stampedObjectTypeOf(eventType: string): "subscription" | "customer" | "invoice" | null {
624
- if (eventType.startsWith("customer.subscription.")) return "subscription";
625
- if (eventType.startsWith("customer.")) return "customer";
626
- if (eventType.startsWith("invoice.")) return "invoice";
627
- return null;
628
- }
629
-
630
- /** `value` when it is a non-null object, else `null` — every step of a stamp read is guarded (NF1). */
631
- function objectOrNull(value: unknown): Record<string, unknown> | null {
632
- return typeof value === "object" && value !== null
633
- ? (value as Record<string, unknown>)
634
- : null;
635
- }
636
-
637
- /**
638
- * The metadata objects that may carry an event's site stamp (#8024 D2), in the
639
- * order they are checked: a Subscription's or a Customer's own metadata; an
640
- * invoice's own metadata, then the subscription snapshot at the pinned API
641
- * version (`parent.subscription_details.metadata`), then at a pre-`basil` one
642
- * (`subscription_details.metadata`). Empty for every other event type, and
643
- * when `data.object.object` is not the family's own type — a
644
- * `customer.source.*` card, say. Reads the payload alone and never throws on
645
- * any shape: an absent, `null` or non-object step yields no source, and
646
- * `isForeignSiteStamp` treats a non-string stamp as unstamped.
647
- */
648
- function siteStampSourcesOf(event: {
649
- type: string;
650
- data?: unknown;
651
- }): Record<string, string>[] {
652
- const objectType = stampedObjectTypeOf(event.type);
653
- const object = objectOrNull(objectOrNull(event.data)?.["object"]);
654
- if (objectType === null || object?.["object"] !== objectType) return [];
655
-
656
- const candidates =
657
- objectType === "invoice"
658
- ? [
659
- object["metadata"],
660
- objectOrNull(objectOrNull(object["parent"])?.["subscription_details"])?.[
661
- "metadata"
662
- ],
663
- objectOrNull(object["subscription_details"])?.["metadata"],
664
- ]
665
- : [object["metadata"]];
666
- // The cast only narrows the value type for `isForeignSiteStamp`, which
667
- // reads the stamp as `unknown` and `typeof`-checks it.
668
- return candidates
669
- .map(objectOrNull)
670
- .filter((source) => source !== null) as Record<string, string>[];
671
- }
672
-
673
- /** The metadata key the hub's Offerings checkout stamps on its sessions (contract A6, #8932 D9). */
674
- const OFFERINGS_STAMP_KEY = "ailk_offering";
675
-
676
- /**
677
- * Where an Offerings stamp may sit (#8932 D9): every site-stamp source
678
- * (`siteStampSourcesOf` — the Subscription, the Customer and an invoice's
679
- * three) plus, for a `checkout.session.*` event whose object is a session,
680
- * the session's own metadata.
681
- */
682
- function offeringsStampSourcesOf(event: {
683
- type: string;
684
- data?: unknown;
685
- }): Record<string, string>[] {
686
- const sources = siteStampSourcesOf(event);
687
- const object = objectOrNull(objectOrNull(event.data)?.["object"]);
688
- if (event.type.startsWith("checkout.session.") && object?.["object"] === "checkout.session") {
689
- const metadata = objectOrNull(object["metadata"]);
690
- if (metadata !== null) sources.push(metadata as Record<string, string>);
691
- }
692
- return sources;
693
- }
694
-
695
- /**
696
- * Minimal projected shape of a Stripe Invoice object for the dunning arms
697
- * (#6034 FR-1). `subscription` and `customer` are EXPANDABLE Stripe fields —
698
- * like `CheckoutSessionObject.payment_link` above, either can arrive as an
699
- * object rather than a string on a future `expand` or API-version change, so
700
- * both are `typeof`-guarded at the call site (§ D9) and never trusted from
701
- * this cast.
702
- */
703
- type InvoiceObject = {
704
- subscription?: string | null;
705
- customer?: string | null;
706
- };
707
-
708
- /**
709
- * Minimal projected shape of a Stripe Subscription object for the dunning
710
- * arms (#6034 FR-2). `customer` carries the same expandable-field risk as
711
- * `InvoiceObject.customer` and is guarded the same way.
712
- */
713
- type SubscriptionObject = {
714
- id?: string;
715
- customer?: string | null;
716
- status?: string;
717
- canceled_at?: number | null;
718
- ended_at?: number | null;
719
- };
720
-
721
- /**
722
- * Stamp the recommender's FlowCheckout buyer row from a terminal Checkout
723
- * Session event (#4838).
724
- *
725
- * The `status: "created"` guard on the update IS the idempotency key (D1):
726
- * `count === 1` → stamped; `count === 0` → the row is already terminal, or the
727
- * id is unknown — a warning, never a retry (Stripe would re-fire telemetry +
728
- * billing on eventual success). A `completed` session whose
729
- * `payment_status` is not `"paid"` logs `unpaid` and leaves the row `created`. A charged amount that differs from the quoted
730
- * `amountMinor` is logged with both integers and the stamp proceeds (D2). Log
731
- * lines carry only `eventIdPrefix`, an 8-char `flowCheckoutIdPrefix`, an
732
- * `outcome`, and the two integers — never the email, customer id, or permalink.
733
- *
734
- * Never throws — the handler's "always 200 for a verified event" contract.
735
- */
736
- async function stampFlowCheckout(
737
- request: FastifyRequest,
738
- {
739
- session,
740
- eventIdPrefix,
741
- outcome,
742
- }: {
743
- session: CheckoutSessionObject;
744
- eventIdPrefix: string;
745
- outcome: "completed" | "expired";
746
- },
747
- ): Promise<void> {
748
- const flowCheckoutId = session.metadata?.["flowCheckoutId"];
749
- if (!flowCheckoutId) return;
750
- const flowCheckoutIdPrefix = flowCheckoutId.substring(0, 8);
751
-
752
- // A `completed` session is only a purchase once Stripe reports it paid, OR
753
- // reports nothing was due (`no_payment_required` — a 100%-off promo code,
754
- // #4862, still a Stripe-confirmed completion). A delayed-notification or
755
- // genuinely unpaid completion leaves the row `created` (code + security
756
- // review, PR #4855).
757
- if (
758
- outcome === "completed" &&
759
- session.payment_status !== "paid" &&
760
- session.payment_status !== "no_payment_required"
761
- ) {
762
- request.log.warn(
763
- { eventIdPrefix, flowCheckoutIdPrefix, outcome: "unpaid" },
764
- "flow checkout: completed session is not paid — not stamping",
765
- );
766
- return;
767
- }
768
-
769
- try {
770
- if (outcome === "completed" && typeof session.amount_total === "number") {
771
- const row = await prisma.flowCheckout.findUnique({
772
- where: { id: flowCheckoutId },
773
- select: { amountMinor: true },
774
- });
775
- if (row && row.amountMinor !== session.amount_total) {
776
- request.log.warn(
777
- {
778
- eventIdPrefix,
779
- flowCheckoutIdPrefix,
780
- outcome: "amount_mismatch",
781
- expected: row.amountMinor,
782
- received: session.amount_total,
783
- },
784
- "flow checkout: charged amount differs from the quoted amount — stamping anyway",
785
- );
786
- }
787
- }
788
-
789
- const result = await prisma.flowCheckout.updateMany({
790
- where: { id: flowCheckoutId, status: "created" },
791
- data:
792
- outcome === "completed"
793
- ? {
794
- status: "completed",
795
- completedAt: new Date(),
796
- stripeSessionId: session.id ?? null,
797
- stripeCustomerId: session.customer ?? null,
798
- }
799
- : { status: "expired" },
800
- });
801
-
802
- if (result.count === 1) {
803
- request.log.info(
804
- { eventIdPrefix, flowCheckoutIdPrefix, outcome },
805
- "flow checkout stamped",
806
- );
807
- } else {
808
- request.log.warn(
809
- { eventIdPrefix, flowCheckoutIdPrefix, outcome: "stale_or_unknown" },
810
- "flow checkout: no created row matched — replay, late terminal event, or unknown id",
811
- );
812
- }
813
- } catch (err) {
814
- request.log.error(
815
- {
816
- eventIdPrefix,
817
- flowCheckoutIdPrefix,
818
- outcome: "stamp_failed",
819
- errName: err instanceof Error ? err.name : "UnknownError",
820
- },
821
- "flow checkout stamp failed — continuing",
822
- );
823
- }
824
- }
825
-
826
- /**
827
- * The hub checkout's Person (#852 D6): after `stampFlowCheckout`, find or
828
- * create the Person of the completed checkout's lead
829
- * (`services/person.ts`'s `resolveCheckoutPerson`). Runs only for a paid (or
830
- * nothing-due) session of THIS site — the foreign-site filter has already
831
- * returned — that carries `metadata.flowCheckoutId`. The customer id's ONE
832
- * source is `session.customer`, written onto the Person only for a
833
- * live-mode event (SEC-852-A). A replay matches the same completed row, so a
834
- * delivery whose Person step failed is repaired by the next one.
835
- *
836
- * Logs `{ eventIdPrefix, flowCheckoutIdPrefix, outcome }` only — never the
837
- * email or the customer id. Answers the Person, or `null` when the step did
838
- * not run or found none (#8765 D14). Never throws: the response stays 200.
839
- */
840
- async function recordFlowCheckoutPerson(
841
- request: FastifyRequest,
842
- {
843
- session,
844
- livemode,
845
- eventIdPrefix,
846
- }: {
847
- session: CheckoutSessionObject;
848
- livemode: boolean;
849
- eventIdPrefix: string;
850
- },
851
- ): Promise<CheckoutPersonResult["person"]> {
852
- const flowCheckoutId = session.metadata?.["flowCheckoutId"];
853
- if (!flowCheckoutId) return null;
854
- if (
855
- session.payment_status !== "paid" &&
856
- session.payment_status !== "no_payment_required"
857
- ) {
858
- return null;
859
- }
860
- const flowCheckoutIdPrefix = flowCheckoutId.substring(0, 8);
861
- let result: CheckoutPersonResult;
862
- try {
863
- result = await resolveCheckoutPerson({
864
- flowCheckoutId,
865
- stripeSessionId: session.id,
866
- customer: session.customer,
867
- livemode,
868
- });
869
- } catch {
870
- result = { outcome: "person_failed", person: null };
871
- }
872
- const line = { eventIdPrefix, flowCheckoutIdPrefix, outcome: result.outcome };
873
- if (result.outcome === "person_failed") {
874
- request.log.error(line, "flow checkout person failed — continuing");
875
- } else {
876
- request.log.info(line, "flow checkout person");
877
- }
878
- return result.person;
879
- }
880
-
881
- /** The metadata key the Checkout creators stamp with the terms the box showed (#8765 D12). */
882
- const TERMS_STAMP_KEY = "ailk_terms";
883
-
884
- /**
885
- * `<purposeId>@<policyVersion>` of the account terms as the registry reads
886
- * them now — the only stamp a grant is recorded for (SEC-8765-E) — and that
887
- * version, which `recordCheckoutConsent` checks against the site's registry.
888
- * Derived, never written down, so a version bump retires every older stamp.
889
- */
890
- function currentTermsStamp(): { stamp: string; policyVersion: number } | null {
891
- const purpose = consentPurposeById(
892
- SITE_CONSENT_CONFIG_DEFAULTS,
893
- ACCOUNT_TERMS_PURPOSE_ID,
894
- );
895
- return purpose
896
- ? {
897
- stamp: `${purpose.id}@${purpose.policyVersion}`,
898
- policyVersion: purpose.policyVersion,
899
- }
900
- : null;
901
- }
902
-
903
- /**
904
- * The buyer's terms grant (#8765 D14). Writes nothing — and logs why — for a
905
- * session whose box was not accepted (`consent_absent`: Stripe enforced the
906
- * box, so the order completes regardless), one that does not carry the
907
- * current `ailk_terms` stamp (`terms_unstamped`: a Payment Link, an invoice,
908
- * an older session or other terms), or one whose buyer has no Person
909
- * (`person_unresolved`). Otherwise `recordCheckoutConsent` writes at most one
910
- * row per Person and session (`recorded` / `unchanged`), or none when the
911
- * site's registry has moved past the stamped version (`version_changed`).
912
- *
913
- * Logs `{ event, outcome, eventIdPrefix }` only (plus `errName` on `failed`)
914
- * — never an email or a Person id. Never throws: the response stays 200.
915
- */
916
- async function recordCheckoutTermsGrant(
917
- request: FastifyRequest,
918
- {
919
- session,
920
- livemode,
921
- eventIdPrefix,
922
- flowPerson,
923
- }: {
924
- session: CheckoutSessionObject;
925
- livemode: boolean;
926
- eventIdPrefix: string;
927
- /** A flow checkout's Person, from `recordFlowCheckoutPerson`. */
928
- flowPerson: CheckoutPersonResult["person"];
929
- },
930
- ): Promise<void> {
931
- const line = (outcome: string) => ({
932
- event: "checkout-consent",
933
- outcome,
934
- eventIdPrefix,
935
- });
936
- try {
937
- if (session.consent?.terms_of_service !== "accepted") {
938
- request.log.info(
939
- line("consent_absent"),
940
- "checkout terms grant: box not accepted",
941
- );
942
- return;
943
- }
944
- const stamp: unknown = session.metadata?.[TERMS_STAMP_KEY];
945
- const expected = currentTermsStamp();
946
- if (expected === null || stamp !== expected.stamp) {
947
- request.log.info(
948
- line("terms_unstamped"),
949
- "checkout terms grant: session carries no current terms stamp",
950
- );
951
- return;
952
- }
953
- const sessionId = session.id;
954
- const buyer =
955
- typeof sessionId === "string" && sessionId !== ""
956
- ? await checkoutBuyerPerson(session, livemode, flowPerson)
957
- : null;
958
- if (buyer === null || typeof sessionId !== "string") {
959
- request.log.info(
960
- line("person_unresolved"),
961
- "checkout terms grant: no Person for this buyer",
962
- );
963
- return;
964
- }
965
- const outcome = await recordCheckoutConsent({
966
- workspaceId: buyer.workspaceId,
967
- personId: buyer.personId,
968
- sessionId,
969
- policyVersion: expected.policyVersion,
970
- });
971
- request.log.info(line(outcome), "checkout terms grant");
972
- } catch (err) {
973
- // The error's class only (a Prisma error's message can carry values).
974
- request.log.error(
975
- {
976
- ...line("failed"),
977
- errName: err instanceof Error ? err.name : "UnknownError",
978
- },
979
- "checkout terms grant failed — continuing",
980
- );
981
- }
982
- }
983
-
984
- /**
985
- * Stamp `paidAt` on a request-and-confirm callback row (#5970 AC-3).
986
- *
987
- * THE MATCH KEY IS THE ARTIFACT ID, not metadata. Paying a Payment Link opens
988
- * a Checkout Session under that link, so the paid event is the ordinary
989
- * `checkout.session.completed` — and the session carries
990
- * `payment_link: "plink_…"`, which is exactly the id the confirm route stored
991
- * on the row. A session with no `payment_link` is an ordinary checkout and is
992
- * skipped BEFORE any query, so the existing checkout suites see no new DB
993
- * traffic whatsoever.
994
- *
995
- * TWO IDEMPOTENCY LAYERS, and only the second is durable. A replayed event
996
- * never reaches here at all — `hasSeen` short-circuits it upstream. But that
997
- * store is an in-process TTL `Map`: restart the process and the id is gone. So
998
- * the `paidAt: null` guard on the update IS the idempotency key, the same way
999
- * `status: "created"` is `stampFlowCheckout`'s. `count === 1` ⇒ stamped once;
1000
- * `count === 0` ⇒ already paid, or an id this deployment never minted — a
1001
- * warning, never a throw and never a retry (Stripe would re-fire the sibling
1002
- * telemetry and billing tasks on eventual success).
1003
- *
1004
- * A `completed` session stamps only when Stripe reports it `paid`, or reports
1005
- * nothing was due (`no_payment_required` — a 100%-off promotion is still a
1006
- * Stripe-confirmed completion). The same two values `stampFlowCheckout`
1007
- * accepts, for the same reason.
1008
- *
1009
- * `stripeCheckoutSessionId` is written from the same event for support
1010
- * lookups. Nothing ever matches on it.
1011
- *
1012
- * Never throws — the handler's "always 200 for a verified event" contract.
1013
- */
1014
- async function stampRequestPaid(
1015
- request: FastifyRequest,
1016
- {
1017
- session,
1018
- eventIdPrefix,
1019
- }: { session: CheckoutSessionObject; eventIdPrefix: string },
1020
- ): Promise<void> {
1021
- const paymentLinkId = session.payment_link;
1022
- // `typeof`, not just truthiness (#5970 security review, finding 7):
1023
- // `payment_link` is an EXPANDABLE Stripe field, so a future `expand` or an
1024
- // API-version change could deliver it as an object — on which `.substring`
1025
- // throws a TypeError that would escape this function, reject the
1026
- // `Promise.all` above, and turn a verified event into a 500 that Stripe then
1027
- // retries, taking the sibling telemetry and billing tasks down with it. This
1028
- // function's contract is that it never throws.
1029
- if (typeof paymentLinkId !== "string" || paymentLinkId === "") return;
1030
- const paymentLinkIdPrefix = paymentLinkId.substring(0, 8);
1031
-
1032
- if (
1033
- session.payment_status !== "paid" &&
1034
- session.payment_status !== "no_payment_required"
1035
- ) {
1036
- request.log.warn(
1037
- { eventIdPrefix, paymentLinkIdPrefix, outcome: "unpaid" },
1038
- "request-confirm: completed session is not paid — not stamping",
1039
- );
1040
- return;
1041
- }
1042
-
1043
- try {
1044
- const result = await prisma.callback.updateMany({
1045
- where: { stripePaymentLinkId: paymentLinkId, paidAt: null },
1046
- data: {
1047
- paidAt: new Date(),
1048
- stripeCheckoutSessionId: session.id ?? null,
1049
- },
1050
- });
1051
-
1052
- if (result.count === 1) {
1053
- request.log.info(
1054
- { eventIdPrefix, paymentLinkIdPrefix, outcome: "paid" },
1055
- "request-confirm stamped paid",
1056
- );
1057
- } else {
1058
- request.log.warn(
1059
- { eventIdPrefix, paymentLinkIdPrefix, outcome: "stale_or_unknown" },
1060
- "request-confirm: no unpaid row matched — replay, late event, or an unknown payment link",
1061
- );
1062
- }
1063
- } catch (err) {
1064
- request.log.error(
1065
- {
1066
- eventIdPrefix,
1067
- paymentLinkIdPrefix,
1068
- outcome: "stamp_failed",
1069
- errName: err instanceof Error ? err.name : "UnknownError",
1070
- },
1071
- "request-confirm stamp failed — continuing",
1072
- );
1073
- }
1074
- }
1075
-
1076
- /**
1077
- * #8516 D13 — stamp a client's proposal paid from its own Checkout Session,
1078
- * and audit the outcome as Stripe. The two ids come only from the session's
1079
- * metadata, which this server wrote when it opened the session — a payer can
1080
- * never set it — and the stamp is scoped by both. Never throws.
1081
- */
1082
- async function stampProposalPaid(
1083
- request: FastifyRequest,
1084
- {
1085
- session,
1086
- eventId,
1087
- eventIdPrefix,
1088
- }: { session: CheckoutSessionObject; eventId: string; eventIdPrefix: string },
1089
- ): Promise<void> {
1090
- const pieceId = session.metadata?.["ailk_proposal"];
1091
- const workspaceId = session.metadata?.["ailk_workspace"];
1092
- const sessionId = session.id;
1093
- if (
1094
- typeof pieceId !== "string" ||
1095
- typeof workspaceId !== "string" ||
1096
- typeof sessionId !== "string" ||
1097
- !isId("piece", pieceId) ||
1098
- !isId("workspace", workspaceId)
1099
- ) {
1100
- return;
1101
- }
1102
- const ref = pieceId.substring(6, 14);
1103
-
1104
- const audit = async (outcome: { ok: true } | { ok: false; reason: string }) => {
1105
- const result = await recordWorkspaceAuditAction({
1106
- workspaceId,
1107
- actor: { type: "system", systemId: "stripe" },
1108
- domain: "people",
1109
- tool: "proposal.paid",
1110
- outcome: outcome.ok ? "succeeded" : "failed",
1111
- ...(!outcome.ok && { failureReason: outcome.reason }),
1112
- idempotencyKey: eventId,
1113
- targetType: "piece",
1114
- targetId: pieceId,
1115
- });
1116
- if (!result.ok) {
1117
- request.log.error(
1118
- { eventIdPrefix, ref, error: result.error.kind },
1119
- "proposal paid: audit write failed",
1120
- );
1121
- }
1122
- };
1123
-
1124
- if (
1125
- session.payment_status !== "paid" &&
1126
- session.payment_status !== "no_payment_required"
1127
- ) {
1128
- request.log.warn(
1129
- { eventIdPrefix, ref, outcome: "not_paid" },
1130
- "proposal paid: completed session is not paid — not stamping",
1131
- );
1132
- await audit({ ok: false, reason: "not_paid" });
1133
- return;
1134
- }
1135
-
1136
- try {
1137
- const outcome = await writeProposalPaid(workspaceId, pieceId, sessionId, new Date());
1138
- if (outcome === "stamped") {
1139
- request.log.info({ eventIdPrefix, ref, outcome }, "proposal stamped paid");
1140
- await audit({ ok: true });
1141
- } else if (outcome === "already_paid") {
1142
- request.log.warn(
1143
- { eventIdPrefix, ref, outcome },
1144
- "proposal paid: already paid by another session — a second charge",
1145
- );
1146
- await audit({ ok: false, reason: "already_paid" });
1147
- } else if (outcome === "not_found") {
1148
- request.log.warn({ eventIdPrefix, ref, outcome }, "proposal paid: no such proposal");
1149
- } else {
1150
- request.log.info({ eventIdPrefix, ref, outcome }, "proposal paid: replay");
1151
- }
1152
- } catch (err) {
1153
- request.log.error(
1154
- {
1155
- eventIdPrefix,
1156
- ref,
1157
- outcome: "stamp_failed",
1158
- errName: err instanceof Error ? err.name : "UnknownError",
1159
- },
1160
- "proposal paid stamp failed — continuing",
1161
- );
1162
- }
1163
- }
1164
-
1165
- /**
1166
- * The hosted-invoice twin of `stampRequestPaid` (#5970 D4/D8).
1167
- *
1168
- * Inert at this issue's boundary — nothing writes `stripeInvoiceId` yet — and
1169
- * deliberately present anyway, carrying the identical guarded update, so the
1170
- * invoice rung is a writer away rather than a migration and a webhook change
1171
- * away.
1172
- */
1173
- async function stampRequestPaidByInvoice(
1174
- request: FastifyRequest,
1175
- {
1176
- invoiceId,
1177
- eventIdPrefix,
1178
- }: { invoiceId: string | null; eventIdPrefix: string },
1179
- ): Promise<void> {
1180
- // The same `typeof` guard its Payment-Link sibling carries, for the same
1181
- // reason (#5970 security review round 2, L1): this arm is explicitly
1182
- // forward-looking, so the hardening has to travel with it rather than be
1183
- // added when a writer appears and the shape stops being guaranteed.
1184
- if (typeof invoiceId !== "string" || invoiceId === "") return;
1185
- const invoiceIdPrefix = invoiceId.substring(0, 8);
1186
-
1187
- try {
1188
- const result = await prisma.callback.updateMany({
1189
- where: { stripeInvoiceId: invoiceId, paidAt: null },
1190
- data: { paidAt: new Date() },
1191
- });
1192
-
1193
- if (result.count === 1) {
1194
- request.log.info(
1195
- { eventIdPrefix, invoiceIdPrefix, outcome: "paid" },
1196
- "request-confirm stamped paid from invoice",
1197
- );
1198
- return;
1199
- }
1200
- // An unmatched `invoice.paid` is the ORDINARY case today and for every
1201
- // deployment using Stripe invoices for anything else, so this is `info`
1202
- // rather than the `warn` its Payment-Link sibling emits.
1203
- request.log.info(
1204
- { eventIdPrefix, invoiceIdPrefix, outcome: "not_a_request_invoice" },
1205
- "request-confirm: invoice.paid matched no request row",
1206
- );
1207
- } catch (err) {
1208
- request.log.error(
1209
- {
1210
- eventIdPrefix,
1211
- invoiceIdPrefix,
1212
- outcome: "stamp_failed",
1213
- errName: err instanceof Error ? err.name : "UnknownError",
1214
- },
1215
- "request-confirm invoice stamp failed — continuing",
1216
- );
1217
- }
1218
- }
1219
-
1220
- /**
1221
- * The verified user signal (#6852): `metadata.ailk_user_id` on the Checkout
1222
- * session or the Stripe customer, when it is a non-empty string. Never
1223
- * `client_reference_id` (a Payment Link accepts it from the payer's URL) and
1224
- * never the payer-typed email.
1225
- */
1226
- function signalOf(
1227
- metadata: Record<string, string> | null | undefined,
1228
- ): string | null {
1229
- const value: unknown = metadata?.["ailk_user_id"];
1230
- return typeof value === "string" && value !== "" ? value : null;
1231
- }
1232
-
1233
- /**
1234
- * Link User.billingProvider + User.billingCustomerId for a Stripe customer.
1235
- *
1236
- * Lookup priority:
1237
- * 1. Typed composite match: (billingProvider="stripe", billingCustomerId=customerId)
1238
- * → already linked; no-op (idempotent)
1239
- * 2. Verified user signal (#6852): `metadata.ailk_user_id` →
1240
- * User.findUnique({ where: { id } }) → bind only when the row's
1241
- * billingCustomerId is empty; otherwise log billing_identity_conflict and
1242
- * write nothing (#6113). The write is guarded on `billingCustomerId: null`;
1243
- * a P2025 means a concurrent event bound the row first — the same customer
1244
- * is a no-op, any other is a conflict.
1245
- * No signal → log billing_identity_unverified and write nothing. The payer
1246
- * types the Checkout email and Stripe never verifies it, so an email
1247
- * never makes a binding, first or otherwise.
1248
- * Trust boundary: Checkout-session and customer `metadata` can be written
1249
- * only by a principal the seller authorised on their Stripe account (our
1250
- * server's key, a write-capable restricted key, a connected app, the
1251
- * dashboard, a Payment Link's own metadata) — never by the payer. A
1252
- * producer sets the key only from an authenticated server session, never
1253
- * from request input.
1254
- * 3. Signal names no User → warn billing_identity_unknown_user; do NOT
1255
- * create a User row (pre-signup state preserved for Phase B #852)
1256
- *
1257
- * No line logs the email, the Stripe customer id, or an unresolved signal.
1258
- *
1259
- * DB failures are caught and logged — a broken DB link should not cause Stripe to retry
1260
- * the event (which would fire analytics + billing again on eventual success).
1261
- */
1262
- async function upsertBillingIdentity(
1263
- request: FastifyRequest,
1264
- {
1265
- customerId,
1266
- userId,
1267
- eventType,
1268
- eventIdPrefix,
1269
- }: {
1270
- customerId: string;
1271
- userId: string | null;
1272
- eventType: string;
1273
- eventIdPrefix: string;
1274
- },
1275
- ): Promise<void> {
1276
- try {
1277
- const existingByBilling = await prisma.user.findFirst({
1278
- where: {
1279
- billingProvider: "stripe",
1280
- billingCustomerId: customerId,
1281
- },
1282
- });
1283
-
1284
- if (existingByBilling) {
1285
- request.log.info(
1286
- { eventIdPrefix },
1287
- "billing identity already linked — idempotent no-op",
1288
- );
1289
- return;
1290
- }
1291
-
1292
- if (!userId) {
1293
- // A customer Checkout creates never carries session metadata, so a
1294
- // no-signal customer.created is every ordinary purchase — info, not warn.
1295
- const fields = {
1296
- eventIdPrefix,
1297
- eventType,
1298
- outcome: "billing_identity_unverified",
1299
- };
1300
- const msg =
1301
- "stripe webhook: no verified user signal — billing identity not bound";
1302
- if (eventType === "customer.created") request.log.info(fields, msg);
1303
- else request.log.warn(fields, msg);
1304
- return;
1305
- }
1306
-
1307
- const row = await prisma.user.findUnique({
1308
- where: { id: userId },
1309
- select: { id: true, billingProvider: true, billingCustomerId: true },
1310
- });
1311
-
1312
- if (!row) {
1313
- request.log.warn(
1314
- { eventIdPrefix, eventType, outcome: "billing_identity_unknown_user" },
1315
- "stripe webhook: user signal names no User — pre-signup state preserved",
1316
- );
1317
- return;
1318
- }
1319
-
1320
- const isSameBinding = (r: {
1321
- billingProvider: string | null;
1322
- billingCustomerId: string | null;
1323
- }) => r.billingProvider === "stripe" && r.billingCustomerId === customerId;
1324
- const logAlreadyLinked = () =>
1325
- request.log.info(
1326
- { eventIdPrefix, outcome: "billing_identity_already_linked" },
1327
- "billing identity already linked — idempotent no-op",
1328
- );
1329
- const logConflict = () =>
1330
- request.log.warn(
1331
- {
1332
- eventIdPrefix,
1333
- outcome: "billing_identity_conflict",
1334
- userId: row.id,
1335
- },
1336
- "stripe webhook: user already bound to a different billing customer — not re-pointed",
1337
- );
1338
-
1339
- if (row.billingCustomerId !== null) {
1340
- if (isSameBinding(row)) logAlreadyLinked();
1341
- else logConflict();
1342
- return;
1343
- }
1344
-
1345
- try {
1346
- await prisma.user.update({
1347
- where: { id: row.id, billingCustomerId: null },
1348
- data: {
1349
- billingProvider: "stripe",
1350
- billingCustomerId: customerId,
1351
- },
1352
- });
1353
- } catch (err) {
1354
- if ((err as { code?: unknown }).code !== "P2025") throw err;
1355
- const now = await prisma.user.findUnique({
1356
- where: { id: row.id },
1357
- select: { billingProvider: true, billingCustomerId: true },
1358
- });
1359
- if (now && isSameBinding(now)) logAlreadyLinked();
1360
- else logConflict();
1361
- return;
1362
- }
1363
- request.log.info(
1364
- { eventIdPrefix },
1365
- "billing identity linked via verified user signal",
1366
- );
1367
- } catch (err) {
1368
- request.log.error(
1369
- {
1370
- eventIdPrefix,
1371
- error: err instanceof Error ? err.message : String(err),
1372
- },
1373
- "billing identity upsert failed — continuing",
1374
- );
1375
- }
1376
- }
1377
-
1378
- /**
1379
- * Link Organization.billingProvider + billingCustomerId for a Stripe customer
1380
- * (org-scoped billing, #3601, spec D2/D3), only on proof (#9067 D13,
1381
- * SEC-9067-1 to -3). `metadata.organizationId` names the target; the proof
1382
- * is the session id POST /v1/billing/plan-checkout recorded on that
1383
- * Organization. The bind is one guarded `updateMany` on `{ id,
1384
- * planCheckoutSessionId: sessionId, billingCustomerId: null }`, which also
1385
- * clears the recorded session — so a session no route recorded, a session
1386
- * recorded by another deployment's database, a re-point of a bound customer
1387
- * and a `customer.created` (`sessionId` null: a customer's metadata proves
1388
- * nothing) all bind nothing and log `org_bind_unproven`.
1389
- *
1390
- * Idempotent: a typed-composite match (billingProvider="stripe",
1391
- * billingCustomerId=customerId) already pointing at THIS org is a no-op on
1392
- * replay.
1393
- *
1394
- * DB failures are caught and logged (never re-thrown) — a broken link must not
1395
- * make Stripe retry (which would re-fire analytics + billing on eventual
1396
- * success), matching the User-path contract above.
1397
- */
1398
- async function upsertOrgBillingIdentity(
1399
- request: FastifyRequest,
1400
- {
1401
- organizationId,
1402
- customerId,
1403
- sessionId,
1404
- eventIdPrefix,
1405
- }: {
1406
- organizationId: string;
1407
- customerId: string;
1408
- sessionId: string | null;
1409
- eventIdPrefix: string;
1410
- },
1411
- ): Promise<void> {
1412
- const unproven = () =>
1413
- request.log.warn(
1414
- { eventIdPrefix, outcome: "org_bind_unproven" },
1415
- "org billing identity not linked — no recorded plan checkout proves it",
1416
- );
1417
- if (sessionId === null) {
1418
- unproven();
1419
- return;
1420
- }
1421
- try {
1422
- const existingByBilling = await prisma.organization.findFirst({
1423
- where: {
1424
- billingProvider: "stripe",
1425
- billingCustomerId: customerId,
1426
- },
1427
- });
1428
-
1429
- if (existingByBilling && existingByBilling.id === organizationId) {
1430
- request.log.info(
1431
- { eventIdPrefix },
1432
- "org billing identity already linked — idempotent no-op",
1433
- );
1434
- return;
1435
- }
1436
-
1437
- const { count } = await prisma.organization.updateMany({
1438
- where: { id: organizationId, planCheckoutSessionId: sessionId, billingCustomerId: null },
1439
- data: {
1440
- billingProvider: "stripe",
1441
- billingCustomerId: customerId,
1442
- planCheckoutSessionId: null,
1443
- },
1444
- });
1445
- if (count !== 1) {
1446
- unproven();
1447
- return;
1448
- }
1449
- request.log.info(
1450
- { eventIdPrefix },
1451
- "org billing identity linked from the recorded plan checkout",
1452
- );
1453
- } catch (err) {
1454
- // #9067 FR-6 — the name and Prisma code only: some Prisma messages
1455
- // print the call's arguments, which here carry the session and customer ids.
1456
- request.log.error(
1457
- {
1458
- eventIdPrefix,
1459
- errName: err instanceof Error ? err.name : "unknown",
1460
- code: (err as { code?: unknown } | null)?.code,
1461
- },
1462
- "org billing identity upsert failed — continuing",
1463
- );
1464
- }
1465
- }
1466
-
1467
- async function fireTelemetryWithTimeout(
1468
- request: FastifyRequest,
1469
- name: string,
1470
- props: Record<string, unknown>,
1471
- ): Promise<void> {
1472
- let timeoutId!: ReturnType<typeof setTimeout>;
1473
- const timeout = new Promise<void>((resolve) => {
1474
- timeoutId = setTimeout(() => {
1475
- request.log.warn(
1476
- { telemetryEvent: name },
1477
- "telemetry call exceeded timeout; continuing",
1478
- );
1479
- resolve();
1480
- }, TELEMETRY_TIMEOUT_MS);
1481
- });
1482
-
1483
- try {
1484
- await Promise.race([track(name, props), timeout]);
1485
- } catch (err) {
1486
- request.log.error(
1487
- {
1488
- telemetryEvent: name,
1489
- error: err instanceof Error ? err.message : String(err),
1490
- },
1491
- "telemetry call threw",
1492
- );
1493
- } finally {
1494
- clearTimeout(timeoutId);
1495
- }
1496
- }
1497
-
1498
- // ── Dunning (#6034) ──────────────────────────────────────────────────────
1499
- //
1500
- // Arms and applies the per-tenant dunning record documented in
1501
- // README.md § Dunning. Both arms below share one write primitive
1502
- // (`writeDunningRecord`) that enforces § D6's ordering/tie/durable-replay
1503
- // admission rule and its compare-and-swap over the FULL observed read-set
1504
- // (`value` as well as `updatedAt`) — never a `$transaction`, following
1505
- // `usage-credits.ts:20-33`'s reasoning: a single conditional `UPDATE` IS the
1506
- // atomic compare-and-swap.
1507
-
1508
- /**
1509
- * The "past_due" candidate both arms compute identically (FR-1's
1510
- * `invoice.payment_failed` arm, and `customer.subscription.updated`'s own
1511
- * `past_due`/`unpaid` branch) — one shared shape rather than two copies that
1512
- * could drift: never revokes, `dunningArmedAt` is stamped once and never
1513
- * moved while the subscription stays failing (§ D5), and `accessRevokesAt`
1514
- * is cleared so a re-arm after a prior cancellation carries no stale
1515
- * revocation schedule.
1516
- *
1517
- * Callers differ on whether a recorded `canceled` entry may be relaxed by
1518
- * this candidate — see `armDunning`'s own guard, which is deliberately NOT
1519
- * folded in here (code review finding, #6034): `customer.subscription
1520
- * .updated` is the SUBSCRIPTION-level authoritative source and a strictly
1521
- * newer transition to `past_due` is a real signal worth admitting (§ D6
1522
- * rule 4), while `invoice.payment_failed` is only ever about ONE invoice and
1523
- * must never outrank a subscription-level cancellation already recorded.
1524
- */
1525
- function computeArmedEntry(
1526
- current: DunningEntry | undefined,
1527
- event: { id: string; created: number },
1528
- ): DunningEntry {
1529
- return {
1530
- status: "past_due",
1531
- accessState: "granted",
1532
- dunningArmedAt: current?.dunningArmedAt ?? new Date().toISOString(),
1533
- accessRevokesAt: null,
1534
- lastEventAt: event.created,
1535
- lastEventId: event.id,
1536
- };
1537
- }
1538
-
1539
- /**
1540
- * `invoice.payment_failed` (#6034 FR-1). Arms dunning for the `User` matched
1541
- * by the invoice's Stripe customer id — the recorded state becomes
1542
- * `past_due`, `dunningArmedAt` is stamped once (never moved while the
1543
- * subscription stays failing), and `accessState` stays `granted`. This arm
1544
- * never revokes — and, just as importantly, never UN-revokes: it must never
1545
- * clear a subscription-level `canceled` recording, because it is only ever
1546
- * about ONE invoice, not the subscription's current status (code review
1547
- * finding, #6034). Stripe's Smart Retries schedule can still fire a queued
1548
- * retry's failure webhook for an invoice that predates a cancellation, with
1549
- * an `event.created` genuinely NEWER than the cancellation's own — which
1550
- * § D6's admission rule alone does not reject (rule 4 admits a strictly
1551
- * newer event unconditionally, by design, so that a genuine reactivation via
1552
- * `customer.subscription.updated` is never blocked). Only ANOTHER
1553
- * `customer.subscription.updated` may clear a canceled record.
1554
- *
1555
- * Never throws — the handler's "always 200 for a verified event" contract
1556
- * (NFR-1). Every rejection below returns BEFORE any query (§ D9).
1557
- */
1558
- async function armDunning(
1559
- request: FastifyRequest,
1560
- {
1561
- invoice,
1562
- eventId,
1563
- eventCreated,
1564
- eventIdPrefix,
1565
- }: {
1566
- invoice: InvoiceObject;
1567
- eventId: string;
1568
- eventCreated: number;
1569
- eventIdPrefix: string;
1570
- },
1571
- ): Promise<void> {
1572
- const subscriptionId = invoice.subscription;
1573
- if (typeof subscriptionId !== "string" || subscriptionId === "") {
1574
- request.log.info(
1575
- { eventIdPrefix, outcome: "not_a_subscription_invoice" },
1576
- "dunning: invoice.payment_failed carries no subscription — not a subscription invoice",
1577
- );
1578
- return;
1579
- }
1580
-
1581
- const customerId = invoice.customer;
1582
- if (typeof customerId !== "string" || customerId === "") {
1583
- request.log.warn(
1584
- { eventIdPrefix, outcome: "unresolvable_customer" },
1585
- "dunning: invoice.payment_failed has no resolvable customer",
1586
- );
1587
- return;
1588
- }
1589
-
1590
- const userId = await findSubscriberUserId(request, {
1591
- customerId,
1592
- eventIdPrefix,
1593
- });
1594
- if (!userId) return;
1595
-
1596
- await writeDunningRecord(request, {
1597
- userId,
1598
- subscriptionId,
1599
- eventId,
1600
- eventCreated,
1601
- eventIdPrefix,
1602
- computeCandidate: (current) => {
1603
- // A subscription already recorded `canceled` (by the SUBSCRIPTION-level
1604
- // authoritative `customer.subscription.updated` arm) is left untouched
1605
- // by an invoice-level signal — see this function's own doc comment.
1606
- if (current?.status === "canceled") return current;
1607
- return computeArmedEntry(current, { id: eventId, created: eventCreated });
1608
- },
1609
- });
1610
- }
1611
-
1612
- /**
1613
- * `customer.subscription.updated` (#6034 FR-2/FR-4). Maps the narrowed
1614
- * Stripe status (§ D3's `toSubscriptionLifecycleStatus`) onto the recorded
1615
- * lifecycle state:
1616
- *
1617
- * - `active` / `trialing` → § D7's clean recovery (both narrow to a
1618
- * recorded `status: "active"`; #6038's read shows nothing for it).
1619
- * - `past_due` (incl. `unpaid`, narrowed) → arms exactly as `armDunning` does.
1620
- * - `canceled` → § D5: grace runs from the FIRST failure, lazily evaluated,
1621
- * never scheduled.
1622
- *
1623
- * Never throws (NFR-1); every identifier is guarded before use (§ D9).
1624
- */
1625
- async function applySubscriptionStatus(
1626
- request: FastifyRequest,
1627
- {
1628
- subscription,
1629
- eventId,
1630
- eventCreated,
1631
- eventIdPrefix,
1632
- }: {
1633
- subscription: SubscriptionObject;
1634
- eventId: string;
1635
- eventCreated: number;
1636
- eventIdPrefix: string;
1637
- },
1638
- ): Promise<void> {
1639
- const customerId = subscription.customer;
1640
- if (typeof customerId !== "string" || customerId === "") {
1641
- request.log.warn(
1642
- { eventIdPrefix, outcome: "unresolvable_customer" },
1643
- "dunning: customer.subscription.updated has no resolvable customer",
1644
- );
1645
- return;
1646
- }
1647
-
1648
- const subscriptionId = subscription.id;
1649
- if (typeof subscriptionId !== "string" || subscriptionId === "") {
1650
- request.log.warn(
1651
- { eventIdPrefix, outcome: "unresolvable_subscription" },
1652
- "dunning: customer.subscription.updated has no resolvable subscription id",
1653
- );
1654
- return;
1655
- }
1656
-
1657
- // toSubscriptionLifecycleStatus's own default arm is already "canceled" —
1658
- // never an implied grant (§ D3) — so a non-string status maps the same
1659
- // conservative way rather than being silently ignored (§ D9).
1660
- const statusRaw = subscription.status;
1661
- const narrowedStatus =
1662
- typeof statusRaw === "string"
1663
- ? toSubscriptionLifecycleStatus(statusRaw)
1664
- : "canceled";
1665
-
1666
- const userId = await findSubscriberUserId(request, {
1667
- customerId,
1668
- eventIdPrefix,
1669
- });
1670
- if (!userId) return;
1671
-
1672
- if (narrowedStatus === "active" || narrowedStatus === "trialing") {
1673
- await writeDunningRecord(request, {
1674
- userId,
1675
- subscriptionId,
1676
- eventId,
1677
- eventCreated,
1678
- eventIdPrefix,
1679
- computeCandidate: () => ({
1680
- status: "active",
1681
- accessState: "granted",
1682
- dunningArmedAt: null,
1683
- accessRevokesAt: null,
1684
- lastEventAt: eventCreated,
1685
- lastEventId: eventId,
1686
- }),
1687
- });
1688
- return;
1689
- }
1690
-
1691
- if (narrowedStatus === "past_due") {
1692
- await writeDunningRecord(request, {
1693
- userId,
1694
- subscriptionId,
1695
- eventId,
1696
- eventCreated,
1697
- eventIdPrefix,
1698
- computeCandidate: (current) =>
1699
- computeArmedEntry(current, { id: eventId, created: eventCreated }),
1700
- });
1701
- return;
1702
- }
1703
-
1704
- // narrowedStatus === "canceled" — § D5's grace computation. The policy read
1705
- // never throws (dunning-policy.ts AC-3), so this can be awaited unguarded.
1706
- const policy = await dunningPolicyFor(currentSiteId());
1707
-
1708
- await writeDunningRecord(request, {
1709
- userId,
1710
- subscriptionId,
1711
- eventId,
1712
- eventCreated,
1713
- eventIdPrefix,
1714
- computeCandidate: (current) => {
1715
- const armedAtIso =
1716
- current?.dunningArmedAt ??
1717
- new Date(
1718
- resolveCancellationInstantMs(subscription, eventCreated),
1719
- ).toISOString();
1720
- const revokeAtMs =
1721
- Date.parse(armedAtIso) + policy.graceDays * 24 * 60 * 60 * 1000;
1722
- const revoked = Date.now() >= revokeAtMs;
1723
- return {
1724
- status: "canceled",
1725
- accessState: revoked ? "revoked" : "granted",
1726
- dunningArmedAt: armedAtIso,
1727
- accessRevokesAt: new Date(revokeAtMs).toISOString(),
1728
- lastEventAt: eventCreated,
1729
- lastEventId: eventId,
1730
- };
1731
- },
1732
- });
1733
- }
1734
-
1735
- /**
1736
- * The cancellation instant, taken from the verified event in § D5's order —
1737
- * `canceled_at` → `ended_at` → `event.created` → `Date.now()` — each
1738
- * accepted only when `Number.isFinite()` holds (Stripe epoch SECONDS; the
1739
- * final fallback is milliseconds already).
1740
- */
1741
- function resolveCancellationInstantMs(
1742
- subscription: SubscriptionObject,
1743
- eventCreatedSec: number,
1744
- ): number {
1745
- const candidatesSec = [
1746
- subscription.canceled_at,
1747
- subscription.ended_at,
1748
- eventCreatedSec,
1749
- ];
1750
- for (const candidate of candidatesSec) {
1751
- if (typeof candidate === "number" && Number.isFinite(candidate)) {
1752
- return candidate * 1000;
1753
- }
1754
- }
1755
- return Date.now();
1756
- }
1757
-
1758
- /**
1759
- * D10 — no matching `User` is a warn-and-continue, not an error. Matches
1760
- * `upsertBillingIdentity`'s pre-signup posture: a customer id with no linked
1761
- * `User` row is expected (a buyer who purchased without an account), so no
1762
- * `User` row is ever created here.
1763
- */
1764
- async function findSubscriberUserId(
1765
- request: FastifyRequest,
1766
- { customerId, eventIdPrefix }: { customerId: string; eventIdPrefix: string },
1767
- ): Promise<string | null> {
1768
- let user: { id: string } | null;
1769
- try {
1770
- user = await prisma.user.findUnique({
1771
- where: {
1772
- billingProvider_billingCustomerId: {
1773
- billingProvider: "stripe",
1774
- billingCustomerId: customerId,
1775
- },
1776
- },
1777
- select: { id: true },
1778
- });
1779
- } catch (err) {
1780
- request.log.error(
1781
- {
1782
- eventIdPrefix,
1783
- outcome: "subscriber_lookup_failed",
1784
- errName: err instanceof Error ? err.name : "UnknownError",
1785
- },
1786
- "dunning: subscriber lookup failed — continuing",
1787
- );
1788
- return null;
1789
- }
1790
-
1791
- if (!user) {
1792
- request.log.warn(
1793
- { eventIdPrefix, outcome: "no_subscriber_match" },
1794
- "dunning: no User matched this Stripe customer — pre-signup state, no write",
1795
- );
1796
- return null;
1797
- }
1798
-
1799
- return user.id;
1800
- }
1801
-
1802
- type DunningAdmission =
1803
- | { admit: true }
1804
- | { admit: false; outcome: "duplicate_event" | "stale_event" | "stale_tie" };
1805
-
1806
- /**
1807
- * A write is a DE-ESCALATION when it would move the entry toward LESS
1808
- * restriction relative to what is currently recorded: setting `status` to
1809
- * `active` (§ D7's `trialing`-collapses-to-`active` shape), clearing
1810
- * `accessRevokesAt`, or moving `accessState` from `revoked` to `granted`
1811
- * (§ D6 rule 3). All three are checked independently — the earlier draft
1812
- * keyed terminality on `accessState === "revoked"` alone, which left the
1813
- * in-grace cancellation (`status: "canceled"`, `accessState: "granted"`,
1814
- * `accessRevokesAt` non-null) unprotected (§ 9 SEC-03).
1815
- */
1816
- function isDeEscalation(current: DunningEntry, candidate: DunningEntry): boolean {
1817
- const statusRelaxed =
1818
- candidate.status === "active" && current.status !== "active";
1819
- const revokesAtCleared =
1820
- current.accessRevokesAt !== null && candidate.accessRevokesAt === null;
1821
- const accessStateRelaxed =
1822
- current.accessState === "revoked" && candidate.accessState === "granted";
1823
- return statusRelaxed || revokesAtCleared || accessStateRelaxed;
1824
- }
1825
-
1826
- /**
1827
- * § D6's five-rule admission ladder, folded to what actually needs checking:
1828
- * no current entry → admit (first event for this subscription); the SAME
1829
- * event id replayed → the durable twin of `hasSeen` (rule 1); a strictly
1830
- * OLDER event → stale (rule 2); an EQUAL-timestamp de-escalation → stale tie
1831
- * (rule 3, § D6's "terminal-state monotonicity" folded in — a de-escalating
1832
- * write is rejected at a tie regardless of which of the three terminal
1833
- * disjuncts made it terminal); anything else (a genuinely newer event,
1834
- * unconditionally per rule 4/5) → admit.
1835
- */
1836
- function admitDunningWrite(
1837
- current: DunningEntry | undefined,
1838
- candidate: DunningEntry,
1839
- event: { id: string; created: number },
1840
- ): DunningAdmission {
1841
- if (!current) return { admit: true };
1842
-
1843
- if (event.id === current.lastEventId) {
1844
- return { admit: false, outcome: "duplicate_event" };
1845
- }
1846
- if (event.created < current.lastEventAt) {
1847
- return { admit: false, outcome: "stale_event" };
1848
- }
1849
- if (event.created === current.lastEventAt && isDeEscalation(current, candidate)) {
1850
- return { admit: false, outcome: "stale_tie" };
1851
- }
1852
- return { admit: true };
1853
- }
1854
-
1855
- function parseDunningRecord(value: unknown): DunningRecord {
1856
- const obj = value as { subscriptions?: unknown } | null | undefined;
1857
- const subscriptions =
1858
- obj &&
1859
- typeof obj === "object" &&
1860
- obj.subscriptions &&
1861
- typeof obj.subscriptions === "object" &&
1862
- !Array.isArray(obj.subscriptions)
1863
- ? (obj.subscriptions as Record<string, DunningEntry>)
1864
- : {};
1865
- return { v: 1, subscriptions };
1866
- }
1867
-
1868
- /**
1869
- * The map cap (§ D2) — evicts the oldest SETTLED entries (`status: "active"`,
1870
- * `accessState: "granted"`) first, never an entry still being dunned, so a
1871
- * per-event read-and-rewrite never grows unbounded with a customer's whole
1872
- * subscription history.
1873
- */
1874
- function applyCandidateWithCap(
1875
- record: DunningRecord,
1876
- subscriptionId: string,
1877
- candidate: DunningEntry,
1878
- ): DunningRecord {
1879
- const subscriptions: Record<string, DunningEntry> = {
1880
- ...record.subscriptions,
1881
- [subscriptionId]: candidate,
1882
- };
1883
-
1884
- let overflow = Object.keys(subscriptions).length - DUNNING_MAX_SUBSCRIPTIONS;
1885
- if (overflow <= 0) {
1886
- return { v: 1, subscriptions };
1887
- }
1888
-
1889
- const evictionOrder = Object.keys(subscriptions)
1890
- .filter((key) => {
1891
- const entry = subscriptions[key]!;
1892
- return entry.status === "active" && entry.accessState === "granted";
1893
- })
1894
- .sort((a, b) => subscriptions[a]!.lastEventAt - subscriptions[b]!.lastEventAt);
1895
-
1896
- for (const key of evictionOrder) {
1897
- if (overflow <= 0) break;
1898
- delete subscriptions[key];
1899
- overflow -= 1;
1900
- }
1901
-
1902
- return { v: 1, subscriptions };
1903
- }
1904
-
1905
- /**
1906
- * The shared write primitive (§ D6). Reads the FULL record, applies the
1907
- * admission rule, and writes back a compare-and-swap whose `where` restates
1908
- * BOTH `updatedAt` AND the observed `value` (read-set ≡ CAS-set — NFR-9;
1909
- * `updatedAt` alone lets two writes inside the same millisecond silently
1910
- * overwrite each other, § 9 SEC-07). Bounded at `DUNNING_WRITE_MAX_ATTEMPTS`
1911
- * — an honest `write_conflict` log beats an unbounded spin on an access
1912
- * decision. Never throws (NFR-1) — the outer `catch` is the same
1913
- * never-throw contract every other helper in this file carries.
1914
- */
1915
- async function writeDunningRecord(
1916
- request: FastifyRequest,
1917
- {
1918
- userId,
1919
- subscriptionId,
1920
- eventId,
1921
- eventCreated,
1922
- eventIdPrefix,
1923
- computeCandidate,
1924
- }: {
1925
- userId: string;
1926
- subscriptionId: string;
1927
- eventId: string;
1928
- eventCreated: number;
1929
- eventIdPrefix: string;
1930
- computeCandidate: (current: DunningEntry | undefined) => DunningEntry;
1931
- },
1932
- ): Promise<void> {
1933
- const subscriptionIdPrefix = subscriptionId.substring(0, 8);
1934
-
1935
- try {
1936
- for (let attempt = 1; attempt <= DUNNING_WRITE_MAX_ATTEMPTS; attempt++) {
1937
- const row = await prisma.userData.findUnique({
1938
- where: { userId_key: { userId, key: DUNNING_USER_DATA_KEY } },
1939
- select: { value: true, updatedAt: true },
1940
- });
1941
-
1942
- const observedValue: unknown = row ? row.value : null;
1943
- const record = parseDunningRecord(observedValue);
1944
- const current = record.subscriptions[subscriptionId];
1945
- const candidate = computeCandidate(current);
1946
-
1947
- const admission = admitDunningWrite(current, candidate, {
1948
- id: eventId,
1949
- created: eventCreated,
1950
- });
1951
- if (!admission.admit) {
1952
- request.log.info(
1953
- { eventIdPrefix, subscriptionIdPrefix, outcome: admission.outcome },
1954
- "dunning: event not admitted — record unchanged",
1955
- );
1956
- return;
1957
- }
1958
-
1959
- const nextRecord = applyCandidateWithCap(record, subscriptionId, candidate);
1960
- const nextValue = nextRecord as unknown as Prisma.InputJsonValue;
1961
-
1962
- if (!row) {
1963
- try {
1964
- await prisma.userData.create({
1965
- data: { userId, key: DUNNING_USER_DATA_KEY, value: nextValue },
1966
- });
1967
- request.log.info(
1968
- {
1969
- eventIdPrefix,
1970
- subscriptionIdPrefix,
1971
- outcome: "written",
1972
- status: candidate.status,
1973
- },
1974
- "dunning: record created",
1975
- );
1976
- return;
1977
- } catch (err) {
1978
- if (isUniqueViolation(err)) {
1979
- // Another delivery won the create race — re-read and retry.
1980
- continue;
1981
- }
1982
- throw err;
1983
- }
1984
- }
1985
-
1986
- const { count } = await prisma.userData.updateMany({
1987
- where: {
1988
- userId,
1989
- key: DUNNING_USER_DATA_KEY,
1990
- updatedAt: row.updatedAt,
1991
- value: { equals: observedValue as Prisma.InputJsonValue },
1992
- },
1993
- data: { value: nextValue },
1994
- });
1995
-
1996
- if (count > 0) {
1997
- request.log.info(
1998
- {
1999
- eventIdPrefix,
2000
- subscriptionIdPrefix,
2001
- outcome: "written",
2002
- status: candidate.status,
2003
- },
2004
- "dunning: record updated",
2005
- );
2006
- return;
2007
- }
2008
- // count === 0 — a concurrent writer moved the row. Re-read and retry.
2009
- }
2010
-
2011
- request.log.error(
2012
- { eventIdPrefix, subscriptionIdPrefix, outcome: "write_conflict" },
2013
- "dunning: record write exhausted its retries — continuing",
2014
- );
2015
- } catch (err) {
2016
- request.log.error(
2017
- {
2018
- eventIdPrefix,
2019
- subscriptionIdPrefix,
2020
- outcome: "stamp_failed",
2021
- errName: err instanceof Error ? err.name : "UnknownError",
2022
- },
2023
- "dunning: record write failed — continuing",
2024
- );
2025
- }
2026
- }