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,2073 +0,0 @@
1
- /**
2
- * NOT marked `oss: false` (D-48/#5366 escalation — see
3
- * `routes/project-listings/me.ts`'s header comment): imported by
4
- * `routes/project-listings/{start,patch-draft,submit,public,me}.ts`, each of
5
- * which ships unconditionally because `routes/project-listings/index.ts`'s
6
- * multi-tenant literal `import()` forces it. Registration of the routes that
7
- * call into this service stays gated (`isModuleEnabled("signal-collectors")`).
8
- *
9
- * @file project-listings.ts
10
- * @description The founder's-application-row service (#4998, reshaped by
11
- * #5036) — writes, reads, and transitions `ProjectListing` (ADR 0009 D3
12
- * service-layer convention, mirroring `lead-routing.ts` and
13
- * `waitlist-dashboard.ts`).
14
- *
15
- * The single anonymous create became THREE operations when the application
16
- * became a ten-step form that saves as it goes (#5036 D1):
17
- *
18
- * start name + email + consent -> a `draft` row and a resume token
19
- * patch merges a partial payload; asserts no completeness
20
- * submit validates the WHOLE application, `draft` -> `requested`
21
- *
22
- * Validation therefore moved from write-time to submit-time, and that is why
23
- * every application field is nullable on the row: a half-filled draft is a
24
- * legitimate row, and only `submit` asserts it is finished.
25
- *
26
- * `submitProjectListingDraft` calls `routeLead` (kind `submit`, source
27
- * `projects-apply`) for the Lead write — never a duplicate Lead-shaped insert.
28
- * The Lead is written at SUBMIT rather than at start: the founder's contact
29
- * details are already captured on the listing row itself at step one, so a
30
- * Lead at step one adds no capture, and what it DOES add is an operator
31
- * notification email per abandoned first step on an anonymous route (PR #5042
32
- * security review, finding 4). Every tenant read/write
33
- * is scoped by `siteId` (`request.tenant.workspaceId`) — there is no
34
- * client-supplied site id on any tenant route. `waitlistCount` joins THROUGH
35
- * `experimentId` (`WaitlistExperiment.id` -> `.key` -> `WaitlistScore.experimentKey`,
36
- * scoped by `siteId`), 0 when a listing carries no `experimentKey`.
37
- *
38
- * PII boundary: this module never logs `founderEmail`, `founderName`, or
39
- * `questions` — the same discipline `lead-routing.ts` documents. The resume
40
- * token is never logged either, at any level: it is the ONLY credential on
41
- * the anonymous draft surface.
42
- */
43
-
44
- import { createHash, randomBytes } from "node:crypto";
45
-
46
- import type { Prisma } from "@working-theory/database";
47
- import {
48
- DEFAULT_WORKSPACE_SLUG,
49
- resolveSentinelWorkspaceRow,
50
- } from "@working-theory/database/tenancy";
51
- import { logger } from "@working-theory/observability";
52
- import {
53
- clampWindowDays,
54
- buildProjectListingDraftPatchSchema,
55
- buildProjectListingSubmitSchema,
56
- composeAddressLine,
57
- composeFounderName,
58
- flowAddressValueSchema,
59
- flowConfigSchema,
60
- listicleSiteAnswerQuestions,
61
- listingProfile,
62
- publicSiteAnswers,
63
- withListicleQuestions,
64
- LISTING_DIRECTORY_MAX_ENTRIES,
65
- LISTING_ENTRY_TYPE_DEFAULT,
66
- PROJECT_LISTING_CONCURRENT_LIMIT,
67
- PROJECT_LISTING_NON_TERMINAL_STATUSES,
68
- RESERVED_FLOW_SLUGS,
69
- } from "@working-theory/validation";
70
- import type {
71
- FlowAddressValue,
72
- FlowConfig,
73
- ListingDirectoryResponse,
74
- ListingEntryPublic,
75
- ListingSiteAnswersConfig,
76
- ProjectListing,
77
- ProjectListingDraftPatchInput,
78
- ProjectListingFaqs,
79
- ProjectListingPublic,
80
- ProjectListingQuestions,
81
- ProjectListingStartInput,
82
- } from "@working-theory/validation";
83
-
84
- import { prisma } from "../lib/prisma.js";
85
-
86
- import {
87
- consentConfigForSite,
88
- MAX_CONSENT_KEYS,
89
- recordConsent,
90
- recordLegacyConsent,
91
- requiredConsentUnmet,
92
- } from "./consent.js";
93
- import { routeLead, type SourceMeta } from "./lead-routing.js";
94
- import { listingConfigFor } from "./listing-config.js";
95
-
96
- // ─── The computed lifecycle state ───────────────────────────────────────────
97
-
98
- type ProjectListingStatus = ProjectListing["status"];
99
-
100
- /**
101
- * Resolve a row's LIFECYCLE status from its STORED status (#5033 D3).
102
- *
103
- * `closed` is the one state nothing writes. An `active` listing whose window
104
- * end has passed reads `closed`, here, on every read, with no job having run.
105
- * Storing it instead would need a scheduler whose failure leaves expired
106
- * listings publicly open — a silent, wrong-way failure. This makes that
107
- * unrepresentable.
108
- *
109
- * A FEATURED row is exempt (#5036 D6b). The operator's own products become
110
- * listing rows carrying `featured: true`, and such a row is not a time-boxed
111
- * validation experiment: it has no meaningful window and must not vanish from
112
- * the shelf because a date passed. Its `windowEndsAt` may be null, and it
113
- * reads `active` either way.
114
- *
115
- * A null window on a NON-featured `active` row is an ERROR, not a licence to
116
- * stay open forever: every real listing is time-boxed by design, and the whole
117
- * point of computing `closed` rather than storing it is that an expired
118
- * listing cannot linger. It is logged and read `closed` — failing toward the
119
- * closed shelf rather than toward a publicly-open listing nothing bounds.
120
- * `draft`, `requested` and `rejected` rows legitimately carry no window and
121
- * are not touched by any of this.
122
- */
123
- export function computeListingStatus(
124
- storedStatus: string,
125
- windowEndsAt: Date | null,
126
- now: Date,
127
- featured: boolean,
128
- ): ProjectListingStatus {
129
- if (storedStatus !== "active") return storedStatus as ProjectListingStatus;
130
- if (featured) return "active";
131
- if (windowEndsAt === null) {
132
- logger.error(
133
- { kind: "active_listing_without_window" },
134
- "[project-listings] a non-featured active listing carries no window end; reading it closed",
135
- );
136
- return "closed";
137
- }
138
- return windowEndsAt.getTime() <= now.getTime() ? "closed" : "active";
139
- }
140
-
141
- // ─── Slug derivation (#5033 D2) ─────────────────────────────────────────────
142
-
143
- /** The `name`-derived slug's length cap. */
144
- const SLUG_MAX_LENGTH = 48;
145
-
146
- /** The slug a name with no alphanumeric content falls back to before suffixing. */
147
- const SLUG_FALLBACK = "listing";
148
-
149
- /**
150
- * Derive a slug from a listing `name`: lowercase, every non-alphanumeric run
151
- * to a single hyphen, trimmed of leading/trailing hyphens, truncated to 48.
152
- * A name carrying no alphanumerics at all (the payload allows it — `name` is
153
- * only bounded by length) falls back to `listing`, which the site-scoped
154
- * suffixing below then disambiguates like any other collision.
155
- */
156
- export function deriveListingSlug(name: string): string {
157
- const base = name
158
- .toLowerCase()
159
- .replace(/[^a-z0-9]+/g, "-")
160
- .replace(/^-+|-+$/g, "")
161
- .slice(0, SLUG_MAX_LENGTH)
162
- .replace(/-+$/, "");
163
- return base.length > 0 ? base : SLUG_FALLBACK;
164
- }
165
-
166
- /**
167
- * The most same-prefix slugs one create will read before giving up.
168
- *
169
- * The collision read is a prefix scan, and `base` derives from a fully
170
- * caller-controlled `name` on an ANONYMOUS route — a one-character name makes
171
- * the prefix match most of the site's slugs, and every accepted application
172
- * adds another row to that family. Unbounded, the cost of a create would grow
173
- * with the number of listings an attacker had already filed. Bounded, a
174
- * pathological family degrades to the same `slug_taken` 409 a genuine race
175
- * already produces, rather than to an ever-slower table scan.
176
- */
177
- const SLUG_COLLISION_SCAN_LIMIT = 200;
178
-
179
- /**
180
- * The first free slug for `base` on this site. Uniqueness is already scoped
181
- * `@@unique([siteId, slug])`, so the suffix is too: a second "Atlas" on this
182
- * site becomes `atlas-2` even if `atlas` is taken on another.
183
- *
184
- * Two concurrent creates of the same name can still both resolve the same
185
- * free slug and race to the insert; the loser hits the unique constraint and
186
- * is reported as `slug_taken`, exactly as it was when the client supplied the
187
- * slug itself.
188
- *
189
- * #8661 D4 — a listing's slug becomes its diagnostic flow's slug on approval,
190
- * so the standard magnets' reserved slugs are treated as taken: a project
191
- * named "Contact" is stored at `contact-2`.
192
- */
193
- async function firstFreeSlug(siteId: string, base: string): Promise<string> {
194
- const rows = await prisma.projectListing.findMany({
195
- where: { siteId, slug: { startsWith: base } },
196
- select: { slug: true },
197
- take: SLUG_COLLISION_SCAN_LIMIT,
198
- });
199
- const taken = new Set<string | null>([...RESERVED_FLOW_SLUGS, ...rows.map((r) => r.slug)]);
200
- if (!taken.has(base)) return base;
201
-
202
- // Bounded by `taken.size + 1` iterations — one of the first `n` candidates
203
- // is necessarily free.
204
- let suffix = 2;
205
- while (taken.has(`${base}-${suffix}`)) suffix += 1;
206
- return `${base}-${suffix}`;
207
- }
208
-
209
- // ─── Row shape ──────────────────────────────────────────────────────────────
210
-
211
- const PROJECT_LISTING_SELECT = {
212
- id: true,
213
- siteId: true,
214
- leadId: true,
215
- slug: true,
216
- name: true,
217
- oneLiner: true,
218
- problem: true,
219
- solution: true,
220
- url: true,
221
- product: true,
222
- commitment: true,
223
- teamComposition: true,
224
- faqs: true,
225
- anythingElse: true,
226
- address: true,
227
- // #5279 — the structured parts beside the display string.
228
- addressLine1: true,
229
- addressLine2: true,
230
- addressCity: true,
231
- addressRegion: true,
232
- addressPostalCode: true,
233
- addressCountry: true,
234
- questions: true,
235
- // #5285 — the site's own answers, and the window the applicant asked for.
236
- // `windowDays` rides the select because `submit` re-validates the assembled
237
- // application, and `requestedWindowDays` is one of its fields now.
238
- siteAnswers: true,
239
- windowDays: true,
240
- founderName: true,
241
- // #5407 — the name parts beside the composed display string, the phone, and
242
- // the resume-link verification stamp.
243
- founderFirstName: true,
244
- founderLastName: true,
245
- founderEmail: true,
246
- founderPhone: true,
247
- emailVerifiedAt: true,
248
- founderCompany: true,
249
- headline: true,
250
- logoMarkUrl: true,
251
- logoWordmarkUrl: true,
252
- featured: true,
253
- status: true,
254
- consentAt: true,
255
- decidedAt: true,
256
- decidedBy: true,
257
- issueUrl: true,
258
- experimentKey: true,
259
- windowEndsAt: true,
260
- createdAt: true,
261
- updatedAt: true,
262
- } as const satisfies Prisma.ProjectListingSelect;
263
-
264
- type ProjectListingRow = Prisma.ProjectListingGetPayload<{
265
- select: typeof PROJECT_LISTING_SELECT;
266
- }>;
267
-
268
- /**
269
- * The structured address parts of a row, or null (#5279).
270
- *
271
- * Exported because `project-listing-decision.ts` renders the same row shape
272
- * and must answer the same way — two readers guessing separately at what
273
- * "has parts" means is exactly how one of them starts emitting a half-filled
274
- * object.
275
- *
276
- * The rule is the composite's REQUIRED set: the five non-optional parts are
277
- * all present, or there are no parts. `addressLine2` is optional in the
278
- * fieldset, so it rides along when present and is simply absent when not. A
279
- * row written before #5279 has all six columns null and answers null here —
280
- * never a partial object reconstructed from `address`, which nothing in this
281
- * repo parses.
282
- *
283
- * `.safeParse` rather than a cast: these are six nullable TEXT columns, and
284
- * the emitted object must satisfy `flowAddressValueSchema` or the row fails
285
- * its own response schema downstream. A shape that somehow does not (a
286
- * `country` that is not an alpha-2 code, say) answers null rather than
287
- * putting an invalid address on the PUBLIC read.
288
- */
289
- export function addressPartsFromRow(row: {
290
- addressLine1: string | null;
291
- addressLine2: string | null;
292
- addressCity: string | null;
293
- addressRegion: string | null;
294
- addressPostalCode: string | null;
295
- addressCountry: string | null;
296
- }): FlowAddressValue | null {
297
- if (
298
- row.addressLine1 === null ||
299
- row.addressCity === null ||
300
- row.addressRegion === null ||
301
- row.addressPostalCode === null ||
302
- row.addressCountry === null
303
- ) {
304
- return null;
305
- }
306
- const parsed = flowAddressValueSchema.safeParse({
307
- addressLine1: row.addressLine1,
308
- ...(row.addressLine2 !== null && { addressLine2: row.addressLine2 }),
309
- city: row.addressCity,
310
- region: row.addressRegion,
311
- postalCode: row.addressPostalCode,
312
- country: row.addressCountry,
313
- });
314
- return parsed.success ? parsed.data : null;
315
- }
316
-
317
- /**
318
- * The site-answers object of a row, or null (#5285).
319
- *
320
- * Exported for the same reason `addressPartsFromRow` is: the operator's
321
- * decision payload renders the same row shape and must answer the same way.
322
- *
323
- * The column is `Json?`, so Prisma types it as `JsonValue` — an array, a
324
- * number and a string all satisfy it. Only ever written by
325
- * `draftUpdateData` from a body the site's own declarations validated, so a
326
- * row holding anything else is a row somebody wrote around this service.
327
- * A non-object answers null rather than being cast: a value of the wrong
328
- * SHAPE reaching the response schema would fail the whole read, and one
329
- * malformed row must not take a listing page down.
330
- *
331
- * Non-string members are dropped for the same reason — the store is
332
- * `Record<string, string>`, and what is handed back has to actually be one.
333
- */
334
- export function siteAnswersFromRow(value: Prisma.JsonValue | null): Record<string, string> | null {
335
- if (value === null || typeof value !== "object" || Array.isArray(value)) return null;
336
- return Object.fromEntries(
337
- Object.entries(value).filter(
338
- (entry): entry is [string, string] => typeof entry[1] === "string",
339
- ),
340
- );
341
- }
342
-
343
- /**
344
- * `now` is passed rather than read inside so one read renders every row of a
345
- * list against a single instant. `featuredEnabled` is the site's config
346
- * switch (#5033 D6): where a site has not enabled a featured shelf, the flag
347
- * never surfaces. The tenant dashboard passes `true` — an operator manages
348
- * the flag and must see what they set.
349
- */
350
- function toResponseRow(
351
- row: ProjectListingRow,
352
- waitlistCount: number,
353
- now: Date,
354
- featuredEnabled: boolean,
355
- ): ProjectListing {
356
- return {
357
- id: row.id,
358
- siteId: row.siteId,
359
- leadId: row.leadId,
360
- slug: row.slug,
361
- name: row.name,
362
- headline: row.headline,
363
- oneLiner: row.oneLiner,
364
- problem: row.problem,
365
- solution: row.solution,
366
- url: row.url,
367
- product: row.product as ProjectListing["product"],
368
- commitment: row.commitment as ProjectListing["commitment"],
369
- teamComposition: row.teamComposition as ProjectListing["teamComposition"],
370
- faqs: row.faqs as unknown as ProjectListingFaqs | null,
371
- anythingElse: row.anythingElse,
372
- address: row.address,
373
- addressParts: addressPartsFromRow(row),
374
- founderName: row.founderName,
375
- founderFirstName: row.founderFirstName,
376
- founderLastName: row.founderLastName,
377
- founderEmail: row.founderEmail,
378
- founderPhone: row.founderPhone,
379
- // #5407 — the operator's verification filter at review. Null means "no
380
- // opening of the resume link recorded", never "verification failed".
381
- emailVerifiedAt: row.emailVerifiedAt ? row.emailVerifiedAt.toISOString() : null,
382
- founderCompany: row.founderCompany,
383
- questions: row.questions as unknown as ProjectListingQuestions | null,
384
- logoMarkUrl: row.logoMarkUrl,
385
- logoWordmarkUrl: row.logoWordmarkUrl,
386
- // #5285 — UNFILTERED here, deliberately. This row shape serves the tenant
387
- // dashboard and the founder's own draft read, both of which are entitled
388
- // to every answer. The PUBLIC read is the one that must not carry an
389
- // `operator-only` answer, and it narrows this through `publicSiteAnswers`
390
- // in `publicProjectListings` — one filter, on the one read that publishes.
391
- siteAnswers: siteAnswersFromRow(row.siteAnswers),
392
- featured: featuredEnabled && row.featured,
393
- // The row's OWN flag decides the closed exemption (#5036 D6b), not the
394
- // site's `featuredEnabled` switch: that switch governs whether the flag
395
- // SURFACES on a read, not whether the listing is time-boxed.
396
- status: computeListingStatus(row.status, row.windowEndsAt, now, row.featured),
397
- consentAt: row.consentAt.toISOString(),
398
- decidedAt: row.decidedAt ? row.decidedAt.toISOString() : null,
399
- decidedBy: row.decidedBy,
400
- issueUrl: row.issueUrl,
401
- experimentKey: row.experimentKey,
402
- windowEndsAt: row.windowEndsAt ? row.windowEndsAt.toISOString() : null,
403
- waitlistCount,
404
- createdAt: row.createdAt.toISOString(),
405
- updatedAt: row.updatedAt.toISOString(),
406
- };
407
- }
408
-
409
- /**
410
- * `waitlistCount` per row, keyed by `experimentKey`.
411
- *
412
- * Since #5036 D6d the listing stores the experiment's KEY rather than its id,
413
- * and that key is the same string `WaitlistScore.experimentKey` holds — so the
414
- * `WaitlistExperiment` read that existed purely to translate one into the
415
- * other is gone. One `WaitlistScore.count` per DISTINCT key remains, bounded
416
- * by the small number of distinct experiments a dashboard page carries rather
417
- * than by row count (`waitlist-dashboard.ts`'s "one read across every returned
418
- * row" discipline).
419
- */
420
- async function attachWaitlistCounts(
421
- siteId: string,
422
- rows: readonly Pick<ProjectListingRow, "experimentKey">[],
423
- ): Promise<Map<string, number>> {
424
- const experimentKeys = [
425
- ...new Set(rows.map((r) => r.experimentKey).filter((v): v is string => v != null)),
426
- ];
427
- if (experimentKeys.length === 0) return new Map();
428
-
429
- const counts = new Map<string, number>();
430
- await Promise.all(
431
- experimentKeys.map(async (experimentKey) => {
432
- // fence: workspaceId === the scope id this query already filters siteId by
433
- // (workspace_site_agree CHECK, 20260922120000_tenancy_fence). Filtering the
434
- // CONSTRAINED column makes the scope correct by construction; the format
435
- // CHECK makes a raw alias match nothing rather than by accident.
436
- //
437
- // What that id IS depends on the caller, and only two of the six are
438
- // route-resolved: `listProjectListings` and `getProjectListing` receive
439
- // `tenant.workspaceId`, so for them this is an isolation control.
440
- // `listMyProjectListings` and the two `publicProjectListings` call sites
441
- // pass a ProjectListing row's OWN `siteId`, so for them it is a
442
- // CONSISTENCY control — the count agrees with the row it is reported
443
- // against — exactly as `project-listing-decision.ts#waitlistCountFor`
444
- // spells out (#6258 § 1.6 / § 5 D8, security review L-2).
445
- const count = await prisma.waitlistScore.count({
446
- where: { siteId, workspaceId: siteId, experimentKey },
447
- });
448
- counts.set(experimentKey, count);
449
- }),
450
- );
451
- return counts;
452
- }
453
-
454
- function waitlistCountFor(
455
- row: Pick<ProjectListingRow, "experimentKey">,
456
- counts: Map<string, number>,
457
- ): number {
458
- return row.experimentKey ? (counts.get(row.experimentKey) ?? 0) : 0;
459
- }
460
-
461
- // ─── The founder's key (#5036 D7) ──────────────────────────────────────────
462
-
463
- /**
464
- * Normalize the email a founder is counted under.
465
- *
466
- * Trim and lowercase, so `Ada@Example.com ` and `ada@example.com` are one
467
- * founder rather than two. Postgres text equality is case-sensitive, so
468
- * without this the concurrent-listing limit is evaded by holding down shift.
469
- *
470
- * Deliberately NOT stripping plus-tags: `ada+two@example.com` still counts as
471
- * a different founder. Plus-addressing is a legitimate, widely-used feature
472
- * and treating it as evasion would refuse real applicants; closing that gap
473
- * properly needs a verified email, which this anonymous surface does not have.
474
- */
475
- function normalizeFounderEmail(email: string): string {
476
- return email.trim().toLowerCase();
477
- }
478
-
479
- /**
480
- * How long an unsubmitted draft occupies one of a founder's two slots
481
- * (#5036 D7).
482
- *
483
- * Drafts MUST count, or the limit is evaded by never submitting. But
484
- * `founderEmail` is unverified on an anonymous surface, so anyone can open a
485
- * draft in a stranger's name — and a draft that counted forever would let two
486
- * anonymous requests lock a named founder out of ever applying, with no
487
- * operator remedy (there is no route that deletes a listing; PR #5042 security
488
- * review, finding 1).
489
- *
490
- * Bounding the window keeps D7's intent — an application in progress holds a
491
- * slot, so not submitting evades nothing — while making that lockout expire on
492
- * its own. Fourteen days is far longer than a ten-step form takes and far
493
- * shorter than "forever".
494
- *
495
- * This bounds the QUOTA impact, not retention: an abandoned draft still holds
496
- * the founder's name, email and address in the table. A retention sweep is a
497
- * separate unit and is not in this change.
498
- */
499
- const DRAFT_HOLDS_A_SLOT_DAYS = 14;
500
-
501
- // ─── The resume token (#5036 D1) ───────────────────────────────────────────
502
-
503
- /**
504
- * The token's entropy, in bytes. 256 bits — the same floor the repo's other
505
- * capability tokens carry, and far beyond guessing at any request rate the
506
- * `leadsScope` rate limiter permits.
507
- */
508
- const RESUME_TOKEN_BYTES = 32;
509
-
510
- /**
511
- * Mint an opaque resume token. Returned to the caller EXACTLY once, at
512
- * `start`: only its digest is stored, so the server cannot hand it back a
513
- * second time and an attacker who reads the table still cannot present one.
514
- */
515
- function mintResumeToken(): string {
516
- return randomBytes(RESUME_TOKEN_BYTES).toString("base64url");
517
- }
518
-
519
- /**
520
- * What the column holds. A plain sha-256 with no salt and no stretching is
521
- * correct here and a KDF would not be: the input is 256 bits of CSPRNG output,
522
- * not a human-chosen secret, so there is no dictionary to precompute and
523
- * nothing for a work factor to slow down.
524
- */
525
- function hashResumeToken(token: string): string {
526
- return createHash("sha256").update(token).digest("hex");
527
- }
528
-
529
- // ─── The email-verification nonce (#5407) ──────────────────────────────────
530
-
531
- /**
532
- * Mint the nonce that PROVES the founder read mail sent to `founderEmail`.
533
- *
534
- * WHY A SECOND CREDENTIAL EXISTS AT ALL, since the obvious design is to reuse
535
- * the resume token the emailed link already carries. That design cannot work:
536
- * `start` returns the resume token in its own 201 body, to whoever posted the
537
- * form. The emailed link is a SECOND COPY of a credential the applicant
538
- * already holds, so keying verification on it would let two HTTP calls — open
539
- * a draft under a stranger's address, take the token out of the response,
540
- * present it back — forge the stamp with no mailbox involved. Found by this
541
- * change's own security review, before it shipped.
542
- *
543
- * This nonce closes that because of where it does NOT go. It is minted here,
544
- * digested into `emailVerifyNonceHash`, and returned to exactly one caller —
545
- * `start`, which hands it to `sendListingResumeLink` and to nothing else. It
546
- * is in no response body, no log line, and no browser that filled the form.
547
- * The only way to hold it is to have read the email.
548
- *
549
- * Same 256 bits as the resume token, for the same reason.
550
- */
551
- function mintVerifyNonce(): string {
552
- return randomBytes(RESUME_TOKEN_BYTES).toString("base64url");
553
- }
554
-
555
- /**
556
- * What `emailVerifyNonceHash` holds. The same plain sha-256 as
557
- * `hashResumeToken`, for the same reason — the input is CSPRNG output, not a
558
- * human-chosen secret — and kept as its own function rather than aliased so
559
- * no call site has to read "resume token" while meaning the nonce.
560
- */
561
- function hashVerifyNonce(nonce: string): string {
562
- return createHash("sha256").update(nonce).digest("hex");
563
- }
564
-
565
- /**
566
- * Resolve the ONE draft a token grants access to (#5036 D1).
567
- *
568
- * Both the id and the token's digest are in the `where`, so a valid token
569
- * presented against a different listing's id resolves to nothing: a token is
570
- * bound to one listing and grants access to no other. `status: "draft"` is in
571
- * there too — `submit` clears the digest, so a token that leaks after
572
- * submission is inert twice over.
573
- *
574
- * The comparison is an equality test on a 256-bit digest inside Postgres.
575
- * There is no application-level secret compare to make constant-time, and no
576
- * practical timing signal in matching digests of that width.
577
- */
578
- async function findDraftByToken(
579
- id: string,
580
- resumeToken: string,
581
- ): Promise<ProjectListingRow | null> {
582
- return prisma.projectListing.findFirst({
583
- where: { id, status: "draft", resumeTokenHash: hashResumeToken(resumeToken) },
584
- select: PROJECT_LISTING_SELECT,
585
- });
586
- }
587
-
588
- // ─── start (POST, anonymous) ────────────────────────────────────────────────
589
-
590
- /**
591
- * `start` has one failure mode of its own to report (#5275): a `consents`
592
- * map that does not GRANT every purpose the site's registry marks required —
593
- * declined, or simply absent. The legacy literal says the founder consented;
594
- * a `false` (or nothing) beside it for the required purpose says they did
595
- * not — the body contradicts itself, and the row must not be created on it
596
- * (it would go on to publish the founder's address against a recorded
597
- * decline, or with no evidence row at all). An oversized map is the same
598
- * 400. Everything else is as before: the site's config falls back to the
599
- * platform defaults rather than erroring, and a Prisma failure is a 500
600
- * through the framework. The Lead write — the step that used to give this
601
- * operation a `persist_failed`/`config_missing` surface — moved to `submit`.
602
- */
603
- export type StartProjectListingDraftResult =
604
- | {
605
- ok: true;
606
- id: string;
607
- resumeToken: string;
608
- /**
609
- * #5407 — the email-verification nonce, for the RESUME-EMAIL BUILDER
610
- * and for nothing else.
611
- *
612
- * A sibling of the result rather than a field of anything the route
613
- * hands to a response schema, deliberately (lesson 05): `start`'s 201
614
- * body is `projectListingStartResponseSchema`, which is `.strict()` and
615
- * carries `id` and `resumeToken` only. That route's request and
616
- * response shapes are a declared hard floor and are unchanged — this
617
- * value reaches `sendListingResumeLink` from the route's local
618
- * variable and never touches the wire.
619
- */
620
- verifyNonce: string;
621
- }
622
- | { ok: false; error: { kind: "invalid_input"; message: string } }
623
- // #6203 — the resolved `siteId` names no workspace this database holds.
624
- // Distinct from `invalid_input` (a body problem): this is a server-side
625
- // tenancy misconfiguration, and the route answers 503, never 400.
626
- | { ok: false; error: { kind: "tenant_unresolved"; message: string } };
627
-
628
- /**
629
- * Resolves an ALREADY-RESOLVED `siteId` (never a caller-supplied string — see
630
- * `startProjectListingDraft`'s own header) to its workspace id (#6203).
631
- *
632
- * Mirrors `apps/api/src/lib/site.ts`'s `resolveSiteWorkspaceId()` — the SAME
633
- * two-branch alias mapping the #6203 migration's own backfill `CASE`
634
- * encodes: the literal alias `"default"` resolves to the seeded sentinel
635
- * workspace IFF that row exists and hangs off the sentinel Organization;
636
- * any other alias resolves only by exact `workspaces.id` equality. Kept
637
- * LOCAL and PARAMETERIZED rather than reusing `resolveSiteWorkspaceId()`
638
- * directly: that function is hardwired to `currentSiteId()`
639
- * (`AILK_SITE_ID`), while a `ProjectListing`'s `siteId` can legitimately
640
- * name a DIFFERENT site under a multi-key deployment
641
- * (`listing-config.ts#siteIdForPublicKey`'s `SiteListingConfig.publicKey`
642
- * path) — the workspace stamped here must correspond to the SAME site the
643
- * row's own `siteId` already names, not the deployment's default. NOT
644
- * memoized (unlike `resolveSiteWorkspaceId()`): a different `siteId` per
645
- * call means the sentinel-only cache that function keeps would be wrong
646
- * here.
647
- */
648
- async function resolveWorkspaceIdForSite(siteId: string): Promise<string | null> {
649
- if (siteId === DEFAULT_WORKSPACE_SLUG) {
650
- const row = await resolveSentinelWorkspaceRow(prisma);
651
- return row?.id ?? null;
652
- }
653
- const row = await prisma.workspace.findUnique({ where: { id: siteId } });
654
- return row ? siteId : null;
655
- }
656
-
657
- /**
658
- * #6314 — resolve the capturing listicle magnet, SERVER-SIDE, from the slug
659
- * the body named.
660
- *
661
- * All four terms in ONE query, and only `slug` came from the caller:
662
- * `siteId` and `workspaceId` are the value `startProjectListingDraft` has
663
- * already resolved from the site's PUBLIC KEY (`siteIdForPublicKey`, then
664
- * `resolveWorkspaceIdForSite`), never from the body. `@@unique([siteId,
665
- * slug])` makes the match at most one row.
666
- *
667
- * `kind: "listicle"` is LOAD-BEARING, not cosmetic: without it a visitor
668
- * could name a contact or newsletter magnet's slug — both are public path
669
- * segments — and file an application against it.
670
- *
671
- * NO `status` term, deliberately. A magnet can be flipped `live -> draft`
672
- * while a visitor is mid-application, and dropping attribution on that flip
673
- * would silently punish the operator's own edit. The cost is bounded: a draft
674
- * magnet's slug is the operator's own, the resulting row lands only in that
675
- * operator's own workspace, and the Applications wire row carries `status`
676
- * so a never-submitted row stays legible as one.
677
- *
678
- * Returns `unresolved` for a slug that names nothing, names another
679
- * workspace's magnet, or names a magnet of the wrong kind — those three are
680
- * deliberately indistinguishable, and all three write NULL.
681
- *
682
- * `failed` is a FOURTH outcome and is NOT one of them: the lookup itself threw.
683
- * It also writes NULL, so the wire is unchanged, but the caller must not
684
- * describe it as "no such magnet" — during a database incident that would send
685
- * an operator hunting a magnet-configuration problem that does not exist. This
686
- * function has already logged the accurate line by the time it returns `failed`.
687
- */
688
- type CapturingFlowResolution =
689
- | { kind: "resolved"; id: string }
690
- | { kind: "unresolved" }
691
- | { kind: "failed" };
692
-
693
- async function resolveCapturingFlowId(
694
- workspaceId: string,
695
- slug: string,
696
- ): Promise<CapturingFlowResolution> {
697
- try {
698
- const row = await prisma.flowDefinition.findFirst({
699
- where: {
700
- slug,
701
- // Both scope terms, both from the value resolved above. They are equal
702
- // by the `flow_definitions_workspace_site_agree` CHECK the fence added;
703
- // carrying both is what makes the scope explicit at the query rather
704
- // than implied by a constraint a future migration could move.
705
- siteId: workspaceId,
706
- workspaceId,
707
- kind: "listicle",
708
- },
709
- select: { id: true },
710
- });
711
- return row === null ? { kind: "unresolved" } : { kind: "resolved", id: row.id };
712
- } catch (err) {
713
- // The lookup is OPTIONAL attribution on a never-gate anonymous route: an
714
- // unavailable read (statement timeout, connection blip) must degrade
715
- // exactly like a slug that names nothing — NULL, and the application is
716
- // kept — rather than turn into a 500 that loses a real founder's
717
- // submission. Both outcomes are NULL on the row, so this line is the only
718
- // thing that tells an operator "lookup failed" from "no such magnet".
719
- // PII-SAFE, same idiom as the unresolved-slug line below: routing
720
- // metadata plus the caught error; never the founder's identity, the
721
- // resume token or the verify nonce (none is in scope here).
722
- logger.warn(
723
- { workspaceId, capturedByFlowSlug: slug, err },
724
- "[project-listings] capturedByFlowSlug lookup failed; application stored unattributed",
725
- );
726
- return { kind: "failed" };
727
- }
728
- }
729
-
730
- /**
731
- * Create a `draft` from step one — the founder's name, email and consent.
732
- *
733
- * `siteId` is a PARAMETER, not a field of `input` (#5048 D2). The payload
734
- * names the site by its public key and the route resolves it through
735
- * `siteIdForPublicKey` before calling here, so no request body carries a
736
- * tenant identifier and nothing a caller sends can choose which site an
737
- * application is filed against.
738
- *
739
- * The site's own terms are read SERVER-SIDE and stamped now, so a listing is
740
- * granted the terms that were in force when it applied; nothing in `input`
741
- * can reach them. The applicant's *requested* window is clamped here, not
742
- * rejected, because a founder who could post their own bound could post an
743
- * unbounded one.
744
- *
745
- * No slug yet: it is derived from `name` at SUBMIT (#5033 D2), which is the
746
- * first moment a name exists.
747
- *
748
- * WORKSPACE STAMP (#6203). The row's `workspaceId` is resolved from `siteId`
749
- * itself (`resolveWorkspaceIdForSite` above) — never a client-supplied
750
- * value, and never a fixed deployment default. An unresolved result rejects
751
- * the write before any row is created (spec AC-4).
752
- */
753
- export async function startProjectListingDraft(
754
- siteId: string,
755
- input: ProjectListingStartInput,
756
- ): Promise<StartProjectListingDraftResult> {
757
- const workspaceId = await resolveWorkspaceIdForSite(siteId);
758
- if (workspaceId === null) {
759
- return {
760
- ok: false,
761
- error: {
762
- kind: "tenant_unresolved",
763
- message: "This site is not configured to accept applications.",
764
- },
765
- };
766
- }
767
-
768
- const { requestedWindowDays } = input;
769
- // #5407 — the NOT NULL display column. `composeFounderName` builds it from
770
- // the PARTS wherever both are written (even beside a `founderName` the body
771
- // also sent, so the stored line and the stored parts can never disagree),
772
- // and stores a line sent on its own verbatim. ONE WAY ONLY: nothing here or
773
- // anywhere else derives parts back out of a line. The schema has already
774
- // refused a body carrying neither shape, so this always produces a string.
775
- const founderName = composeFounderName(input);
776
- const founderEmail = normalizeFounderEmail(input.founderEmail);
777
-
778
- const listingConfig = await listingConfigFor(siteId);
779
- const windowDays = clampWindowDays(requestedWindowDays, listingConfig);
780
-
781
- // #5275 — refuse BEFORE the row exists: a required purpose not granted
782
- // (declined or absent) is a body that contradicts its own `consent: true`,
783
- // and an oversized map is not a form's answer.
784
- const consentConfig = await consentConfigForSite(siteId);
785
- if (input.consents) {
786
- if (Object.keys(input.consents).length > MAX_CONSENT_KEYS) {
787
- return {
788
- ok: false,
789
- error: {
790
- kind: "invalid_input",
791
- message: `consents carries more than ${MAX_CONSENT_KEYS} purposes`,
792
- },
793
- };
794
- }
795
- const unmet = requiredConsentUnmet(consentConfig, input.consents);
796
- if (unmet !== undefined) {
797
- return {
798
- ok: false,
799
- error: {
800
- kind: "invalid_input",
801
- message: `required consent purpose "${unmet}" was not granted`,
802
- },
803
- };
804
- }
805
- }
806
-
807
- const resumeToken = mintResumeToken();
808
- // #5407 — minted on EVERY draft, whether or not the site sends the resume
809
- // email. `start` cannot know: the send is decided asynchronously inside
810
- // `sendListingResumeLink`, against the site's own config. A site running no
811
- // resume email therefore stores a nonce nobody is ever handed, and nothing
812
- // on that row can ever verify — which is the correct outcome rather than a
813
- // gap, because no one has read anything at that address.
814
- const verifyNonce = mintVerifyNonce();
815
- // #5275 — the row and its grant record land in ONE transaction: from here
816
- // on `consentAt` and the ConsentGrant row are stamped by the SAME
817
- // affirmative act, and a grant write that fails takes the row with it
818
- // rather than stranding a "consented" listing with no evidence (security
819
- // review, Medium 2). A body carrying `consents` records the wording the
820
- // founder read (resolved server-side from the same registry the renderer
821
- // used, D7); a body carrying only the legacy `consent: true` literal
822
- // records one grant marked unrecoverable (D11) rather than today's
823
- // wording, which nobody was shown.
824
- const consents = input.consents;
825
- const locale = input.locale ?? "en";
826
- // #6314 — the capturing magnet, resolved SERVER-SIDE from the slug the body
827
- // named. Only runs when the key is present, so an existing caller costs
828
- // nothing; when it is, it is one probe of `@@unique([siteId, slug])`.
829
- const capture =
830
- input.capturedByFlowSlug === undefined
831
- ? undefined
832
- : await resolveCapturingFlowId(workspaceId, input.capturedByFlowSlug);
833
- const capturedByFlowId = capture?.kind === "resolved" ? capture.id : null;
834
- const row = await prisma.$transaction(async (tx) => {
835
- const created = await tx.projectListing.create({
836
- data: {
837
- // #6254 AC-3/AC-6/AC-10 — the RESOLVED workspace id, not the raw
838
- // `siteId` parameter: `project_listings` now requires
839
- // `workspace_id = site_id`
840
- // (database/migrations/20260922120000_tenancy_fence), and this
841
- // column is the isolation key every downstream reader (including
842
- // `submitProjectListingDraft`'s `routeLead` call) reads back as
843
- // `draft.siteId`. `siteId` (the public-facing param, possibly the
844
- // raw `"default"` alias) is still used above to look up
845
- // `listingConfigFor`/`consentConfigForSite` — those are independent,
846
- // unfenced reads keyed on the site concept, not this row.
847
- siteId: workspaceId,
848
- // #6203 — the isolation key, resolved above from this SAME siteId.
849
- workspaceId,
850
- founderName,
851
- // #5407 — the parts as sent, beside the composed line. Absent where a
852
- // caller sent only a display line, which is the shape every row
853
- // written before #5407 carries; nothing here ever splits that line.
854
- ...(input.founderFirstName !== undefined && {
855
- founderFirstName: input.founderFirstName,
856
- }),
857
- ...(input.founderLastName !== undefined && {
858
- founderLastName: input.founderLastName,
859
- }),
860
- founderEmail,
861
- ...(input.founderPhone !== undefined && { founderPhone: input.founderPhone }),
862
- status: "draft",
863
- consentAt: new Date(),
864
- resumeTokenHash: hashResumeToken(resumeToken),
865
- emailVerifyNonceHash: hashVerifyNonce(verifyNonce),
866
- windowDays,
867
- // #6314 — WRITE-ONCE, and only here. `draftUpdateData` never learns
868
- // this key, so no patch body and no submit can re-attribute a draft
869
- // to a different magnet after the fact — not by its holder, and not
870
- // by anyone who obtains its resume token.
871
- ...(capturedByFlowId !== null && { capturedByFlowId }),
872
- },
873
- select: { id: true },
874
- });
875
- const subject = { siteId, subjectType: "project_listing", subjectId: created.id };
876
- // #8438 D3 — a listing names no magnet slug (ProjectListing carries no
877
- // link to its flow), so `magnet` would be unprovable: the source is `api`.
878
- if (consents) {
879
- await recordConsent(
880
- { ...subject, personId: null, source: "api", locale, config: consentConfig, consents },
881
- tx,
882
- );
883
- } else {
884
- await recordLegacyConsent({ ...subject, source: "api", config: consentConfig }, tx);
885
- }
886
- return created;
887
- });
888
-
889
- // #6314 — an unresolved slug is the operator's ONLY signal, precisely
890
- // because the response deliberately carries none (a distinguishable error
891
- // would be a cross-workspace magnet-slug oracle on an anonymous route).
892
- // Without this line, a mis-wired or stale consuming site yields a
893
- // permanently empty Applications list an operator cannot tell from "no
894
- // applications yet".
895
- //
896
- // PII-SAFE, in this route family's existing idiom: routing metadata only.
897
- // Never `founderEmail`, `founderName`, the resume token or the verify
898
- // nonce — the last two never leave this function except inside the email.
899
- // ONLY the `unresolved` outcome, never `failed`. Both store NULL and both
900
- // return the same 201, but only one of them establishes "no listicle magnet
901
- // of that slug in this site". Asserting it on the throw path would put a
902
- // false magnet-configuration signal into the log during a database incident,
903
- // which is exactly when an operator is grepping for a cause. `failed` has its
904
- // own, accurate line, emitted inside `resolveCapturingFlowId`.
905
- if (capture?.kind === "unresolved") {
906
- logger.warn(
907
- {
908
- siteId,
909
- listingId: row.id,
910
- capturedByFlowSlug: input.capturedByFlowSlug,
911
- },
912
- "[project-listings] capturedByFlowSlug resolved to no listicle magnet in this site; application stored unattributed",
913
- );
914
- }
915
-
916
- return { ok: true, id: row.id, resumeToken, verifyNonce };
917
- }
918
-
919
- // ─── verify-email (POST, anonymous, nonce-gated) ───────────────────────────
920
-
921
- /**
922
- * THE NONCE HAS NO EXPIRY, and shares the resume token's lifetime exactly: it
923
- * lives until `submit` clears both digests, and an unsubmitted draft is never
924
- * swept (`DRAFT_HOLDS_A_SLOT_DAYS` bounds the QUOTA a draft occupies, not the
925
- * row). A resume email sitting in a mailbox for a year still verifies that
926
- * draft a year later.
927
- *
928
- * That is acceptable rather than overlooked, and for one reason: the same
929
- * message carries the resume token, so anyone who can read it can already
930
- * resume and submit the draft outright. A TTL would have to cover both
931
- * credentials to mean anything, and that is a change to #5048's resume
932
- * contract rather than to this column.
933
- *
934
- * It is also NOT cleared on a successful stamp — the fallback read below
935
- * needs it to answer a repeat call idempotently.
936
- */
937
- export type VerifyProjectListingDraftEmailResult =
938
- | { ok: true; value: { id: string; emailVerifiedAt: Date } }
939
- | { ok: false; error: { kind: "not_found"; message: string } };
940
-
941
- /**
942
- * Record that somebody who can read mail at `founderEmail` opened this
943
- * draft's emailed link (#5407).
944
- *
945
- * THE PRECISION IN THAT SENTENCE IS DELIBERATE. It is evidence about the
946
- * ADDRESS, not about the person driving the draft. Whoever posted `start`
947
- * chose the address and holds the resume token, so an attacker can open a
948
- * draft under a stranger's address and the platform will mail that stranger a
949
- * link; if they click it, the attacker's draft is stamped. Binding the stamp
950
- * to the application's CONTENT, or to `ownerUserId`, is what would close that,
951
- * and neither is in this issue. What the stamp rules out is the case it was
952
- * built for: a stamp obtained with no mailbox involved at all.
953
- *
954
- * WHAT IT PROVES, and why it takes TWO credentials. The caller must present
955
- * both the draft's resume token and its verification NONCE, and only the
956
- * second one carries the proof:
957
- *
958
- * - the RESUME TOKEN says "you opened this draft". `start` returns it in
959
- * its own 201 body, so anyone who posted the form has it. On its own it
960
- * proves nothing about an address, and a design that stamped on it alone
961
- * would be forgeable in two HTTP calls — open a draft under a stranger's
962
- * address, take the token out of the response, present it back. That is
963
- * the design this one replaced, caught by its own security review.
964
- * - the NONCE says "you read mail sent to `founderEmail`". It is minted at
965
- * `start`, digested onto the row, and handed to nothing but
966
- * `sendListingResumeLink`. It is in no response body and no log line, and
967
- * the only place it exists outside this server is the `?verify=`
968
- * parameter of the link inside the email.
969
- *
970
- * The token stays in the guard anyway: it costs one term in a `where` and it
971
- * means a nonce that somehow leaked alone still opens nothing.
972
- *
973
- * What it does NOT say is who the founder is. `ownerUserId` (#5295) is the
974
- * column that carries an identity claim and still needs a signed-in user
975
- * whose own address the auth system verified.
976
- *
977
- * WRITE-ONCE, BY COMPARE-AND-SWAP. `emailVerifiedAt: null` is in the `where`,
978
- * so the stamp is the atomic transition and two concurrent openings of the
979
- * same link produce one stamp between them rather than a last-writer-wins
980
- * race. A repeat opening reads back the FIRST stamp, so the call is
981
- * idempotent in its effect and in its answer. It is not indistinguishable —
982
- * a repeat answers an older timestamp than "now" — and does not need to be:
983
- * only a holder of both credentials can make the call at all, and they are
984
- * the one person entitled to know when their own link was first opened.
985
- *
986
- * ONE ANSWER FOR EVERY FAILURE. A wrong token, a wrong nonce, a credential
987
- * bound to a different listing, an unknown id and an already-submitted row
988
- * are all `not_found` — exactly what `patch` and `submit` answer. The
989
- * anonymous surface must not distinguish "exists but not yours" from "does
990
- * not exist", and a verification route least of all: its whole input is a
991
- * guessable-in-principle id and two secrets, so a distinguishable response
992
- * would turn it into an oracle for which drafts exist and, worse, into a
993
- * nonce-guessing feedback channel.
994
- *
995
- * Neither credential is ever logged, returned, or compared in application
996
- * code — only their sha-256 digests reach the query.
997
- */
998
- export async function verifyProjectListingDraftEmail(
999
- id: string,
1000
- resumeToken: string,
1001
- verifyNonce: string,
1002
- ): Promise<VerifyProjectListingDraftEmailResult> {
1003
- const guard = {
1004
- id,
1005
- status: "draft",
1006
- resumeTokenHash: hashResumeToken(resumeToken),
1007
- emailVerifyNonceHash: hashVerifyNonce(verifyNonce),
1008
- };
1009
- const emailVerifiedAt = new Date();
1010
-
1011
- const stamped = await prisma.projectListing.updateMany({
1012
- where: { ...guard, emailVerifiedAt: null },
1013
- data: { emailVerifiedAt },
1014
- });
1015
- if (stamped.count > 0) return { ok: true, value: { id, emailVerifiedAt } };
1016
-
1017
- // Zero rows means one of two things, and they answer differently: the draft
1018
- // is already stamped (idempotent success, carrying the FIRST stamp), or the
1019
- // credentials do not open this draft (`not_found`). This read is what tells
1020
- // them apart, and it is gated by the same four terms the write was — so it
1021
- // cannot report a draft the caller's credentials do not open.
1022
- const row = await prisma.projectListing.findFirst({
1023
- where: guard,
1024
- select: { id: true, emailVerifiedAt: true },
1025
- });
1026
- if (row?.emailVerifiedAt) {
1027
- return { ok: true, value: { id: row.id, emailVerifiedAt: row.emailVerifiedAt } };
1028
- }
1029
- return { ok: false, error: { kind: "not_found", message: "Draft not found" } };
1030
- }
1031
-
1032
- // ─── patch (PATCH, anonymous, token-gated) ──────────────────────────────────
1033
-
1034
- export type PatchProjectListingDraftResult =
1035
- | { ok: true; value: ProjectListing }
1036
- | {
1037
- ok: false;
1038
- error:
1039
- | { kind: "not_found"; message: string }
1040
- | { kind: "invalid_input"; message: string };
1041
- };
1042
-
1043
- /**
1044
- * What `draftUpdateData` cannot read off the patch body (#5285).
1045
- *
1046
- * Both members are the SERVER's, and that is why they are a second argument
1047
- * rather than two more payload fields: `windowDays` is the applicant's
1048
- * request already clamped against the site's own maximum, and
1049
- * `storedSiteAnswers` is what is on the row, which the merge needs and a
1050
- * request body must never be able to supply.
1051
- */
1052
- interface DraftUpdateContext {
1053
- /** The clamped window, when the patch asked for one. */
1054
- windowDays?: number;
1055
- /** The answers already stored, for the merge. */
1056
- storedSiteAnswers?: Record<string, string>;
1057
- }
1058
-
1059
- /**
1060
- * Translate a validated partial application into a Prisma update.
1061
- *
1062
- * Only the keys the caller actually sent are written: an absent key is
1063
- * `undefined`, which Prisma omits from the UPDATE, so patching one field
1064
- * cannot blank the nine the founder filled in on earlier steps.
1065
- *
1066
- * #5279 — THIS IS WHERE THE DISPLAY ADDRESS IS COMPOSED, and the only place.
1067
- * `address` is a union of the legacy display STRING and the structured PARTS
1068
- * (`flowAddressValueSchema`), and the two branches write different columns:
1069
- *
1070
- * string → `address` verbatim, no part column touched. A founder who typed
1071
- * a line gets that line stored exactly as typed, and a draft
1072
- * written before #5279 keeps patching as it always did.
1073
- * parts → the six part columns, PLUS `address` composed from them by
1074
- * `composeAddressLine`.
1075
- *
1076
- * The derivation runs ONE WAY ONLY. Nothing anywhere derives parts from a
1077
- * line: address parsing guesses, and a wrong guess silently corrupts the
1078
- * party identification a listing's privacy notice points at (#5036 D6), with
1079
- * nothing on the row to mark it as invented.
1080
- */
1081
- function draftUpdateData(
1082
- patch: ProjectListingDraftPatchInput,
1083
- context: DraftUpdateContext,
1084
- ): Prisma.ProjectListingUpdateInput {
1085
- return {
1086
- ...(patch.name !== undefined && { name: patch.name }),
1087
- ...(patch.headline !== undefined && { headline: patch.headline }),
1088
- ...(patch.oneLiner !== undefined && { oneLiner: patch.oneLiner }),
1089
- ...(patch.problem !== undefined && { problem: patch.problem }),
1090
- ...(patch.solution !== undefined && { solution: patch.solution }),
1091
- ...(patch.url !== undefined && { url: patch.url }),
1092
- ...(patch.product !== undefined && { product: patch.product }),
1093
- ...(patch.commitment !== undefined && { commitment: patch.commitment }),
1094
- ...(patch.teamComposition !== undefined && { teamComposition: patch.teamComposition }),
1095
- ...(patch.faqs !== undefined && { faqs: patch.faqs as unknown as Prisma.InputJsonValue }),
1096
- ...(patch.anythingElse !== undefined && { anythingElse: patch.anythingElse }),
1097
- ...(patch.address !== undefined &&
1098
- (typeof patch.address === "string"
1099
- ? { address: patch.address }
1100
- : {
1101
- address: composeAddressLine(patch.address),
1102
- addressLine1: patch.address.addressLine1,
1103
- addressLine2: patch.address.addressLine2 ?? null,
1104
- addressCity: patch.address.city,
1105
- addressRegion: patch.address.region,
1106
- addressPostalCode: patch.address.postalCode,
1107
- addressCountry: patch.address.country,
1108
- })),
1109
- ...(patch.founderCompany !== undefined && { founderCompany: patch.founderCompany }),
1110
- ...(patch.questions !== undefined && {
1111
- questions: patch.questions as unknown as Prisma.InputJsonValue,
1112
- }),
1113
- ...(patch.logoMarkUrl !== undefined && { logoMarkUrl: patch.logoMarkUrl }),
1114
- ...(patch.logoWordmarkUrl !== undefined && {
1115
- logoWordmarkUrl: patch.logoWordmarkUrl,
1116
- }),
1117
- // #5285 — the applicant's REQUEST, already clamped by the caller against
1118
- // the site's own `maxWindowDays`. It is written to `windowDays`, the same
1119
- // column `start` writes, because there is one window per listing and the
1120
- // screen that asks for it is the site's choice of screen, not a second
1121
- // field. Clamped and not refused, for the reason `startProjectListingDraft`
1122
- // gives: a founder who could post their own bound could post an unbounded
1123
- // one.
1124
- ...(context.windowDays !== undefined && { windowDays: context.windowDays }),
1125
- // #5285 — MERGED, never replaced. A founder patches one screen at a time,
1126
- // so a body carrying screen four's two answers must not blank screen
1127
- // two's. The incoming keys win; everything already stored is carried.
1128
- // Every incoming id was checked against the site's declarations by the
1129
- // compiled patch schema, so nothing undeclared can enter here.
1130
- ...(patch.siteAnswers !== undefined && {
1131
- siteAnswers: {
1132
- ...context.storedSiteAnswers,
1133
- ...patch.siteAnswers,
1134
- } as Prisma.InputJsonValue,
1135
- }),
1136
- };
1137
- }
1138
-
1139
- /**
1140
- * The site-answer declarations a CAPTURED draft is checked against (#7521 D2):
1141
- * the site's own, plus the eligible Application fields of the LIVE listicle
1142
- * that captured it (`listicleSiteAnswerQuestions`). A draft listicle accepts
1143
- * no answers (SEC-7521-B1).
1144
- *
1145
- * Fails CLOSED: a missing listicle or a config that no longer parses logs at
1146
- * warn and answers the site's declarations alone, so an id nobody declared
1147
- * is still a 400.
1148
- */
1149
- async function capturedDraftSiteAnswers(
1150
- siteId: string,
1151
- listingId: string,
1152
- capturedByFlowId: string,
1153
- siteDeclared: ListingSiteAnswersConfig,
1154
- ): Promise<ListingSiteAnswersConfig> {
1155
- const listicle = await prisma.flowDefinition.findFirst({
1156
- where: {
1157
- id: capturedByFlowId,
1158
- siteId,
1159
- workspaceId: siteId,
1160
- kind: "listicle",
1161
- status: "live",
1162
- },
1163
- select: { config: true },
1164
- });
1165
- const config = listicle ? flowConfigSchema.safeParse(listicle.config) : null;
1166
- if (!config?.success) {
1167
- logger.warn(
1168
- { siteId, listingId },
1169
- "[project-listings] a captured draft's listicle is not live or its config does not parse; accepting the site's own answers only",
1170
- );
1171
- return siteDeclared;
1172
- }
1173
- return withListicleQuestions(siteDeclared, listicleSiteAnswerQuestions(config.data));
1174
- }
1175
-
1176
- /**
1177
- * Merge a partial application into a draft and hand back the merged row.
1178
- *
1179
- * Enforces NO completeness — that is `submit`'s job alone, and the split is
1180
- * the whole point of the lifecycle. Returning the merged row is what makes a
1181
- * step's save verifiable by the client that wrote it.
1182
- */
1183
- export async function patchProjectListingDraft(
1184
- id: string,
1185
- resumeToken: string,
1186
- body: unknown,
1187
- ): Promise<PatchProjectListingDraftResult> {
1188
- // The word caps are the SITE's (#5048 D6), so the body cannot be validated
1189
- // until the draft's site is known. This read resolves that and nothing
1190
- // else — it is not the write's guard, which stays the compare-and-swap
1191
- // below. A caller holding no valid token never gets past it, so a bad token
1192
- // still answers `not_found` before any body is inspected.
1193
- const owner = await prisma.projectListing.findFirst({
1194
- where: { id, status: "draft", resumeTokenHash: hashResumeToken(resumeToken) },
1195
- // #5285 — `siteAnswers` rides this read because the write MERGES into it
1196
- // (a founder patches one screen at a time). It is still not the write's
1197
- // guard: the compare-and-swap below is, and a concurrent patch of a
1198
- // DIFFERENT screen can still lose its answers to this one, exactly as it
1199
- // can already lose a column. The store is one row's worth of one
1200
- // founder's own form, not a shared document.
1201
- //
1202
- // #7521 D2 — `capturedByFlowId` rides it too: a draft a listicle captured
1203
- // may answer that listicle's own Application fields.
1204
- select: { siteId: true, siteAnswers: true, capturedByFlowId: true },
1205
- });
1206
- if (!owner) {
1207
- return { ok: false, error: { kind: "not_found", message: "Draft not found" } };
1208
- }
1209
-
1210
- const listingConfig = await listingConfigFor(owner.siteId);
1211
- const siteAnswers =
1212
- owner.capturedByFlowId === null
1213
- ? listingConfig.siteAnswers
1214
- : await capturedDraftSiteAnswers(
1215
- owner.siteId,
1216
- id,
1217
- owner.capturedByFlowId,
1218
- listingConfig.siteAnswers,
1219
- );
1220
- const parsed = buildProjectListingDraftPatchSchema(
1221
- listingConfig.wordCaps,
1222
- listingConfig.collectedFields,
1223
- siteAnswers,
1224
- ).safeParse(body);
1225
- if (!parsed.success) {
1226
- return {
1227
- ok: false,
1228
- error: {
1229
- kind: "invalid_input",
1230
- message: parsed.error.issues[0]?.message ?? "invalid input",
1231
- },
1232
- };
1233
- }
1234
- const patch: ProjectListingDraftPatchInput = parsed.data;
1235
-
1236
- const stored = siteAnswersFromRow(owner.siteAnswers);
1237
- const context: DraftUpdateContext = {
1238
- // THE CLAMP, and the reason `requestedWindowDays` is safe to accept from
1239
- // an anonymous body at all (#5285). The site's `maxWindowDays` is read
1240
- // server-side and caps everything; the payload carries a REQUEST. A
1241
- // founder who could post their own bound could post an unbounded one, and
1242
- // this is the only place a patched window reaches a column.
1243
- ...(patch.requestedWindowDays !== undefined && {
1244
- windowDays: clampWindowDays(patch.requestedWindowDays, listingConfig),
1245
- }),
1246
- // What is on the row already, so the merge below adds to it rather than
1247
- // replacing it. It comes from the ROW and never from the body.
1248
- ...(stored !== null && { storedSiteAnswers: stored }),
1249
- };
1250
-
1251
- // A GUARDED `updateMany`, not a read-then-write: the token check and the
1252
- // write are one statement, so a concurrent `submit` cannot flip the row to
1253
- // `requested` in between and let this patch land on an application the
1254
- // operator is already reviewing (PR #5042 security review, finding 3). The
1255
- // same compare-and-swap shape `submit` and `decideListing` already use.
1256
- const updated = await prisma.projectListing.updateMany({
1257
- where: { id, status: "draft", resumeTokenHash: hashResumeToken(resumeToken) },
1258
- data: draftUpdateData(patch, context),
1259
- });
1260
- if (updated.count === 0) {
1261
- return { ok: false, error: { kind: "not_found", message: "Draft not found" } };
1262
- }
1263
-
1264
- const row = await prisma.projectListing.findFirst({
1265
- where: { id },
1266
- select: PROJECT_LISTING_SELECT,
1267
- });
1268
- if (!row) {
1269
- return { ok: false, error: { kind: "not_found", message: "Draft not found" } };
1270
- }
1271
-
1272
- return { ok: true, value: toResponseRow(row, 0, new Date(), true) };
1273
- }
1274
-
1275
- // ─── submit (POST, anonymous, token-gated) ──────────────────────────────────
1276
-
1277
- export type SubmitProjectListingDraftResult =
1278
- | { ok: true; id: string; slug: string; listing: ProjectListing }
1279
- | {
1280
- ok: false;
1281
- error:
1282
- | { kind: "not_found"; message: string }
1283
- | { kind: "incomplete"; message: string; missingFields: string[] }
1284
- | { kind: "listing_limit_reached"; message: string }
1285
- | { kind: "slug_taken"; message: string };
1286
- };
1287
-
1288
- /**
1289
- * The application, assembled from the stored row for `submit` to validate.
1290
- *
1291
- * Narrowed to the site's COLLECTED fields (#5048 D5). The built submit schema
1292
- * is `.strict()` over exactly that set, so a stored value for a field the site
1293
- * does not collect would otherwise fail as an unrecognised key — which is the
1294
- * right shape for a REQUEST body and the wrong one for a row that may carry a
1295
- * value written before the site narrowed its step set.
1296
- */
1297
- function applicationFromRow(
1298
- row: ProjectListingRow,
1299
- collectedFields: readonly string[],
1300
- ): Record<string, unknown> {
1301
- const collected = new Set(collectedFields);
1302
- const all: Record<string, unknown> = {
1303
- name: row.name,
1304
- headline: row.headline,
1305
- oneLiner: row.oneLiner,
1306
- problem: row.problem,
1307
- ...(row.url !== null && { url: row.url }),
1308
- product: row.product,
1309
- commitment: row.commitment,
1310
- teamComposition: row.teamComposition,
1311
- faqs: row.faqs,
1312
- ...(row.anythingElse !== null && { anythingElse: row.anythingElse }),
1313
- address: row.address,
1314
- ...(row.founderCompany !== null && { founderCompany: row.founderCompany }),
1315
- questions: row.questions,
1316
- // #5285/#5096 — the four fields that became writable. Each is optional in
1317
- // the application schema, so a row that never carried one simply omits it
1318
- // and `submit` is unaffected. `requestedWindowDays` reads back the CLAMPED
1319
- // `windowDays` the row actually holds, not what was asked for: the
1320
- // request is not stored anywhere, and re-asserting it would be asserting
1321
- // a number nothing ever agreed to.
1322
- ...(row.logoMarkUrl !== null && { logoMarkUrl: row.logoMarkUrl }),
1323
- ...(row.logoWordmarkUrl !== null && { logoWordmarkUrl: row.logoWordmarkUrl }),
1324
- ...(row.windowDays !== null && { requestedWindowDays: row.windowDays }),
1325
- ...(row.solution !== null && { solution: row.solution }),
1326
- };
1327
- return Object.fromEntries(
1328
- Object.entries(all).filter(([key]) => collected.has(key)),
1329
- );
1330
- }
1331
-
1332
- /**
1333
- * Count the founder's OTHER non-terminal listings on this site (#5036 D7).
1334
- *
1335
- * Drafts count. A limit drafts escaped would be evaded by never submitting,
1336
- * which is exactly the state a ten-step form leaves a founder in by default.
1337
- *
1338
- * The stored-status filter is a first pass, not the answer: `closed` is
1339
- * computed, so an `active` row whose window has elapsed is terminal and must
1340
- * not count. `computeListingStatus` is the one place that knows this, and
1341
- * consulting it here is the same discipline the CSV sweep learned in #5033.
1342
- */
1343
- async function countOtherNonTerminalListings(
1344
- siteId: string,
1345
- founderEmail: string,
1346
- exceptId: string,
1347
- ): Promise<number> {
1348
- const now = new Date();
1349
- const draftCutoff = new Date(now.getTime() - DRAFT_HOLDS_A_SLOT_DAYS * 24 * 60 * 60 * 1000);
1350
-
1351
- const rows = await prisma.projectListing.findMany({
1352
- where: {
1353
- siteId,
1354
- founderEmail,
1355
- id: { not: exceptId },
1356
- OR: [
1357
- // Every non-terminal state except `draft`, which the clause below
1358
- // handles on its own terms. Derived from the shared constant rather
1359
- // than typed out, so a fifth non-terminal state is counted the day it
1360
- // is added.
1361
- {
1362
- status: {
1363
- in: PROJECT_LISTING_NON_TERMINAL_STATUSES.filter((s) => s !== "draft"),
1364
- },
1365
- },
1366
- // A draft holds a slot only while it is live — see
1367
- // `DRAFT_HOLDS_A_SLOT_DAYS`. It still counts, so not submitting evades
1368
- // nothing; it just stops counting once the application is plainly
1369
- // abandoned, which is what keeps an unverified email from locking a
1370
- // named founder out permanently.
1371
- { status: "draft", createdAt: { gt: draftCutoff } },
1372
- ],
1373
- },
1374
- select: { status: true, windowEndsAt: true, featured: true },
1375
- });
1376
- return rows.filter(
1377
- (r) => computeListingStatus(r.status, r.windowEndsAt, now, r.featured) !== "closed",
1378
- ).length;
1379
- }
1380
-
1381
- /**
1382
- * Validate the whole application and move the row `draft` -> `requested`.
1383
- *
1384
- * Three things happen here and nowhere else: completeness is asserted (an
1385
- * incomplete draft comes back with the offending fields NAMED, so the form can
1386
- * send the founder to the step that owns each one); the concurrent-listing
1387
- * limit binds; and the slug is derived, which is the first moment a `name`
1388
- * exists to derive it from.
1389
- *
1390
- * The transition write is a GUARDED `updateMany` on `status: "draft"`, so two
1391
- * concurrent submits of the same draft cannot both succeed — the loser reads
1392
- * as `not_found`, the same answer a spent token gets. The token's digest is
1393
- * cleared in that same write: a token that leaks after submission grants
1394
- * nothing.
1395
- *
1396
- * The Lead write and the Slack post are both side effects of that committed
1397
- * transition and both fail soft, in that order — never before it, or a submit
1398
- * that lost the race would still have put an application in the operator's
1399
- * pipeline with no listing behind it.
1400
- */
1401
- export async function submitProjectListingDraft(
1402
- id: string,
1403
- resumeToken: string,
1404
- sourceMeta: SourceMeta,
1405
- ): Promise<SubmitProjectListingDraftResult> {
1406
- const draft = await findDraftByToken(id, resumeToken);
1407
- if (!draft) {
1408
- return { ok: false, error: { kind: "not_found", message: "Draft not found" } };
1409
- }
1410
-
1411
- // #5048 D5 — completeness derives from the site's CONFIGURED collected-field
1412
- // set, never from a fixed schema. Steps are individually optional, so a
1413
- // field whose step the site never rendered was never asked for; requiring it
1414
- // would refuse a valid application naming a question the founder never saw.
1415
- //
1416
- // The set comes from the site's own server-side `SiteListingConfig`. It is
1417
- // never read from the request: a caller that could post its own required-
1418
- // field set could post an empty one and submit a blank listing.
1419
- const listingConfig = await listingConfigFor(draft.siteId);
1420
- const submitSchema = buildProjectListingSubmitSchema(
1421
- listingConfig.wordCaps,
1422
- listingConfig.collectedFields,
1423
- );
1424
- const parsed = submitSchema.safeParse(
1425
- applicationFromRow(draft, listingConfig.collectedFields),
1426
- );
1427
- if (!parsed.success) {
1428
- const missingFields = [
1429
- ...new Set(parsed.error.issues.map((issue) => String(issue.path[0]))),
1430
- ].sort();
1431
- return {
1432
- ok: false,
1433
- error: {
1434
- kind: "incomplete",
1435
- message: `application is incomplete: ${missingFields.join(", ")}`,
1436
- missingFields,
1437
- },
1438
- };
1439
- }
1440
-
1441
- const concurrent = await countOtherNonTerminalListings(
1442
- draft.siteId,
1443
- draft.founderEmail,
1444
- draft.id,
1445
- );
1446
- if (concurrent >= PROJECT_LISTING_CONCURRENT_LIMIT) {
1447
- return {
1448
- ok: false,
1449
- error: {
1450
- kind: "listing_limit_reached",
1451
- message: `a founder may hold at most ${PROJECT_LISTING_CONCURRENT_LIMIT} listings at once`,
1452
- },
1453
- };
1454
- }
1455
-
1456
- // `name` may be absent from the picked schema if a site does not collect it
1457
- // (#5048 D5), so the slug derives from the ROW rather than from the parsed
1458
- // payload. A site that collects no name has none to derive from, and the
1459
- // founder's own name is the only other stable string on the row.
1460
- const base = deriveListingSlug(draft.name ?? draft.founderName);
1461
- const slug = await firstFreeSlug(draft.siteId, base);
1462
-
1463
- const transition = async (candidate: string): Promise<number | "taken"> => {
1464
- try {
1465
- const updated = await prisma.projectListing.updateMany({
1466
- where: { id, status: "draft" },
1467
- // #5407 — the verification nonce is cleared here too, for the reason
1468
- // the resume-token digest is: a credential that leaks after the draft
1469
- // stops being a draft is inert twice over.
1470
- data: {
1471
- status: "requested",
1472
- slug: candidate,
1473
- resumeTokenHash: null,
1474
- emailVerifyNonceHash: null,
1475
- },
1476
- });
1477
- return updated.count;
1478
- } catch (err) {
1479
- if (isUniqueViolation(err)) return "taken";
1480
- throw err;
1481
- }
1482
- };
1483
-
1484
- let count = await transition(slug);
1485
- if (count === "taken") {
1486
- // `firstFreeSlug` samples at most 200 same-prefix rows, so a family larger
1487
- // than that can hand back a slug that is in fact taken — and a plain retry
1488
- // resamples and fails the same way, which would let a squatted prefix wall
1489
- // off every later applicant whose name derives to it (PR #5042 security
1490
- // review, finding 2). One random suffix ends that: an ugly slug beats an
1491
- // application that cannot be submitted at all.
1492
- count = await transition(`${base}-${randomBytes(3).toString("hex")}`);
1493
- }
1494
- if (count === "taken") {
1495
- return {
1496
- ok: false,
1497
- error: { kind: "slug_taken", message: "slug already in use for this site" },
1498
- };
1499
- }
1500
- if (count === 0) {
1501
- // A concurrent submit won the race and already spent this draft.
1502
- return { ok: false, error: { kind: "not_found", message: "Draft not found" } };
1503
- }
1504
-
1505
- // The Lead write reuses routeLead — never a duplicate persistence path — and
1506
- // happens at SUBMIT rather than at start, so an anonymous stranger cannot
1507
- // cause an operator notification by opening a draft they never finish.
1508
- //
1509
- // It runs AFTER the transition, and fails soft. Before the transition it
1510
- // would write a Lead (and mail the operator) for every submit that then lost
1511
- // the race or hit a taken slug — an application in the operator's pipeline
1512
- // with no listing behind it, and two Leads for the one submit that did land.
1513
- // After it, the worst case is a `requested` listing whose `leadId` is null,
1514
- // which the model allows and the weekly CSV sweep already skips explicitly.
1515
- // The submit itself has landed either way, and that is what the founder
1516
- // asked for; reporting it as a failure would be the wrong answer.
1517
- const leadResult = await routeLead(
1518
- {
1519
- kind: "submit",
1520
- siteId: draft.siteId,
1521
- source: "projects-apply",
1522
- email: draft.founderEmail,
1523
- payload: {
1524
- name: parsed.data.name,
1525
- oneLiner: parsed.data.oneLiner,
1526
- problem: parsed.data.problem,
1527
- product: parsed.data.product,
1528
- founderName: draft.founderName,
1529
- questions: parsed.data.questions,
1530
- },
1531
- },
1532
- sourceMeta,
1533
- );
1534
- if (leadResult.ok) {
1535
- await prisma.projectListing.update({
1536
- where: { id },
1537
- data: { leadId: leadResult.id },
1538
- });
1539
- } else {
1540
- logger.error(
1541
- { listingId: id, kind: leadResult.error.kind },
1542
- "[project-listings] the Lead write failed after a submitted listing already landed",
1543
- );
1544
- }
1545
-
1546
- const row = await prisma.projectListing.findFirst({
1547
- where: { id },
1548
- select: PROJECT_LISTING_SELECT,
1549
- });
1550
- if (!row) {
1551
- return { ok: false, error: { kind: "not_found", message: "Draft not found" } };
1552
- }
1553
-
1554
- return {
1555
- ok: true,
1556
- id,
1557
- slug: row.slug!,
1558
- listing: toResponseRow(row, 0, new Date(), true),
1559
- };
1560
- }
1561
-
1562
- function isUniqueViolation(err: unknown): boolean {
1563
- return (
1564
- err != null &&
1565
- typeof err === "object" &&
1566
- "code" in err &&
1567
- (err as { code: string }).code === "P2002"
1568
- );
1569
- }
1570
-
1571
- // ─── List + get (tenant scope) ──────────────────────────────────────────────
1572
-
1573
- export async function listProjectListings(siteId: string): Promise<ProjectListing[]> {
1574
- const rows = await prisma.projectListing.findMany({
1575
- where: { siteId },
1576
- orderBy: { createdAt: "desc" },
1577
- select: PROJECT_LISTING_SELECT,
1578
- });
1579
- const counts = await attachWaitlistCounts(siteId, rows);
1580
- const now = new Date();
1581
- return rows.map((row) => toResponseRow(row, waitlistCountFor(row, counts), now, true));
1582
- }
1583
-
1584
- export type GetProjectListingResult =
1585
- | { ok: true; value: ProjectListing }
1586
- | { ok: false; error: { kind: "not_found"; message: string } };
1587
-
1588
- export async function getProjectListing(siteId: string, id: string): Promise<GetProjectListingResult> {
1589
- const row = await prisma.projectListing.findFirst({
1590
- where: { id, siteId },
1591
- select: PROJECT_LISTING_SELECT,
1592
- });
1593
- if (!row) {
1594
- return { ok: false, error: { kind: "not_found", message: "Project listing not found" } };
1595
- }
1596
- const counts = await attachWaitlistCounts(siteId, [row]);
1597
- return { ok: true, value: toResponseRow(row, waitlistCountFor(row, counts), new Date(), true) };
1598
- }
1599
-
1600
- // ─── The founder's own listings (auth scope; #5295) ─────────────────────────
1601
-
1602
- /**
1603
- * The listings the CALLING USER owns, newest first.
1604
- *
1605
- * The join is the owner link and ONLY the owner link:
1606
- * `ownerUserId === userId`, the scalar `listing-promotion.ts` stamps once that
1607
- * user's own email is verified, matches the row's `founderEmail`, and the row's
1608
- * site resolves to one of the user's own workspaces. `founderEmail` is NEVER
1609
- * compared here, at any stage — an un-linked listing that happens to carry the
1610
- * caller's address is not theirs until a promotion said so, and a read-time
1611
- * email match would reintroduce exactly the cross-founder capture the link
1612
- * exists to remove. (`flow-checkouts.ts` draws the same line for `Lead`.)
1613
- *
1614
- * No `siteId` parameter and no `currentSiteId()` scope, deliberately — and the
1615
- * reason is NOT that the two can never coincide. `siteIdForPublicKey`
1616
- * (`listing-config.ts`) does fall back to `currentSiteId()`, so a listing's
1617
- * `siteId` CAN be `AILK_SITE_ID` or the literal `"default"` on a single-tenant
1618
- * deployment. The reason is that the owner link is already the narrower scope:
1619
- * it is only ever stamped for a site inside the user's own tenancy
1620
- * (`listing-promotion.ts`, condition 3), so adding a site term could only
1621
- * remove rows the caller owns — and on the multi-tenant shape, where a
1622
- * listing's `siteId` is a WORKSPACE id rather than `AILK_SITE_ID`, it would
1623
- * remove all of them. The response omits `siteId` regardless, so no workspace
1624
- * id leaves the read.
1625
- *
1626
- * The one thing this gives up against the sibling `/me` routes: on a database
1627
- * shared by more than one site, a caller's rows from every such site come back
1628
- * together. They are all the caller's own rows, which is why that is acceptable
1629
- * here and not a disclosure.
1630
- *
1631
- * No verified-email re-check either. `flow-checkouts.ts` performs one as
1632
- * defence in depth beside its email-matching sibling
1633
- * (`waitlist-signups.ts`, where the gate is load-bearing because the match IS
1634
- * an email). Here the link is the proof, and it was only issuable under
1635
- * verification — so a re-check adds no safety, while failing a caller whose
1636
- * address later changed to an unverified one would wrongly hide the rows they
1637
- * already proved they own.
1638
- *
1639
- * `waitlistCount` is resolved PER SITE: the count is keyed by
1640
- * `(siteId, experimentKey)`, and a founder may own listings in more than one of
1641
- * their own workspaces, so counting them all under one site id would report
1642
- * another site's number.
1643
- *
1644
- * An empty array for a caller who owns nothing is the normal answer, not an
1645
- * error.
1646
- */
1647
- export async function listMyProjectListings(userId: string): Promise<ProjectListing[]> {
1648
- const rows = await prisma.projectListing.findMany({
1649
- where: { ownerUserId: userId },
1650
- orderBy: { createdAt: "desc" },
1651
- select: PROJECT_LISTING_SELECT,
1652
- });
1653
- if (rows.length === 0) return [];
1654
-
1655
- const rowsBySite = new Map<string, ProjectListingRow[]>();
1656
- for (const row of rows) {
1657
- const forSite = rowsBySite.get(row.siteId);
1658
- if (forSite) forSite.push(row);
1659
- else rowsBySite.set(row.siteId, [row]);
1660
- }
1661
- const countsBySite = new Map<string, Map<string, number>>();
1662
- await Promise.all(
1663
- [...rowsBySite].map(async ([siteId, siteRows]) => {
1664
- countsBySite.set(siteId, await attachWaitlistCounts(siteId, siteRows));
1665
- }),
1666
- );
1667
-
1668
- const now = new Date();
1669
- // `featuredEnabled: true` — the founder's own row, like the operator's
1670
- // dashboard row, reports the flag as stored. It is the PUBLIC shelf the
1671
- // site's config switch governs, not what the row's owner may see.
1672
- return rows.map((row) =>
1673
- toResponseRow(
1674
- row,
1675
- waitlistCountFor(row, countsBySite.get(row.siteId) ?? new Map()),
1676
- now,
1677
- true,
1678
- ),
1679
- );
1680
- }
1681
-
1682
- // ─── Patch (tenant scope; the featured flag) ───────────────────────────────
1683
-
1684
- export type SetListingFeaturedResult =
1685
- | { ok: true; value: ProjectListing }
1686
- | { ok: false; error: { kind: "not_found"; message: string } };
1687
-
1688
- /**
1689
- * Set the operator's `featured` flag (#5033 D6).
1690
- *
1691
- * This is the only non-status write the PATCH route makes. STATUS
1692
- * transitions do not come through here at all — since the lifecycle
1693
- * collapsed to five states with `closed` computed, `requested -> active |
1694
- * rejected` is the only transition there is, and `decideListing` owns it for
1695
- * both the PATCH route and the Slack button. The old transition table (which
1696
- * also carried `approved -> live` and `live -> closed`) has no states left to
1697
- * describe.
1698
- */
1699
- export async function setListingFeatured(
1700
- siteId: string,
1701
- id: string,
1702
- featured: boolean,
1703
- ): Promise<SetListingFeaturedResult> {
1704
- const updated = await prisma.projectListing.updateMany({
1705
- where: { id, siteId },
1706
- data: { featured },
1707
- });
1708
- if (updated.count === 0) {
1709
- return { ok: false, error: { kind: "not_found", message: "Project listing not found" } };
1710
- }
1711
-
1712
- const row = await prisma.projectListing.findFirst({
1713
- where: { id, siteId },
1714
- select: PROJECT_LISTING_SELECT,
1715
- });
1716
- if (!row) {
1717
- return { ok: false, error: { kind: "not_found", message: "Project listing not found" } };
1718
- }
1719
-
1720
- const counts = await attachWaitlistCounts(siteId, [row]);
1721
- return { ok: true, value: toResponseRow(row, waitlistCountFor(row, counts), new Date(), true) };
1722
- }
1723
-
1724
- // ─── Patch (tenant scope; the operator's copy edit) ─────────────────────────
1725
-
1726
- /**
1727
- * The five PUBLISHED copy fields an operator copy edit may rewrite.
1728
- *
1729
- * The set is deliberately narrow. `questions` is IN because its prompts and
1730
- * option labels render on the public page, which is precisely where abusive
1731
- * language would land. `name` is OUT because the slug is derived from it at
1732
- * submit and stored, so editing it would desync the public URL from the name.
1733
- * `url`, `product`, `commitment`, `teamComposition`, `address` and
1734
- * `founderCompany` are OUT because they are facts rather than copy — a wrong
1735
- * fact is a question to the founder or a reject, not an edit. `anythingElse`
1736
- * is OUT because it is a note to the reviewer and never renders.
1737
- *
1738
- * The request body is derived from the SAME package schema these keys name
1739
- * (`projectListingApplicationFieldsSchema`) at the route boundary, so every
1740
- * bound the application itself carries — the word caps, the fixed FAQ count,
1741
- * the question refinements — holds here for free.
1742
- */
1743
- export type ProjectListingCopyEdit = Pick<
1744
- ProjectListingDraftPatchInput,
1745
- "headline" | "oneLiner" | "problem" | "faqs" | "questions"
1746
- >;
1747
-
1748
- /**
1749
- * The WHERE terms that admit a copy edit: `requested`, or `active` as the row
1750
- * actually READS.
1751
- *
1752
- * `draft` is the applicant's own, held through the resume token, and stays
1753
- * theirs. `rejected` is terminal. `closed` is the awkward one, because nothing
1754
- * stores it: `computeListingStatus` derives it from a stored `active` whose
1755
- * window has elapsed, so scoping on the stored string alone would leave every
1756
- * closed listing editable. These three terms are that function's three
1757
- * accepting branches, transcribed — a featured row (window-exempt, #5036 D6b),
1758
- * or a window still in force. A non-featured row with a null or elapsed window
1759
- * matches none of them and is refused, exactly as it reads.
1760
- *
1761
- * `now` is a parameter so the one instant the caller renders the response
1762
- * against is the same instant the write is guarded by.
1763
- *
1764
- * This lives in the WHERE clause rather than in a read-then-write check, so a
1765
- * concurrent decision cannot slip the row out of the editable set between the
1766
- * check and the write — the same compare-and-swap discipline
1767
- * `patchProjectListingDraft` and `decideListing` use.
1768
- */
1769
- function copyEditableWhere(now: Date): Prisma.ProjectListingWhereInput[] {
1770
- return [
1771
- { status: "requested" },
1772
- { status: "active", featured: true },
1773
- { status: "active", windowEndsAt: { gt: now } },
1774
- ];
1775
- }
1776
-
1777
- export type PatchListingCopyResult =
1778
- | { ok: true; value: ProjectListing }
1779
- | { ok: false; error: { kind: "not_found"; message: string } };
1780
-
1781
- /**
1782
- * Rewrite a listing's published copy, preserving what the applicant submitted.
1783
- *
1784
- * The third review outcome beside approve and reject: a listing whose copy
1785
- * needs a trim was previously publishable only exactly as written, because the
1786
- * legal transitions out of `requested` are `active` and `rejected`, there is no
1787
- * route back to `draft`, and `patchProjectListingDraft` is scoped to the
1788
- * applicant's own resume token.
1789
- *
1790
- * `submittedCopy` is WRITE-ONCE, on the first edit only. The read below is what
1791
- * resolves the pre-edit copy; it is NOT the write's guard, which stays the
1792
- * status-scoped `updateMany` — the same compare-and-swap shape
1793
- * `patchProjectListingDraft` and `decideListing` use. Because that read is one
1794
- * consistent snapshot, a row it saw with a null `submittedCopy` also carries
1795
- * the copy as the applicant submitted it, so two concurrent first edits write
1796
- * the same snapshot value rather than racing to a different one. Nothing
1797
- * clears the column, so the submitted copy stays recoverable for the life of
1798
- * the row.
1799
- *
1800
- * DELIBERATELY silent on the notification surfaces, unlike a decision. No
1801
- * founder email is sent, and the application's Slack card is not re-rendered,
1802
- * so a card posted before an edit keeps showing the pre-edit copy. Both are the
1803
- * decision path's concerns (`sendListingDecisionEmail`, `postListingApplication`)
1804
- * and neither is touched here. Worth revisiting if operators start editing
1805
- * before deciding often enough that the card misleads.
1806
- *
1807
- * The three audit columns are WRITE-ONLY at present: nothing reads them back,
1808
- * because the tenant read's response contract is `.strict()` and surfacing them
1809
- * would mean widening it. "Recoverable" therefore means recoverable from the
1810
- * row, not through an API.
1811
- *
1812
- * PII boundary: as everywhere else in this module, nothing here is logged.
1813
- */
1814
- export async function patchListingCopy(
1815
- siteId: string,
1816
- id: string,
1817
- copy: ProjectListingCopyEdit,
1818
- editedBy: string,
1819
- ): Promise<PatchListingCopyResult> {
1820
- const before = await prisma.projectListing.findFirst({
1821
- where: { id, siteId },
1822
- select: {
1823
- submittedCopy: true,
1824
- headline: true,
1825
- oneLiner: true,
1826
- problem: true,
1827
- faqs: true,
1828
- questions: true,
1829
- },
1830
- });
1831
- if (!before) {
1832
- return { ok: false, error: { kind: "not_found", message: "Project listing not found" } };
1833
- }
1834
-
1835
- const now = new Date();
1836
- const updated = await prisma.projectListing.updateMany({
1837
- where: { id, siteId, OR: copyEditableWhere(now) },
1838
- data: {
1839
- // Only the keys the operator actually sent are written; an absent key is
1840
- // `undefined`, which Prisma omits from the UPDATE, so trimming the
1841
- // headline cannot blank the FAQs.
1842
- ...(copy.headline !== undefined && { headline: copy.headline }),
1843
- ...(copy.oneLiner !== undefined && { oneLiner: copy.oneLiner }),
1844
- ...(copy.problem !== undefined && { problem: copy.problem }),
1845
- ...(copy.faqs !== undefined && { faqs: copy.faqs as unknown as Prisma.InputJsonValue }),
1846
- ...(copy.questions !== undefined && {
1847
- questions: copy.questions as unknown as Prisma.InputJsonValue,
1848
- }),
1849
- ...(before.submittedCopy === null && {
1850
- submittedCopy: {
1851
- headline: before.headline,
1852
- oneLiner: before.oneLiner,
1853
- problem: before.problem,
1854
- faqs: before.faqs,
1855
- questions: before.questions,
1856
- } as unknown as Prisma.InputJsonValue,
1857
- }),
1858
- copyEditedAt: now,
1859
- copyEditedBy: editedBy,
1860
- },
1861
- });
1862
- if (updated.count === 0) {
1863
- return { ok: false, error: { kind: "not_found", message: "Project listing not found" } };
1864
- }
1865
-
1866
- const row = await prisma.projectListing.findFirst({
1867
- where: { id, siteId },
1868
- select: PROJECT_LISTING_SELECT,
1869
- });
1870
- if (!row) {
1871
- return { ok: false, error: { kind: "not_found", message: "Project listing not found" } };
1872
- }
1873
-
1874
- const counts = await attachWaitlistCounts(siteId, [row]);
1875
- return { ok: true, value: toResponseRow(row, waitlistCountFor(row, counts), now, true) };
1876
- }
1877
-
1878
- // ─── Public read (anonymous) ────────────────────────────────────────────────
1879
-
1880
- /**
1881
- * The public order (#5033): the THREE newest by `decidedAt` first, then the
1882
- * rest by `waitlistCount` desc, then `decidedAt` desc. One function, so the
1883
- * project read and the directory read (#7521 D3) cannot order differently.
1884
- */
1885
- function orderPublicListings<T extends { row: { id: string; decidedAt: Date | null }; waitlistCount: number }>(
1886
- withCounts: readonly T[],
1887
- ): T[] {
1888
- const decidedAtMs = (row: T["row"]): number => row.decidedAt?.getTime() ?? -Infinity;
1889
-
1890
- const newestFirst = [...withCounts].sort((a, b) => decidedAtMs(b.row) - decidedAtMs(a.row));
1891
- const top3 = newestFirst.slice(0, 3);
1892
- const top3Ids = new Set(top3.map((t) => t.row.id));
1893
-
1894
- const rest = withCounts
1895
- .filter((t) => !top3Ids.has(t.row.id))
1896
- .sort((a, b) => {
1897
- if (b.waitlistCount !== a.waitlistCount) return b.waitlistCount - a.waitlistCount;
1898
- return decidedAtMs(b.row) - decidedAtMs(a.row);
1899
- });
1900
-
1901
- return [...top3, ...rest];
1902
- }
1903
-
1904
- /**
1905
- * The page-render read (#4998 AC4, reshaped by #5033): every `active` row for
1906
- * the site, the THREE newest by `decidedAt` first, then the rest by
1907
- * `waitlistCount` desc, then `decidedAt` desc. `founderEmail` never leaves
1908
- * this function.
1909
- *
1910
- * Rows whose window has elapsed are returned and read `closed` — computed,
1911
- * per row, against one instant, with no job having run. They are not filtered
1912
- * out: a consumer partitions its shelves on the status it is handed, and a
1913
- * listing that quietly vanished at midnight would be a worse answer than one
1914
- * that says it is closed.
1915
- */
1916
- export async function publicProjectListings(siteId: string): Promise<ProjectListingPublic[]> {
1917
- const listingConfig = await listingConfigFor(siteId);
1918
- const rows = await prisma.projectListing.findMany({
1919
- where: { siteId, status: "active" },
1920
- select: PROJECT_LISTING_SELECT,
1921
- });
1922
- const counts = await attachWaitlistCounts(siteId, rows);
1923
- const withCounts = rows.map((row) => ({ row, waitlistCount: waitlistCountFor(row, counts) }));
1924
-
1925
- const now = new Date();
1926
- return orderPublicListings(withCounts).map(({ row, waitlistCount }) => {
1927
- // #5407 — `founderPhone` and `emailVerifiedAt` leave here with
1928
- // `founderEmail`. `projectListingPublicSchema` omits all three and
1929
- // `sendValidated` re-parses `.strict()`, so a key that stopped being
1930
- // dropped here would 500 the public read rather than quietly publishing a
1931
- // founder's phone number — which is the failure mode worth having.
1932
- const {
1933
- founderEmail: _founderEmail,
1934
- founderPhone: _founderPhone,
1935
- emailVerifiedAt: _emailVerifiedAt,
1936
- ...publicRow
1937
- } = toResponseRow(
1938
- row,
1939
- waitlistCount,
1940
- now,
1941
- listingConfig.featuredEnabled,
1942
- );
1943
- // #5285 — the `public`-visibility answers ONLY. An `operator-only` answer
1944
- // is something a site asked for its own triage, and a founder who was
1945
- // told it would not be published has to be right about that; an answer
1946
- // whose id the site no longer declares is dropped for the same reason,
1947
- // because "no declaration" cannot be read as "public" on the read that
1948
- // publishes. The tenant dashboard and the review payload are the audience
1949
- // that sees the rest, and they do not come through here.
1950
- return {
1951
- ...publicRow,
1952
- siteAnswers: publicSiteAnswers(publicRow.siteAnswers, listingConfig.siteAnswers),
1953
- };
1954
- });
1955
- }
1956
-
1957
- // ─── Directory read (anonymous, #7521) ──────────────────────────────────────
1958
-
1959
- /** Only what the directory maps — no contact column is ever read here. */
1960
- const DIRECTORY_LISTING_SELECT = {
1961
- id: true,
1962
- slug: true,
1963
- name: true,
1964
- headline: true,
1965
- oneLiner: true,
1966
- url: true,
1967
- logoMarkUrl: true,
1968
- founderCompany: true,
1969
- founderName: true,
1970
- siteAnswers: true,
1971
- featured: true,
1972
- status: true,
1973
- decidedAt: true,
1974
- windowEndsAt: true,
1975
- experimentKey: true,
1976
- capturedByFlowId: true,
1977
- } as const satisfies Prisma.ProjectListingSelect;
1978
-
1979
- /**
1980
- * A landing page's directory (#7521 D3): the entry type of the live listicle
1981
- * that names `landingPage`, and that page's ACCEPTED entries — every `active`
1982
- * listing (an elapsed one reads `closed`, as on `/public`) captured by a live
1983
- * listicle naming it, at most the 200 most recently accepted, in the public
1984
- * order. `null` when no live listicle of this site names the page, which is
1985
- * almost every page.
1986
- *
1987
- * Each entry carries the generic directory shape, never the project-shaped
1988
- * row: name, summary, links, and a `profile` built at read time from the
1989
- * capturing listicle's CURRENT Application fields (`listingProfile`, D4).
1990
- * Contact columns never leave this function.
1991
- *
1992
- * Two live listicles naming one page both contribute entries; the
1993
- * earlier-created one supplies the entry type.
1994
- */
1995
- export async function listingDirectoryFor(
1996
- siteId: string,
1997
- landingPage: string,
1998
- locale: string | undefined,
1999
- ): Promise<ListingDirectoryResponse> {
2000
- // fence: siteId and workspaceId both — the value `siteIdForPublicKey`
2001
- // resolved from the public key, never from the request.
2002
- const listicles = await prisma.flowDefinition.findMany({
2003
- where: { siteId, workspaceId: siteId, kind: "listicle", status: "live", landingPage },
2004
- orderBy: [{ createdAt: "asc" }, { id: "asc" }],
2005
- select: { id: true, config: true },
2006
- });
2007
- if (listicles.length === 0) return null;
2008
-
2009
- const configs = new Map<string, FlowConfig | null>();
2010
- for (const listicle of listicles) {
2011
- const parsed = flowConfigSchema.safeParse(listicle.config);
2012
- if (!parsed.success) {
2013
- logger.warn(
2014
- { siteId, flowId: listicle.id },
2015
- "[project-listings] a live listicle's config does not parse; its entries publish with no profile",
2016
- );
2017
- }
2018
- configs.set(listicle.id, parsed.success ? parsed.data : null);
2019
- }
2020
- const entryType =
2021
- configs.get(listicles[0]!.id)?.listing?.entryType ?? LISTING_ENTRY_TYPE_DEFAULT;
2022
-
2023
- const listingConfig = await listingConfigFor(siteId);
2024
- const rows = await prisma.projectListing.findMany({
2025
- where: {
2026
- siteId,
2027
- workspaceId: siteId,
2028
- status: "active",
2029
- capturedByFlowId: { in: listicles.map((l) => l.id) },
2030
- slug: { not: null },
2031
- },
2032
- // NULLS LAST: Postgres sorts NULL first on DESC, so an undecided row
2033
- // would otherwise take a slot in the window ahead of an accepted one.
2034
- orderBy: [{ decidedAt: { sort: "desc", nulls: "last" } }, { id: "asc" }],
2035
- take: LISTING_DIRECTORY_MAX_ENTRIES,
2036
- select: DIRECTORY_LISTING_SELECT,
2037
- });
2038
- const counts = await attachWaitlistCounts(siteId, rows);
2039
- const withCounts = rows.map((row) => ({ row, waitlistCount: waitlistCountFor(row, counts) }));
2040
-
2041
- const now = new Date();
2042
- const entries = orderPublicListings(withCounts).map(
2043
- ({ row, waitlistCount }): ListingEntryPublic => {
2044
- const config = row.capturedByFlowId ? configs.get(row.capturedByFlowId) : null;
2045
- return {
2046
- id: row.id,
2047
- slug: row.slug!,
2048
- name: row.headline ?? row.name ?? row.founderCompany ?? row.founderName,
2049
- summary: row.oneLiner,
2050
- url: row.url,
2051
- logoMarkUrl: row.logoMarkUrl,
2052
- featured: listingConfig.featuredEnabled && row.featured,
2053
- status:
2054
- computeListingStatus(row.status, row.windowEndsAt, now, row.featured) === "closed"
2055
- ? "closed"
2056
- : "active",
2057
- windowEndsAt: row.windowEndsAt ? row.windowEndsAt.toISOString() : null,
2058
- decidedAt: row.decidedAt ? row.decidedAt.toISOString() : null,
2059
- waitlistCount,
2060
- profile: config
2061
- ? listingProfile(
2062
- config,
2063
- siteAnswersFromRow(row.siteAnswers),
2064
- locale ?? config.defaultLocale,
2065
- listingConfig.siteAnswers.questions,
2066
- )
2067
- : [],
2068
- };
2069
- },
2070
- );
2071
-
2072
- return { landingPage, entryType, entries };
2073
- }