create-ailk 0.1.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (284) hide show
  1. package/component-catalog.md +210 -52
  2. package/dist/cli.js +0 -0
  3. package/dist/lib/apply-module-patches.d.ts +47 -0
  4. package/dist/lib/apply-module-patches.js +370 -0
  5. package/dist/lib/extract-module-bundle.d.ts +12 -3
  6. package/dist/lib/extract-module-bundle.js +236 -24
  7. package/dist/lib/fetch-module.d.ts +3 -38
  8. package/dist/lib/fetch-module.js +26 -8
  9. package/dist/lib/module-license-gate.d.ts +2 -0
  10. package/dist/lib/module-license-gate.js +1 -0
  11. package/dist/lib/paid-paths.d.ts +16 -0
  12. package/dist/lib/paid-paths.js +90 -0
  13. package/dist/module-architecture.d.ts +139 -23
  14. package/dist/module-architecture.js +668 -25
  15. package/dist/parse-args.d.ts +2 -2
  16. package/dist/parse-args.js +3 -1
  17. package/dist/programmatic.d.ts +2 -1
  18. package/dist/programmatic.js +15 -4
  19. package/dist/surfaces.d.ts +12 -36
  20. package/dist/surfaces.js +35 -5
  21. package/dist/sync-routes.js +31 -1
  22. package/package.json +14 -15
  23. package/templates/.claude/agents/web.md +2 -3
  24. package/templates/.claude/rules/architecture.md +5 -5
  25. package/templates/.claude/skills/README.md +2 -1
  26. package/templates/.env.example +21 -9
  27. package/templates/CONVENTIONS.md +6 -7
  28. package/templates/apps/api/.env.example +9 -0
  29. package/templates/apps/api/CLAUDE.md +35 -4
  30. package/templates/apps/api/package.json +0 -1
  31. package/templates/apps/api/src/__tests__/cors.test.ts +195 -0
  32. package/templates/apps/api/src/__tests__/module-exclusion.test.ts +60 -2
  33. package/templates/apps/api/src/__tests__/vercel-handler.test.ts +159 -0
  34. package/templates/apps/api/src/config/__tests__/modules.test.ts +76 -0
  35. package/templates/apps/api/src/config/index.ts +19 -0
  36. package/templates/apps/api/src/config/modules.ts +12 -14
  37. package/templates/apps/api/src/lib/__mocks__/prisma.ts +13 -0
  38. package/templates/apps/api/src/lib/__tests__/slice-load.test.ts +89 -0
  39. package/templates/apps/api/src/lib/slice-load.ts +90 -0
  40. package/templates/apps/api/src/openapi/__tests__/openapi.test.ts +52 -32
  41. package/templates/apps/api/src/openapi/__tests__/spec-identity.test.ts +182 -0
  42. package/templates/apps/api/src/openapi/__tests__/surface-drift.test.ts +293 -0
  43. package/templates/apps/api/src/openapi/index.ts +9 -3
  44. package/templates/apps/api/src/openapi/spec.ts +505 -65
  45. package/templates/apps/api/src/openapi/surface-drift.ts +195 -0
  46. package/templates/apps/api/src/routes/content/__tests__/create.test.ts +14 -0
  47. package/templates/apps/api/src/routes/content/__tests__/delete.test.ts +14 -0
  48. package/templates/apps/api/src/routes/content/__tests__/update.test.ts +14 -0
  49. package/templates/apps/api/src/routes/content/index.ts +38 -11
  50. package/templates/apps/api/src/routes/project-listings/__tests__/configured-application.test.ts +28 -0
  51. package/templates/apps/api/src/routes/project-listings/__tests__/drafts.test.ts +144 -0
  52. package/templates/apps/api/src/routes/project-listings/__tests__/founder-identity.test.ts +796 -0
  53. package/templates/apps/api/src/routes/project-listings/__tests__/me.test.ts +478 -0
  54. package/templates/apps/api/src/routes/project-listings/__tests__/public.test.ts +38 -0
  55. package/templates/apps/api/src/routes/project-listings/__tests__/resume-email.test.ts +814 -0
  56. package/templates/apps/api/src/routes/project-listings/__tests__/site-answers.test.ts +717 -0
  57. package/templates/apps/api/src/routes/project-listings/__tests__/site-key.test.ts +35 -0
  58. package/templates/apps/api/src/routes/project-listings/__tests__/structured-address.test.ts +484 -0
  59. package/templates/apps/api/src/routes/project-listings/index.ts +52 -10
  60. package/templates/apps/api/src/routes/project-listings/me.ts +86 -0
  61. package/templates/apps/api/src/routes/project-listings/patch-draft.ts +5 -0
  62. package/templates/apps/api/src/routes/project-listings/public.ts +5 -0
  63. package/templates/apps/api/src/routes/project-listings/respond.ts +11 -0
  64. package/templates/apps/api/src/routes/project-listings/resume-token.ts +5 -0
  65. package/templates/apps/api/src/routes/project-listings/start.ts +38 -0
  66. package/templates/apps/api/src/routes/project-listings/submit.ts +5 -0
  67. package/templates/apps/api/src/routes/project-listings/verify-email.ts +150 -0
  68. package/templates/apps/api/src/server.ts +471 -133
  69. package/templates/apps/api/src/services/__tests__/consent-migration.test.ts +65 -0
  70. package/templates/apps/api/src/services/__tests__/consent.test.ts +282 -0
  71. package/templates/apps/api/src/services/consent.ts +236 -0
  72. package/templates/apps/api/src/services/deliverable-fulfillment.ts +10 -0
  73. package/templates/apps/api/src/services/listing-config.ts +58 -0
  74. package/templates/apps/api/src/services/project-listing-resume-email.ts +326 -0
  75. package/templates/apps/api/src/services/project-listings.ts +602 -29
  76. package/templates/apps/api/src/vercel-handler.ts +60 -26
  77. package/templates/apps/mcp/.env.example +8 -0
  78. package/templates/apps/mcp/CLAUDE.md +2 -2
  79. package/templates/apps/mcp/__tests__/catalog-drift.test.ts +21 -0
  80. package/templates/apps/mcp/__tests__/config/modules.test.ts +78 -0
  81. package/templates/apps/mcp/__tests__/module-exclusion.test.ts +1 -1
  82. package/templates/apps/mcp/src/config/modules.ts +14 -13
  83. package/templates/apps/mcp/src/server.ts +8 -4
  84. package/templates/apps/mcp/src/tools/index.ts +7 -22
  85. package/templates/apps/web/.env.example +15 -0
  86. package/templates/apps/web/app/[locale]/(authed)/{waitlist/__tests__ → __tests__}/gate.test.tsx +4 -4
  87. package/templates/apps/web/app/[locale]/flows/[slug]/FlowStepperClient.tsx +2 -1
  88. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/FlowStepperClient.permalink.test.tsx +2 -1
  89. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/FlowStepperClient.test.tsx +2 -1
  90. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/flow.actions.test.ts +1 -0
  91. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/two-route-tool.test.tsx +1 -0
  92. package/templates/apps/web/app/[locale]/flows/[slug]/flow.actions.ts +2 -1
  93. package/templates/apps/web/app/[locale]/flows/[slug]/page.tsx +1 -0
  94. package/templates/apps/web/app/[locale]/flows/[slug]/start/page.tsx +1 -0
  95. package/templates/apps/web/app/[locale]/layout.tsx +13 -1
  96. package/templates/apps/web/app/llms.txt/route.ts +12 -9
  97. package/templates/apps/web/jest.config.cjs +20 -13
  98. package/templates/apps/web/lib/__tests__/site-theme.test.ts +112 -0
  99. package/templates/apps/web/lib/site-brand.tsx +4 -1
  100. package/templates/apps/web/lib/site-theme.ts +74 -0
  101. package/templates/apps/web/next.config.mjs +1 -3
  102. package/templates/apps/web/package.json +1 -6
  103. package/templates/apps/web/public/android-chrome-192x192.png +0 -0
  104. package/templates/apps/web/public/android-chrome-512x512.png +0 -0
  105. package/templates/apps/web/public/apple-touch-icon.png +0 -0
  106. package/templates/apps/web/public/favicon-16x16.png +0 -0
  107. package/templates/apps/web/public/favicon-32x32.png +0 -0
  108. package/templates/apps/web/public/favicon.ico +0 -0
  109. package/templates/apps/web/public/favicon.svg +6 -3
  110. package/templates/apps/web/public/lockup-horizontal.svg +4 -0
  111. package/templates/apps/web/public/logomark.svg +4 -0
  112. package/templates/apps/web/public/site.webmanifest +2 -2
  113. package/templates/apps/web/public/wordmark.svg +4 -0
  114. package/templates/content/_site.mdx +12 -0
  115. package/templates/database/CHANGELOG.md +94 -0
  116. package/templates/database/inbox/schema.prisma +165 -0
  117. package/templates/database/migrations/20260911140000_listing_structured_address/migration.sql +32 -0
  118. package/templates/database/migrations/20260911180000_consent_grants/migration.sql +71 -0
  119. package/templates/database/migrations/20260911200000_listing_site_answers/migration.sql +30 -0
  120. package/templates/database/migrations/20260912120000_listing_owner_link/migration.sql +49 -0
  121. package/templates/database/migrations/20260914120000_listing_founder_identity/migration.sql +123 -0
  122. package/templates/database/package.json +1 -1
  123. package/templates/database/scripts/db-generate-locked.sh +0 -0
  124. package/templates/package.json +1 -1
  125. package/templates/.claude/skills/scaffold-commerce/SKILL.md +0 -807
  126. package/templates/.claude/skills/scaffold-commerce/references/lookup-keys-template.md +0 -71
  127. package/templates/.claude/skills/scaffold-commerce/references/marketplace-brand-pages.md +0 -83
  128. package/templates/.claude/skills/scaffold-commerce/templates/checkout-route.template.ts +0 -370
  129. package/templates/.claude/skills/scaffold-commerce/templates/invoice-route.template.ts +0 -376
  130. package/templates/.claude/skills/scaffold-commerce/templates/marketplace-cta-route.tsx.tmpl +0 -72
  131. package/templates/.claude/skills/scaffold-commerce/templates/payment-link-route.template.ts +0 -471
  132. package/templates/.claude/skills/scaffold-commerce/templates/portal-route.template.ts +0 -365
  133. package/templates/.claude/skills/scaffold-commerce/templates/stripe-config.template.ts +0 -60
  134. package/templates/.claude/skills/scaffold-commerce/templates/subscription-route.template.ts +0 -446
  135. package/templates/apps/api/src/__tests__/server.test.ts +0 -253
  136. package/templates/apps/api/src/bin/deliverable-resend.ts +0 -144
  137. package/templates/apps/api/src/bin/deliverable-upload.ts +0 -114
  138. package/templates/apps/api/src/bin/followup-sweep.ts +0 -44
  139. package/templates/apps/api/src/bin/listing-csv-sweep.ts +0 -46
  140. package/templates/apps/api/src/bin/seed-presets.ts +0 -58
  141. package/templates/apps/api/src/bin/seed-waitlist-experiments.ts +0 -104
  142. package/templates/apps/api/src/bin/session-retention-sweep.ts +0 -46
  143. package/templates/apps/api/src/lib/__tests__/stripe.test.ts +0 -74
  144. package/templates/apps/api/src/lib/stripe.ts +0 -52
  145. package/templates/apps/api/src/lib/tenant-db.ts +0 -225
  146. package/templates/apps/api/src/lib/ws-token.ts +0 -91
  147. package/templates/apps/api/src/middleware/tenant.ts +0 -99
  148. package/templates/apps/api/src/routes/billing/__tests__/portal.test.ts +0 -450
  149. package/templates/apps/api/src/routes/billing/__tests__/read.test.ts +0 -262
  150. package/templates/apps/api/src/routes/billing/__tests__/usage.test.ts +0 -436
  151. package/templates/apps/api/src/routes/billing/index.ts +0 -36
  152. package/templates/apps/api/src/routes/billing/portal.ts +0 -182
  153. package/templates/apps/api/src/routes/billing/read.ts +0 -75
  154. package/templates/apps/api/src/routes/billing/usage.ts +0 -153
  155. package/templates/apps/api/src/routes/checkout/__tests__/sessions.test.ts +0 -687
  156. package/templates/apps/api/src/routes/checkout/index.ts +0 -13
  157. package/templates/apps/api/src/routes/checkout/sessions.ts +0 -197
  158. package/templates/apps/api/src/routes/deliverables/__tests__/index.test.ts +0 -393
  159. package/templates/apps/api/src/routes/deliverables/index.ts +0 -200
  160. package/templates/apps/api/src/routes/flow-checkouts/__tests__/index.test.ts +0 -443
  161. package/templates/apps/api/src/routes/flow-checkouts/index.ts +0 -82
  162. package/templates/apps/api/src/routes/flows/README.md +0 -147
  163. package/templates/apps/api/src/routes/flows/__tests__/index.test.ts +0 -752
  164. package/templates/apps/api/src/routes/flows/__tests__/recommender.test.ts +0 -671
  165. package/templates/apps/api/src/routes/flows/index.ts +0 -202
  166. package/templates/apps/api/src/routes/flows/recommender.ts +0 -443
  167. package/templates/apps/api/src/routes/project-listings/__tests__/copy-edit.test.ts +0 -815
  168. package/templates/apps/api/src/routes/project-listings/__tests__/tenant-isolation.test.ts +0 -566
  169. package/templates/apps/api/src/routes/project-listings/get.ts +0 -70
  170. package/templates/apps/api/src/routes/project-listings/list.ts +0 -47
  171. package/templates/apps/api/src/routes/project-listings/patch.ts +0 -136
  172. package/templates/apps/api/src/routes/schedule/__tests__/index.test.ts +0 -490
  173. package/templates/apps/api/src/routes/schedule/index.ts +0 -249
  174. package/templates/apps/api/src/routes/slack/__tests__/actions.test.ts +0 -385
  175. package/templates/apps/api/src/routes/slack/actions.ts +0 -177
  176. package/templates/apps/api/src/routes/slack/index.ts +0 -38
  177. package/templates/apps/api/src/routes/waitlist-experiments/__tests__/tenant-isolation.test.ts +0 -577
  178. package/templates/apps/api/src/routes/waitlist-experiments/comparison.ts +0 -78
  179. package/templates/apps/api/src/routes/waitlist-experiments/index.ts +0 -41
  180. package/templates/apps/api/src/routes/waitlist-experiments/list.ts +0 -64
  181. package/templates/apps/api/src/routes/waitlist-experiments/respond.ts +0 -42
  182. package/templates/apps/api/src/routes/waitlist-experiments/signup.ts +0 -84
  183. package/templates/apps/api/src/routes/waitlist-experiments/signups.ts +0 -119
  184. package/templates/apps/api/src/routes/waitlist-signups/__tests__/index.test.ts +0 -238
  185. package/templates/apps/api/src/routes/waitlist-signups/index.ts +0 -101
  186. package/templates/apps/api/src/routes/webhooks/README.md +0 -80
  187. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-flow-checkout.test.ts +0 -315
  188. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-idempotency.test.ts +0 -247
  189. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-org-billing.test.ts +0 -270
  190. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-rate-limit.test.ts +0 -198
  191. package/templates/apps/api/src/routes/webhooks/__tests__/stripe.test.ts +0 -633
  192. package/templates/apps/api/src/routes/webhooks/index.ts +0 -41
  193. package/templates/apps/api/src/routes/webhooks/stripe.ts +0 -481
  194. package/templates/apps/api/src/routes/workspaces/__tests__/config-tenant-isolation.test.ts +0 -356
  195. package/templates/apps/api/src/routes/workspaces/__tests__/tenant-isolation.test.ts +0 -671
  196. package/templates/apps/api/src/routes/workspaces/config.ts +0 -125
  197. package/templates/apps/api/src/routes/workspaces/index.ts +0 -194
  198. package/templates/apps/api/src/routes/workspaces/sessions.ts +0 -218
  199. package/templates/apps/api/src/services/__tests__/flow-aggregate.test.ts +0 -425
  200. package/templates/apps/api/src/services/__tests__/flow-engine.test.ts +0 -2840
  201. package/templates/apps/api/src/services/__tests__/lead-promotion.test.ts +0 -393
  202. package/templates/apps/api/src/services/__tests__/listing-csv-sweep.test.ts +0 -560
  203. package/templates/apps/api/src/services/__tests__/playbook-compile.test.ts +0 -406
  204. package/templates/apps/api/src/services/__tests__/playbook-render.test.ts +0 -290
  205. package/templates/apps/api/src/services/__tests__/project-listing-decision.test.ts +0 -736
  206. package/templates/apps/api/src/services/__tests__/project-listing-flow.test.ts +0 -475
  207. package/templates/apps/api/src/services/__tests__/project-listing-issue.test.ts +0 -340
  208. package/templates/apps/api/src/services/__tests__/recommender-capture.test.ts +0 -983
  209. package/templates/apps/api/src/services/__tests__/tenant-context-cascade.test.ts +0 -71
  210. package/templates/apps/api/src/services/__tests__/tenant-context.test.ts +0 -379
  211. package/templates/apps/api/src/services/__tests__/usage-metering.test.ts +0 -768
  212. package/templates/apps/api/src/services/__tests__/waitlist-dashboard.test.ts +0 -1314
  213. package/templates/apps/api/src/services/__tests__/waitlist-experiments.test.ts +0 -341
  214. package/templates/apps/api/src/services/__tests__/waitlist-followup.test.ts +0 -567
  215. package/templates/apps/api/src/services/__tests__/waitlist-scoring.test.ts +0 -474
  216. package/templates/apps/api/src/services/__tests__/waitlist-signups.test.ts +0 -354
  217. package/templates/apps/api/src/services/flow-aggregate.ts +0 -232
  218. package/templates/apps/api/src/services/flow-checkouts.ts +0 -123
  219. package/templates/apps/api/src/services/flow-engine.ts +0 -1278
  220. package/templates/apps/api/src/services/lead-promotion.ts +0 -176
  221. package/templates/apps/api/src/services/listing-csv-sweep.ts +0 -455
  222. package/templates/apps/api/src/services/playbook-compile.ts +0 -398
  223. package/templates/apps/api/src/services/playbook-render.ts +0 -263
  224. package/templates/apps/api/src/services/project-listing-decision.ts +0 -490
  225. package/templates/apps/api/src/services/project-listing-flow.ts +0 -426
  226. package/templates/apps/api/src/services/project-listing-issue.ts +0 -251
  227. package/templates/apps/api/src/services/recommender-capture.ts +0 -835
  228. package/templates/apps/api/src/services/scheduling/cal-provider.ts +0 -392
  229. package/templates/apps/api/src/services/scheduling/index.ts +0 -63
  230. package/templates/apps/api/src/services/scheduling/types.ts +0 -88
  231. package/templates/apps/api/src/services/tenant-context.ts +0 -451
  232. package/templates/apps/api/src/services/usage-metering.ts +0 -699
  233. package/templates/apps/api/src/services/waitlist-dashboard.ts +0 -947
  234. package/templates/apps/api/src/services/waitlist-experiments.ts +0 -213
  235. package/templates/apps/api/src/services/waitlist-followup.ts +0 -486
  236. package/templates/apps/api/src/services/waitlist-scoring.ts +0 -166
  237. package/templates/apps/api/src/services/waitlist-signups.ts +0 -165
  238. package/templates/apps/mcp/__tests__/schedule_tools.test.ts +0 -242
  239. package/templates/apps/mcp/src/tools/create_booking.ts +0 -58
  240. package/templates/apps/mcp/src/tools/get_event_meta.ts +0 -55
  241. package/templates/apps/mcp/src/tools/get_flow.ts +0 -61
  242. package/templates/apps/mcp/src/tools/list_availability.ts +0 -67
  243. package/templates/apps/mcp/src/tools/submit_flow_step.ts +0 -83
  244. package/templates/apps/web/app/[locale]/(authed)/waitlist/[experimentId]/page.tsx +0 -309
  245. package/templates/apps/web/app/[locale]/(authed)/waitlist/[experimentId]/signups/[leadId]/page.tsx +0 -149
  246. package/templates/apps/web/app/[locale]/(authed)/waitlist/__tests__/comparison.test.tsx +0 -273
  247. package/templates/apps/web/app/[locale]/(authed)/waitlist/__tests__/list.test.tsx +0 -171
  248. package/templates/apps/web/app/[locale]/(authed)/waitlist/__tests__/signup.test.tsx +0 -179
  249. package/templates/apps/web/app/[locale]/(authed)/waitlist/components/ExperimentsTable.tsx +0 -116
  250. package/templates/apps/web/app/[locale]/(authed)/waitlist/components/OfferFunnelTable.tsx +0 -66
  251. package/templates/apps/web/app/[locale]/(authed)/waitlist/components/RollupTicker.tsx +0 -61
  252. package/templates/apps/web/app/[locale]/(authed)/waitlist/components/ScoreTrace.tsx +0 -114
  253. package/templates/apps/web/app/[locale]/(authed)/waitlist/components/SignupsTable.tsx +0 -139
  254. package/templates/apps/web/app/[locale]/(authed)/waitlist/components/WaitlistComparisonTabs.tsx +0 -85
  255. package/templates/apps/web/app/[locale]/(authed)/waitlist/components/status-badges.tsx +0 -67
  256. package/templates/apps/web/app/[locale]/(authed)/waitlist/page.tsx +0 -179
  257. package/templates/apps/web/app/[locale]/blog/[[...slug]]/page.tsx +0 -178
  258. package/templates/apps/web/app/[locale]/dev/purchase/__tests__/actions.test.ts +0 -160
  259. package/templates/apps/web/app/[locale]/dev/purchase/error.tsx +0 -25
  260. package/templates/apps/web/app/[locale]/dev/purchase/page.tsx +0 -117
  261. package/templates/apps/web/app/[locale]/dev/purchase/purchase.actions.ts +0 -58
  262. package/templates/apps/web/app/[locale]/docs/[[...slug]]/page.tsx +0 -119
  263. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/checkout.actions.test.ts +0 -287
  264. package/templates/apps/web/app/[locale]/flows/[slug]/checkout.actions.ts +0 -254
  265. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/ResultsClient.tsx +0 -532
  266. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/ResultsEmailStep.tsx +0 -121
  267. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/__tests__/ResultsClient.checkout.test.tsx +0 -457
  268. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/__tests__/page.test.tsx +0 -396
  269. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/page.tsx +0 -114
  270. package/templates/apps/web/app/[locale]/projects/apply/ListingApplicationClient.tsx +0 -110
  271. package/templates/apps/web/app/[locale]/projects/apply/__tests__/ListingApplicationClient.test.tsx +0 -96
  272. package/templates/apps/web/app/[locale]/schedule/__tests__/page.test.tsx +0 -117
  273. package/templates/apps/web/app/[locale]/schedule/confirmed/__tests__/page.test.tsx +0 -96
  274. package/templates/apps/web/app/[locale]/schedule/confirmed/page.tsx +0 -92
  275. package/templates/apps/web/app/[locale]/schedule/page.tsx +0 -82
  276. package/templates/apps/web/content/en/blog/README.txt +0 -25
  277. package/templates/apps/web/content/en/docs/index.mdx +0 -28
  278. package/templates/apps/web/lib/__mocks__/source-server.js +0 -31
  279. package/templates/apps/web/lib/blog-list-data.ts +0 -95
  280. package/templates/apps/web/lib/blog-post-data.ts +0 -79
  281. package/templates/apps/web/lib/source.ts +0 -34
  282. package/templates/apps/web/public/logomark-dark.svg +0 -4
  283. package/templates/apps/web/public/logomark-light.svg +0 -4
  284. package/templates/apps/web/source.config.ts +0 -78
@@ -0,0 +1,814 @@
1
+ /**
2
+ * @file resume-email.test.ts
3
+ *
4
+ * THE ACCEPTANCE GATE for the resume email's SEND (#5406) — the fire-and-forget
5
+ * side effect `POST /v1/project-listings` gained.
6
+ *
7
+ * Four properties fail quietly if they regress, which is why each is here:
8
+ * - the send is OPT-IN, so a site already mailing its own resume link (the
9
+ * reason this issue exists) does not start sending a second one;
10
+ * - the 201 is never delayed or failed by Resend, because the draft has
11
+ * already committed and the founder must get their token back;
12
+ * - nothing logs the founder's address, their name, or the resume token —
13
+ * the one credential on this anonymous draft, which also rides the LINK;
14
+ * - the site's config is read PER SEND, so editing the row changes the next
15
+ * email with no rebuild and no module reload.
16
+ *
17
+ * Real route, real service, mocked `lib/prisma.js` over a small in-memory row
18
+ * store (the `drafts.test.ts` discipline). `@working-theory/email` is mocked
19
+ * because it is an external package boundary whose own contract is tested in
20
+ * `packages/email/__tests__/send-listing-resume-email.test.ts` — and because
21
+ * this container has no egress, so no email could be sent regardless.
22
+ * `@working-theory/license` is mocked for the reason
23
+ * docs/lessons/project-listings/02 records: the route barrel drags in
24
+ * `routeLead`'s import chain whether or not a test exercises it.
25
+ */
26
+ import Fastify from "fastify";
27
+ import type { FastifyInstance } from "fastify";
28
+
29
+ // eslint-disable-next-line no-restricted-syntax -- prisma is a DB boundary; __mocks__/prisma.ts activates the auto-mock
30
+ jest.mock("../../../lib/prisma.js");
31
+
32
+ const mockSendResumeEmail = jest.fn();
33
+ jest.mock("@working-theory/email", () => ({
34
+ sendLeadNotification: jest.fn().mockResolvedValue({ ok: true, messageId: "msg-test" }),
35
+ sendListingResumeEmail: (...args: unknown[]) => mockSendResumeEmail(...args),
36
+ }));
37
+
38
+ jest.mock("@working-theory/license", () => ({
39
+ checkLicense: jest.fn().mockResolvedValue({
40
+ tier: "free",
41
+ plan: null,
42
+ features: [],
43
+ expiresAt: null,
44
+ revoked: false,
45
+ }),
46
+ }));
47
+
48
+ const mockLoggerInfo = jest.fn();
49
+ const mockLoggerWarn = jest.fn();
50
+ const mockLoggerError = jest.fn();
51
+ jest.mock("@working-theory/observability", () => ({
52
+ logger: {
53
+ info: (...args: unknown[]) => mockLoggerInfo(...args),
54
+ warn: (...args: unknown[]) => mockLoggerWarn(...args),
55
+ error: (...args: unknown[]) => mockLoggerError(...args),
56
+ debug: jest.fn(),
57
+ },
58
+ }));
59
+
60
+ import { prisma } from "../../../lib/prisma.js";
61
+ import { startProjectListingRoute } from "../start.js";
62
+
63
+ // ─── Fixtures ───────────────────────────────────────────────────────────────
64
+
65
+ const SITE_ID = "site-1";
66
+ const SITE_KEY = "site-1-public-key";
67
+
68
+ const FOUNDER_EMAIL = "ada@example.com";
69
+ const FOUNDER_NAME = "Ada Founder";
70
+
71
+ const START_PAYLOAD = {
72
+ siteKey: SITE_KEY,
73
+ founderName: FOUNDER_NAME,
74
+ founderEmail: FOUNDER_EMAIL,
75
+ consent: true,
76
+ };
77
+
78
+ const BASE_URL = "https://samhenry.org/projects/apply/start";
79
+
80
+ /** The minimum a site writes to turn the email on. */
81
+ const RESUME_EMAIL_ON = { fromAddress: "hello@samhenry.org", baseUrl: BASE_URL };
82
+
83
+ // ─── The in-memory row store ────────────────────────────────────────────────
84
+
85
+ type Row = Record<string, unknown>;
86
+
87
+ let rows: Row[];
88
+ let nextId: number;
89
+ /** What `prisma.siteListingConfig.findUnique({ where: { siteId } })` answers. */
90
+ let storedConfig: Record<string, unknown> | null;
91
+ /**
92
+ * The siteId `SITE_KEY` resolves to. `SITE_ID` for every test that does not
93
+ * care; the per-site budget's tests each claim their OWN site, because the
94
+ * cap's once-per-window log is remembered PER SITE in module state and two
95
+ * tests sharing a site would share that memory (#5414).
96
+ */
97
+ let resolvedSiteId: string;
98
+
99
+ function matches(row: Row, where: Record<string, unknown>): boolean {
100
+ return Object.entries(where).every(([key, value]) => {
101
+ // The per-recipient cap's window clause.
102
+ if (value !== null && typeof value === "object" && !(value instanceof Date)) {
103
+ const clause = value as Record<string, unknown>;
104
+ if ("gt" in clause) return (row[key] as Date) > (clause["gt"] as Date);
105
+ }
106
+ return row[key] === value;
107
+ });
108
+ }
109
+
110
+ function installStore(): void {
111
+ rows = [];
112
+ nextId = 1;
113
+ storedConfig = null;
114
+ resolvedSiteId = SITE_ID;
115
+
116
+ // One delegate, two lookups: `where.publicKey` is the site-key resolution,
117
+ // `where.siteId` the config read.
118
+ (prisma.siteListingConfig.findUnique as jest.Mock).mockImplementation(
119
+ ({ where }: { where: { siteId?: string; publicKey?: string } }) => {
120
+ if (where.publicKey !== undefined) {
121
+ return Promise.resolve(where.publicKey === SITE_KEY ? { siteId: resolvedSiteId } : null);
122
+ }
123
+ return Promise.resolve(storedConfig === null ? null : { data: storedConfig });
124
+ },
125
+ );
126
+
127
+ (prisma.$transaction as jest.Mock).mockImplementation(
128
+ async (fn: (tx: typeof prisma) => Promise<unknown>) => fn(prisma),
129
+ );
130
+
131
+ (prisma.projectListing.create as jest.Mock).mockImplementation(({ data }: { data: Row }) => {
132
+ const row: Row = {
133
+ id: `prjl_00000000-0000-7000-8000-00000000000${nextId++}`,
134
+ name: null,
135
+ leadId: null,
136
+ // Through `Date.now()` rather than a bare `new Date()` so a test that
137
+ // moves the clock moves the rows with it (the once-per-window log).
138
+ createdAt: new Date(Date.now()),
139
+ updatedAt: new Date(Date.now()),
140
+ ...data,
141
+ };
142
+ rows.push(row);
143
+ return Promise.resolve(row);
144
+ });
145
+
146
+ (prisma.projectListing.findFirst as jest.Mock).mockImplementation(
147
+ ({ where }: { where: Record<string, unknown> }) =>
148
+ Promise.resolve(rows.find((row) => matches(row, where)) ?? null),
149
+ );
150
+
151
+ (prisma.projectListing.findMany as jest.Mock).mockImplementation(() => Promise.resolve([]));
152
+
153
+ // Both send caps' read: the per-recipient bound (#5411 security review,
154
+ // finding 1) and the per-site budget (#5414) are the same delegate with
155
+ // different `where` clauses.
156
+ (prisma.projectListing.count as jest.Mock).mockImplementation(
157
+ ({ where }: { where: Record<string, unknown> }) =>
158
+ Promise.resolve(rows.filter((row) => matches(row, where)).length),
159
+ );
160
+
161
+ (prisma.consentGrant.createMany as jest.Mock).mockImplementation(({ data }: { data: Row[] }) =>
162
+ Promise.resolve({ count: data.length }),
163
+ );
164
+ }
165
+
166
+ // ─── Helpers ────────────────────────────────────────────────────────────────
167
+
168
+ async function buildApp(): Promise<FastifyInstance> {
169
+ const app = Fastify();
170
+ await app.register(startProjectListingRoute);
171
+ await app.ready();
172
+ return app;
173
+ }
174
+
175
+ /**
176
+ * Let the fire-and-forget chain run. The send does several awaited reads before
177
+ * it reaches the email — the row, the config, and one count per bound — so a
178
+ * single microtask tick is not enough; `setImmediate` fires only after the
179
+ * microtask queue has fully drained.
180
+ */
181
+ const settle = () => new Promise((resolve) => setImmediate(resolve));
182
+
183
+ async function startDraft(app: FastifyInstance): Promise<{ id: string; resumeToken: string }> {
184
+ const res = await app.inject({
185
+ method: "POST",
186
+ url: "/v1/project-listings",
187
+ payload: START_PAYLOAD,
188
+ });
189
+ expect(res.statusCode).toBe(201);
190
+ return (res.json() as { ok: true; data: { id: string; resumeToken: string } }).data;
191
+ }
192
+
193
+ /** The single `sendListingResumeEmail` argument of the most recent call. */
194
+ function emailed(index = 0): {
195
+ to: string;
196
+ resumeLink: string;
197
+ settings: Record<string, string>;
198
+ variables: Record<string, string>;
199
+ } {
200
+ return mockSendResumeEmail.mock.calls[index]![0];
201
+ }
202
+
203
+ describe("the resume email's send (#5406)", () => {
204
+ let app: FastifyInstance;
205
+
206
+ beforeEach(async () => {
207
+ jest.clearAllMocks();
208
+ mockSendResumeEmail.mockResolvedValue({ ok: true, messageId: "msg-resume" });
209
+ installStore();
210
+ app = await buildApp();
211
+ });
212
+
213
+ afterEach(async () => {
214
+ await app.close();
215
+ });
216
+
217
+ // ── Opt-in ───────────────────────────────────────────────────────────────
218
+
219
+ it("sends NOTHING when the site has no SiteListingConfig row at all", async () => {
220
+ await startDraft(app);
221
+ await settle();
222
+ expect(mockSendResumeEmail).not.toHaveBeenCalled();
223
+ });
224
+
225
+ it("sends NOTHING when the config carries no resumeEmail block", async () => {
226
+ storedConfig = { maxWindowDays: 30 };
227
+ await startDraft(app);
228
+ await settle();
229
+ expect(mockSendResumeEmail).not.toHaveBeenCalled();
230
+ });
231
+
232
+ it("sends NOTHING when resumeEmail carries no fromAddress", async () => {
233
+ // The opt-in switch. A site with wording but no verified sender must not
234
+ // start mailing — and a site already sending its own must not get two.
235
+ storedConfig = { resumeEmail: { subject: "Come back", baseUrl: BASE_URL } };
236
+ await startDraft(app);
237
+ await settle();
238
+ expect(mockSendResumeEmail).not.toHaveBeenCalled();
239
+ expect(mockLoggerInfo).toHaveBeenCalledWith(
240
+ expect.objectContaining({ reason: "no_from_address" }),
241
+ "listing-resume-email-skipped",
242
+ );
243
+ });
244
+
245
+ it("sends NOTHING when resumeEmail carries no baseUrl", async () => {
246
+ // The platform does not know where a site mounted its application, so
247
+ // there is no link to build and no default worth guessing.
248
+ storedConfig = { resumeEmail: { fromAddress: "hello@samhenry.org" } };
249
+ await startDraft(app);
250
+ await settle();
251
+ expect(mockSendResumeEmail).not.toHaveBeenCalled();
252
+ expect(mockLoggerInfo).toHaveBeenCalledWith(
253
+ expect.objectContaining({ reason: "no_base_url" }),
254
+ "listing-resume-email-skipped",
255
+ );
256
+ });
257
+
258
+ // ── The send ─────────────────────────────────────────────────────────────
259
+
260
+ it("sends to the founder with the site's own settings once configured", async () => {
261
+ storedConfig = {
262
+ siteName: "Sam Henry",
263
+ resumeEmail: {
264
+ ...RESUME_EMAIL_ON,
265
+ senderName: "Sam Henry",
266
+ replyTo: "sam@samhenry.org",
267
+ subject: "Verify to continue, {firstName}",
268
+ outro: "Reply if you get stuck.",
269
+ },
270
+ };
271
+ await startDraft(app);
272
+ await settle();
273
+
274
+ expect(mockSendResumeEmail).toHaveBeenCalledTimes(1);
275
+ expect(emailed().to).toBe(FOUNDER_EMAIL);
276
+ expect(emailed().settings).toEqual({
277
+ fromAddress: "hello@samhenry.org",
278
+ senderName: "Sam Henry",
279
+ replyTo: "sam@samhenry.org",
280
+ subject: "Verify to continue, {firstName}",
281
+ outro: "Reply if you get stuck.",
282
+ });
283
+ // `baseUrl` is the API's to consume, not the email package's.
284
+ expect(emailed().settings).not.toHaveProperty("baseUrl");
285
+ });
286
+
287
+ it("builds the link as baseUrl + ?draft=<id>&token=<resumeToken>&verify=<nonce>", async () => {
288
+ storedConfig = { resumeEmail: RESUME_EMAIL_ON };
289
+ const { id, resumeToken } = await startDraft(app);
290
+ await settle();
291
+
292
+ // The exact shape `ListingApplicationFlow`'s `resume` prop reads.
293
+ const url = new URL(emailed().resumeLink);
294
+ expect(`${url.origin}${url.pathname}`).toBe(BASE_URL);
295
+ expect(url.searchParams.get("draft")).toBe(id);
296
+ expect(url.searchParams.get("token")).toBe(resumeToken);
297
+ // #5407 — and the verification nonce, which is what makes
298
+ // `email_verified_at` mean something the resume token could not prove.
299
+ expect(url.searchParams.get("verify")).toEqual(expect.any(String));
300
+ });
301
+
302
+ // #5407 — this message is the ONLY carrier of the verification nonce, and
303
+ // the property is what the whole fix rests on: a caller who has everything
304
+ // `start` returned still cannot verify.
305
+ it("carries a nonce that appears NOWHERE in `start`'s own response", async () => {
306
+ storedConfig = { resumeEmail: RESUME_EMAIL_ON };
307
+ const res = await app.inject({
308
+ method: "POST",
309
+ url: "/v1/project-listings",
310
+ payload: START_PAYLOAD,
311
+ });
312
+ await settle();
313
+
314
+ const nonce = new URL(emailed().resumeLink).searchParams.get("verify")!;
315
+ expect(nonce).toEqual(expect.any(String));
316
+ expect(res.body).not.toContain(nonce);
317
+ // Nor is it any of the values the response DOES carry.
318
+ const data = (res.json() as { data: Record<string, string> }).data;
319
+ expect(Object.values(data)).not.toContain(nonce);
320
+ });
321
+
322
+ it("gives each draft its OWN nonce", async () => {
323
+ storedConfig = { resumeEmail: RESUME_EMAIL_ON };
324
+ await startDraft(app);
325
+ await settle();
326
+ await startDraft(app);
327
+ await settle();
328
+
329
+ const first = new URL(emailed(0).resumeLink).searchParams.get("verify");
330
+ const second = new URL(emailed(1).resumeLink).searchParams.get("verify");
331
+ expect(first).not.toBe(second);
332
+ });
333
+
334
+ it("appends to a baseUrl that already carries a query string", async () => {
335
+ storedConfig = { resumeEmail: { ...RESUME_EMAIL_ON, baseUrl: `${BASE_URL}?locale=en` } };
336
+ const { id } = await startDraft(app);
337
+ await settle();
338
+
339
+ const url = new URL(emailed().resumeLink);
340
+ expect(url.searchParams.get("locale")).toBe("en");
341
+ expect(url.searchParams.get("draft")).toBe(id);
342
+ });
343
+
344
+ it("passes {siteName} from the config, and leaves {firstName}/{projectName} unset", async () => {
345
+ storedConfig = { siteName: "Sam Henry", resumeEmail: RESUME_EMAIL_ON };
346
+ await startDraft(app);
347
+ await settle();
348
+
349
+ // `name` is null on a step-one draft, and THIS payload sends one display
350
+ // line rather than the two name parts — `founderName` is deliberately not
351
+ // split to guess a first name, so `{firstName}` stays unset. Both render
352
+ // as empty text in the email package.
353
+ expect(emailed().variables).toEqual({ siteName: "Sam Henry" });
354
+ });
355
+
356
+ // #5407 — the column the note above was waiting for. `{firstName}` is
357
+ // populated from `founderFirstName` and only where the founder actually
358
+ // gave one; nothing derives it from `founderName`.
359
+ it("passes {firstName} when the founder gave one, and never guesses it", async () => {
360
+ storedConfig = { siteName: "Sam Henry", resumeEmail: RESUME_EMAIL_ON };
361
+ const res = await app.inject({
362
+ method: "POST",
363
+ url: "/v1/project-listings",
364
+ payload: {
365
+ siteKey: SITE_KEY,
366
+ founderFirstName: "Ada",
367
+ founderLastName: "Lovelace",
368
+ founderEmail: FOUNDER_EMAIL,
369
+ consent: true,
370
+ },
371
+ });
372
+ expect(res.statusCode).toBe(201);
373
+ await settle();
374
+
375
+ expect(emailed().variables).toEqual({ siteName: "Sam Henry", firstName: "Ada" });
376
+ });
377
+
378
+ it("passes no {siteName} when the site has not named itself", async () => {
379
+ storedConfig = { resumeEmail: RESUME_EMAIL_ON };
380
+ await startDraft(app);
381
+ await settle();
382
+ expect(emailed().variables).toEqual({});
383
+ });
384
+
385
+ // ── The 201 is independent of the email ──────────────────────────────────
386
+
387
+ it("answers 201 with the token even when Resend FAILS", async () => {
388
+ storedConfig = { resumeEmail: RESUME_EMAIL_ON };
389
+ mockSendResumeEmail.mockResolvedValue({
390
+ ok: false,
391
+ error: { kind: "send_failed", message: "Resend API error" },
392
+ });
393
+
394
+ const { id, resumeToken } = await startDraft(app);
395
+ expect(id).toMatch(/^prjl_/);
396
+ expect(resumeToken.length).toBeGreaterThan(0);
397
+
398
+ await settle();
399
+ // Logged as a KIND, never as the failure's own contents.
400
+ expect(mockLoggerWarn).toHaveBeenCalledWith(
401
+ expect.objectContaining({ errorKind: "send_failed" }),
402
+ "listing resume email send failed",
403
+ );
404
+ });
405
+
406
+ it("answers 201 even when the email THROWS", async () => {
407
+ storedConfig = { resumeEmail: RESUME_EMAIL_ON };
408
+ mockSendResumeEmail.mockRejectedValue(new Error("boom"));
409
+
410
+ const { id } = await startDraft(app);
411
+ expect(id).toMatch(/^prjl_/);
412
+
413
+ await settle();
414
+ expect(mockLoggerWarn).toHaveBeenCalledWith(
415
+ expect.objectContaining({ errName: "Error" }),
416
+ "listing resume email rejected unexpectedly",
417
+ );
418
+ });
419
+
420
+ it("does NOT wait on the email — the 201 lands while the send is still pending", async () => {
421
+ storedConfig = { resumeEmail: RESUME_EMAIL_ON };
422
+ // A send that never settles. If the route awaited it, `inject` would hang
423
+ // and this test would time out rather than assert.
424
+ mockSendResumeEmail.mockReturnValue(new Promise(() => {}));
425
+
426
+ const res = await app.inject({
427
+ method: "POST",
428
+ url: "/v1/project-listings",
429
+ payload: START_PAYLOAD,
430
+ });
431
+ expect(res.statusCode).toBe(201);
432
+ });
433
+
434
+ // ── Per-recipient bound (PR #5411 security review, finding 1) ────────────
435
+
436
+ describe("bounds outbound mail per recipient", () => {
437
+ // `start` is ANONYMOUS and its IP limiter is evadable (`trustProxy`), so
438
+ // without this a loop over one victim's address is a mail bomb sent from
439
+ // the site's own verified domain. The cap is what makes an anonymous
440
+ // outbound send affordable at all.
441
+ beforeEach(() => {
442
+ storedConfig = { resumeEmail: RESUME_EMAIL_ON };
443
+ });
444
+
445
+ it("sends the first three, then suppresses the fourth for the same address", async () => {
446
+ for (let i = 0; i < 3; i++) {
447
+ await startDraft(app);
448
+ await settle();
449
+ }
450
+ expect(mockSendResumeEmail).toHaveBeenCalledTimes(3);
451
+
452
+ await startDraft(app);
453
+ await settle();
454
+ expect(mockSendResumeEmail).toHaveBeenCalledTimes(3);
455
+ expect(mockLoggerWarn).toHaveBeenCalledWith(
456
+ expect.objectContaining({ reason: "recipient_rate_limited" }),
457
+ "listing-resume-email-skipped",
458
+ );
459
+ });
460
+
461
+ it("suppresses the EMAIL only — the draft is still created and the 201 still carries the token", async () => {
462
+ // Lesson 14's rule: a quota on an unverified identifier is a lockout
463
+ // weapon. What this one can deny is the email, never the application —
464
+ // the founder in front of the form has their token from the 201.
465
+ for (let i = 0; i < 4; i++) {
466
+ await startDraft(app);
467
+ await settle();
468
+ }
469
+ expect(rows).toHaveLength(4);
470
+ const { id, resumeToken } = await startDraft(app);
471
+ expect(id).toMatch(/^prjl_/);
472
+ expect(resumeToken.length).toBeGreaterThan(0);
473
+ });
474
+
475
+ it("counts per (site, address) — a different address has its own budget", async () => {
476
+ for (let i = 0; i < 4; i++) {
477
+ await startDraft(app);
478
+ await settle();
479
+ }
480
+ mockSendResumeEmail.mockClear();
481
+
482
+ await app.inject({
483
+ method: "POST",
484
+ url: "/v1/project-listings",
485
+ payload: { ...START_PAYLOAD, founderEmail: "grace@example.com" },
486
+ });
487
+ await settle();
488
+ expect(mockSendResumeEmail).toHaveBeenCalledTimes(1);
489
+ });
490
+
491
+ it("does not count drafts older than the window", async () => {
492
+ // Rolling, so a lockout clears itself rather than being permanent.
493
+ for (let i = 0; i < 4; i++) {
494
+ await startDraft(app);
495
+ await settle();
496
+ }
497
+ const twoHoursAgo = new Date(Date.now() - 2 * 60 * 60 * 1000);
498
+ for (const row of rows) row["createdAt"] = twoHoursAgo;
499
+ mockSendResumeEmail.mockClear();
500
+
501
+ await startDraft(app);
502
+ await settle();
503
+ expect(mockSendResumeEmail).toHaveBeenCalledTimes(1);
504
+ });
505
+ });
506
+
507
+ // ── Per-site budget (#5414) ─────────────────────────────────────────────
508
+
509
+ describe("bounds outbound mail per SITE", () => {
510
+ // The residual #5406 stated rather than hid: the per-recipient bound stops
511
+ // a loop aimed at ONE victim and does nothing about a loop over a thousand
512
+ // strangers, each of whom receives one message from the site's own
513
+ // verified sending domain. That is the pattern a mailbox provider reads as
514
+ // a list blast, and the cost — a flagged domain, a suspendable Resend
515
+ // account — lands on the site rather than on the caller.
516
+ let capSite = 0;
517
+ beforeEach(() => {
518
+ resolvedSiteId = `site-cap-${++capSite}`;
519
+ storedConfig = { resumeEmail: { ...RESUME_EMAIL_ON, maxSendsPerHour: 3 } };
520
+ });
521
+
522
+ /** The `site_rate_limited` warn lines emitted so far. */
523
+ function capWarnings(): unknown[][] {
524
+ return mockLoggerWarn.mock.calls.filter(
525
+ ([fields]: [Record<string, unknown>]) => fields["reason"] === "site_rate_limited",
526
+ );
527
+ }
528
+
529
+ /** Start a draft from an address nobody has used, so only the SITE budget binds. */
530
+ async function startFromFreshAddress(n: number): Promise<void> {
531
+ await app.inject({
532
+ method: "POST",
533
+ url: "/v1/project-listings",
534
+ payload: { ...START_PAYLOAD, founderEmail: `founder-${n}@example.com` },
535
+ });
536
+ await settle();
537
+ }
538
+
539
+ it("sends to every stranger UNDER the cap", async () => {
540
+ for (let i = 0; i < 3; i++) await startFromFreshAddress(i);
541
+ expect(mockSendResumeEmail).toHaveBeenCalledTimes(3);
542
+ });
543
+
544
+ it("suppresses the send once the site is AT its cap, however many addresses are used", async () => {
545
+ for (let i = 0; i < 6; i++) await startFromFreshAddress(i);
546
+ // Three sent, three suppressed — the per-recipient bound never fired,
547
+ // since every address here is distinct and used once.
548
+ expect(mockSendResumeEmail).toHaveBeenCalledTimes(3);
549
+ expect(mockLoggerWarn).toHaveBeenCalledWith(
550
+ expect.objectContaining({ reason: "site_rate_limited" }),
551
+ "listing-resume-email-skipped",
552
+ );
553
+ });
554
+
555
+ it("keeps start's 201 and still creates the draft at the cap", async () => {
556
+ for (let i = 0; i < 6; i++) await startFromFreshAddress(i);
557
+ mockSendResumeEmail.mockClear();
558
+
559
+ // The founder in front of the form loses the EMAIL and nothing else:
560
+ // their draft exists and their resume token is in the response body.
561
+ const res = await app.inject({
562
+ method: "POST",
563
+ url: "/v1/project-listings",
564
+ payload: { ...START_PAYLOAD, founderEmail: "over-the-cap@example.com" },
565
+ });
566
+ expect(res.statusCode).toBe(201);
567
+ const { id, resumeToken } = (
568
+ res.json() as { data: { id: string; resumeToken: string } }
569
+ ).data;
570
+ expect(id).toMatch(/^prjl_/);
571
+ expect(resumeToken.length).toBeGreaterThan(0);
572
+ await settle();
573
+ expect(mockSendResumeEmail).not.toHaveBeenCalled();
574
+ expect(rows.some((row) => row["id"] === id)).toBe(true);
575
+ });
576
+
577
+ it("recovers when the window rolls past the earlier drafts", async () => {
578
+ for (let i = 0; i < 6; i++) await startFromFreshAddress(i);
579
+ expect(mockSendResumeEmail).toHaveBeenCalledTimes(3);
580
+
581
+ const twoHoursAgo = new Date(Date.now() - 2 * 60 * 60 * 1000);
582
+ for (const row of rows) row["createdAt"] = twoHoursAgo;
583
+ mockSendResumeEmail.mockClear();
584
+
585
+ await startFromFreshAddress(99);
586
+ expect(mockSendResumeEmail).toHaveBeenCalledTimes(1);
587
+ });
588
+
589
+ it("counts each SITE independently — one site's flood does not silence another", async () => {
590
+ // Tenant isolation, on the budget itself: the count is keyed on the
591
+ // siteId read off the DRAFT ROW, so a site that has sent nothing sends.
592
+ for (let i = 0; i < 6; i++) await startFromFreshAddress(i);
593
+ mockSendResumeEmail.mockClear();
594
+
595
+ const counts = (prisma.projectListing.count as jest.Mock).mock.calls.map(
596
+ ([arg]: [{ where: Record<string, unknown> }]) => arg.where["siteId"],
597
+ );
598
+ expect(counts.length).toBeGreaterThan(0);
599
+ for (const siteId of counts) expect(siteId).toBe(resolvedSiteId);
600
+
601
+ // A second site, its own config row, its own empty budget.
602
+ const OTHER_SITE = "site-2";
603
+ (prisma.siteListingConfig.findUnique as jest.Mock).mockImplementation(
604
+ ({ where }: { where: { siteId?: string; publicKey?: string } }) => {
605
+ if (where.publicKey !== undefined) {
606
+ return Promise.resolve({ siteId: OTHER_SITE });
607
+ }
608
+ return Promise.resolve({
609
+ data: { resumeEmail: { ...RESUME_EMAIL_ON, maxSendsPerHour: 3 } },
610
+ });
611
+ },
612
+ );
613
+
614
+ await startFromFreshAddress(100);
615
+ expect(mockSendResumeEmail).toHaveBeenCalledTimes(1);
616
+ expect(rows.at(-1)!["siteId"]).toBe(OTHER_SITE);
617
+ });
618
+
619
+ it("still applies the per-recipient bound under a generous site cap", async () => {
620
+ // The two bounds are independent. A site with plenty of site-wide budget
621
+ // must still not mail ONE address more than three times in an hour.
622
+ storedConfig = { resumeEmail: { ...RESUME_EMAIL_ON, maxSendsPerHour: 1000 } };
623
+ for (let i = 0; i < 5; i++) {
624
+ await startDraft(app);
625
+ await settle();
626
+ }
627
+ expect(mockSendResumeEmail).toHaveBeenCalledTimes(3);
628
+ expect(mockLoggerWarn).toHaveBeenCalledWith(
629
+ expect.objectContaining({ reason: "recipient_rate_limited" }),
630
+ "listing-resume-email-skipped",
631
+ );
632
+ });
633
+
634
+ it("logs the site cap ONCE per window, with the siteId and the count only", async () => {
635
+ for (let i = 0; i < 8; i++) await startFromFreshAddress(i);
636
+
637
+ const capLogs = capWarnings();
638
+ // Five sends were suppressed; a line per suppressed send would hand an
639
+ // attacker a log-flooding primitive on top of everything else.
640
+ expect(capLogs).toHaveLength(1);
641
+ expect(capLogs[0]).toEqual([
642
+ { siteId: resolvedSiteId, count: 4, reason: "site_rate_limited" },
643
+ "listing-resume-email-skipped",
644
+ ]);
645
+ });
646
+
647
+ it("logs AGAIN in the next window — the throttle is a window, not a latch", async () => {
648
+ // The dedupe remembers per site in module state. If it never expired, a
649
+ // site attacked on Monday would trip its cap silently for the rest of
650
+ // the deployment's life, which is the failure mode a throttle is most
651
+ // likely to have and least likely to be noticed having.
652
+ const realNow = Date.now.bind(Date);
653
+ try {
654
+ for (let i = 0; i < 5; i++) await startFromFreshAddress(i);
655
+ expect(capWarnings()).toHaveLength(1);
656
+
657
+ // Two hours on. The earlier drafts fall out of the window with the
658
+ // clock, so the budget refills and has to be spent again.
659
+ jest.spyOn(Date, "now").mockImplementation(() => realNow() + 2 * 60 * 60 * 1000);
660
+ for (let i = 10; i < 15; i++) await startFromFreshAddress(i);
661
+ expect(capWarnings()).toHaveLength(2);
662
+ } finally {
663
+ jest.spyOn(Date, "now").mockRestore();
664
+ }
665
+ });
666
+
667
+ it("logs no address, no name, no token and no draft id when the cap is hit", async () => {
668
+ const tokens: string[] = [];
669
+ for (let i = 0; i < 6; i++) {
670
+ const res = await app.inject({
671
+ method: "POST",
672
+ url: "/v1/project-listings",
673
+ payload: { ...START_PAYLOAD, founderEmail: `founder-${i}@example.com` },
674
+ });
675
+ tokens.push((res.json() as { data: { resumeToken: string } }).data.resumeToken);
676
+ await settle();
677
+ }
678
+
679
+ const capLogs = JSON.stringify(capWarnings());
680
+ expect(capLogs).not.toContain("founder-");
681
+ expect(capLogs).not.toContain(FOUNDER_NAME);
682
+ for (const token of tokens) expect(capLogs).not.toContain(token);
683
+ for (const row of rows) expect(capLogs).not.toContain(row["id"] as string);
684
+ expect(capLogs).not.toContain(BASE_URL);
685
+ });
686
+
687
+ it("falls back to the PLATFORM cap when the site wrote an invalid one", async () => {
688
+ // `.catch(undefined)` on the member: a bad cap costs the CAP, never the
689
+ // addressing beside it. Twenty is the platform default, so a site that
690
+ // typed `0` sends its fourth email rather than none.
691
+ storedConfig = {
692
+ maxWindowDays: 7,
693
+ resumeEmail: { ...RESUME_EMAIL_ON, maxSendsPerHour: 0 },
694
+ };
695
+ for (let i = 0; i < 4; i++) await startFromFreshAddress(i);
696
+ expect(mockSendResumeEmail).toHaveBeenCalledTimes(4);
697
+ // And the operator is told their value is not in effect, by NAME only.
698
+ expect(mockLoggerWarn).toHaveBeenCalledWith(
699
+ { siteId: resolvedSiteId, field: "resumeEmail.maxSendsPerHour" },
700
+ expect.stringContaining("DROPPED"),
701
+ );
702
+ });
703
+
704
+ it("suppresses at the PLATFORM cap when the site configured none", async () => {
705
+ storedConfig = { resumeEmail: RESUME_EMAIL_ON };
706
+ for (let i = 0; i < 21; i++) await startFromFreshAddress(i);
707
+ expect(mockSendResumeEmail).toHaveBeenCalledTimes(20);
708
+ });
709
+ });
710
+
711
+ // ── Tenant isolation ─────────────────────────────────────────────────────
712
+
713
+ it("reads the config for the DRAFT'S OWN siteId, never one from the body", async () => {
714
+ storedConfig = { resumeEmail: RESUME_EMAIL_ON };
715
+ await startDraft(app);
716
+ await settle();
717
+
718
+ const configReads = (prisma.siteListingConfig.findUnique as jest.Mock).mock.calls.filter(
719
+ ([arg]: [{ where: Record<string, unknown> }]) => arg.where["siteId"] !== undefined,
720
+ );
721
+ expect(configReads.length).toBeGreaterThan(0);
722
+ for (const [arg] of configReads) {
723
+ expect((arg as { where: Record<string, unknown> }).where["siteId"]).toBe(SITE_ID);
724
+ }
725
+ // And the row the send read its site off is the one just created.
726
+ expect(rows[0]!["siteId"]).toBe(SITE_ID);
727
+ });
728
+
729
+ // ── Runtime configuration ────────────────────────────────────────────────
730
+
731
+ it("sends TWICE with different config rows and no module reload", async () => {
732
+ // The issue's whole premise: an operator edits SiteListingConfig and the
733
+ // NEXT email changes. Nothing between the two starts re-imports a module,
734
+ // restarts the app, or resets a cache — only the stored row moves.
735
+ storedConfig = {
736
+ siteName: "First Site",
737
+ resumeEmail: { fromAddress: "one@a.example", baseUrl: "https://a.example/apply" },
738
+ };
739
+ await startDraft(app);
740
+ await settle();
741
+
742
+ storedConfig = {
743
+ siteName: "Second Site",
744
+ resumeEmail: {
745
+ fromAddress: "two@b.example",
746
+ baseUrl: "https://b.example/apply",
747
+ subject: "A whole new subject",
748
+ },
749
+ };
750
+ await startDraft(app);
751
+ await settle();
752
+
753
+ expect(mockSendResumeEmail).toHaveBeenCalledTimes(2);
754
+ expect(emailed(0).settings.fromAddress).toBe("one@a.example");
755
+ expect(emailed(0).variables.siteName).toBe("First Site");
756
+ expect(emailed(0).settings.subject).toBeUndefined();
757
+ expect(emailed(1).settings.fromAddress).toBe("two@b.example");
758
+ expect(emailed(1).variables.siteName).toBe("Second Site");
759
+ expect(emailed(1).settings.subject).toBe("A whole new subject");
760
+ expect(emailed(1).resumeLink.startsWith("https://b.example/apply")).toBe(true);
761
+ });
762
+
763
+ // ── PII ──────────────────────────────────────────────────────────────────
764
+
765
+ it("logs no founder email, no founder name, no resume token and no link", async () => {
766
+ storedConfig = { siteName: "Sam Henry", resumeEmail: RESUME_EMAIL_ON };
767
+ mockSendResumeEmail.mockResolvedValue({
768
+ ok: false,
769
+ error: { kind: "send_failed", message: "Resend API error" },
770
+ });
771
+
772
+ const { resumeToken } = await startDraft(app);
773
+ await settle();
774
+
775
+ const logged = JSON.stringify([
776
+ ...mockLoggerInfo.mock.calls,
777
+ ...mockLoggerWarn.mock.calls,
778
+ ...mockLoggerError.mock.calls,
779
+ ]);
780
+ expect(logged).not.toContain(FOUNDER_EMAIL);
781
+ expect(logged).not.toContain(FOUNDER_NAME);
782
+ expect(logged).not.toContain(resumeToken);
783
+ // The link CARRIES the token, so it is PII-equivalent on this surface.
784
+ expect(logged).not.toContain(BASE_URL);
785
+ // What IS logged: routing metadata only.
786
+ expect(mockLoggerWarn).toHaveBeenCalledWith(
787
+ { siteId: SITE_ID, listingId: rows[0]!["id"], errorKind: "send_failed" },
788
+ "listing resume email send failed",
789
+ );
790
+ });
791
+
792
+ // ── A dropped config block is observable (PR #5411 review, item 2) ───────
793
+
794
+ it("warns when a malformed resumeEmail block is DROPPED, naming the field only", async () => {
795
+ // `.catch(undefined)` keeps the site's window bounds when its email block
796
+ // is malformed — correct behaviour, but silent. This is what makes it
797
+ // findable: an operator who typos a key gets a line saying so.
798
+ storedConfig = {
799
+ maxWindowDays: 7,
800
+ resumeEmail: { fromAddress: "hello@samhenry.org", subjct: "typo" },
801
+ };
802
+ await startDraft(app);
803
+ await settle();
804
+
805
+ expect(mockSendResumeEmail).not.toHaveBeenCalled();
806
+ expect(mockLoggerWarn).toHaveBeenCalledWith(
807
+ { siteId: SITE_ID, field: "resumeEmail" },
808
+ expect.stringContaining("DROPPED"),
809
+ );
810
+ // Field name only — never the site's addresses or its copy.
811
+ const logged = JSON.stringify(mockLoggerWarn.mock.calls);
812
+ expect(logged).not.toContain("hello@samhenry.org");
813
+ });
814
+ });