create-ailk 0.24.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 (599) hide show
  1. package/README.md +42 -20
  2. package/component-catalog.json +3 -3
  3. package/component-catalog.md +3 -3
  4. package/dist/add-module.js +4 -2
  5. package/dist/add-route.d.ts +12 -1
  6. package/dist/add-route.js +31 -3
  7. package/dist/cli.js +12 -7
  8. package/dist/derive-architecture.d.ts +3 -4
  9. package/dist/derive-architecture.js +65 -29
  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/module-architecture.d.ts +20 -3
  20. package/dist/module-architecture.js +117 -550
  21. package/dist/paid-sections.d.ts +25 -1
  22. package/dist/paid-sections.js +88 -3
  23. package/dist/surfaces.js +10 -2
  24. package/dist/template-record.d.ts +14 -4
  25. package/dist/template-record.js +23 -5
  26. package/dist/topology.d.ts +16 -3
  27. package/dist/topology.js +31 -19
  28. package/dist/update.d.ts +10 -1
  29. package/dist/update.js +540 -16
  30. package/package.json +3 -3
  31. package/release-scope.json +1 -1
  32. package/templates/.claude/cloudparity-repo-hooks.json +5 -0
  33. package/templates/.claude/hooks/template-guard.sh +137 -0
  34. package/templates/.claude/rules/extending.md +106 -0
  35. package/templates/.claude/rules/loop-contract.md +2 -2
  36. package/templates/.claude/settings.json +11 -0
  37. package/templates/.env.example +5 -5
  38. package/templates/.github/workflows/ci.yml +7 -4
  39. package/templates/CLAUDE.md +11 -1
  40. package/templates/CONVENTIONS.md +8 -10
  41. package/templates/README.md +14 -13
  42. package/templates/apps/api/.env.example +2 -2
  43. package/templates/apps/api/CLAUDE.md +102 -76
  44. package/templates/apps/api/jest.config.cjs +15 -5
  45. package/templates/apps/api/package.json +16 -20
  46. package/templates/apps/api/src/__tests__/trusted-origins.server.test.ts +2 -2
  47. package/templates/apps/api/src/__tests__/vercel-handler.test.ts +4 -4
  48. package/templates/apps/api/src/index.ts +1 -1
  49. package/templates/apps/api/src/lib/__mocks__/prisma.ts +3 -3
  50. package/templates/apps/api/src/modules/commerce.ts +10 -0
  51. package/templates/apps/api/src/modules/content-write.ts +10 -0
  52. package/templates/apps/api/src/modules/multi-tenant.ts +10 -0
  53. package/templates/apps/api/src/modules/scheduling.ts +10 -0
  54. package/templates/apps/api/src/modules/signal-collectors.ts +10 -0
  55. package/templates/apps/api/src/modules/workspace.ts +10 -0
  56. package/templates/apps/api/src/server.ts +117 -1882
  57. package/templates/apps/api/vercel.json +2 -2
  58. package/templates/apps/mcp/CLAUDE.md +67 -20
  59. package/templates/apps/mcp/__tests__/app-entry.test.ts +4 -254
  60. package/templates/apps/mcp/__tests__/boot-file.test.ts +92 -0
  61. package/templates/apps/mcp/jest.config.cjs +6 -1
  62. package/templates/apps/mcp/package.json +5 -13
  63. package/templates/apps/mcp/src/app.ts +8 -7
  64. package/templates/apps/mcp/src/index.ts +6 -34
  65. package/templates/apps/mcp/src/lib/paid-tools.generated.ts +10 -0
  66. package/templates/apps/mcp/src/lib/topology.generated.ts +2 -2
  67. package/templates/apps/mcp/src/site.ts +12 -0
  68. package/templates/apps/web/.env.example +1 -1
  69. package/templates/apps/web/CLAUDE.md +10 -3
  70. package/templates/apps/web/app/.well-known/mcp.json/route.ts +9 -3
  71. package/templates/apps/web/app/[locale]/contact/intake-analytics.ts +1 -1
  72. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/magnet-page.test.tsx +22 -1
  73. package/templates/apps/web/app/[locale]/flows/[slug]/magnet-page.tsx +7 -3
  74. package/templates/apps/web/app/[locale]/pricing/__tests__/unconnected.test.tsx +43 -0
  75. package/templates/apps/web/app/[locale]/pricing/page.tsx +7 -3
  76. package/templates/apps/web/app/api/offerings/checkout/[lookupKey]/__tests__/route.test.ts +222 -0
  77. package/templates/apps/web/app/api/offerings/checkout/[lookupKey]/route.ts +10 -3
  78. package/templates/apps/web/app/api/revalidate/route.ts +3 -3
  79. package/templates/apps/web/auth.ts +2 -2
  80. package/templates/apps/web/jest.config.cjs +1 -0
  81. package/templates/apps/web/lib/auth-email.ts +1 -1
  82. package/templates/apps/web/lib/relay.ts +2 -2
  83. package/templates/apps/web/lib/release-scope.ts +47 -0
  84. package/templates/apps/web/lib/server-api.ts +1 -1
  85. package/templates/apps/web/src/lib/commerce-claim.ts +1 -1
  86. package/templates/customizations.yaml +37 -0
  87. package/templates/database/prisma.config.ts +10 -14
  88. package/templates/database/seed-test.ts +2 -2
  89. package/templates/database/seed.ts +5 -5
  90. package/templates/package.json +12 -6
  91. package/templates/pnpm-workspace.yaml +0 -1
  92. package/templates/project.yaml +16 -8
  93. package/templates/tools/jest/reporters.cjs +65 -0
  94. package/templates/tools/lint-architecture.ts +553 -7
  95. package/templates/tsconfig.json +1 -2
  96. package/versions.json +48 -35
  97. package/templates/apps/api/src/__tests__/commerce-claim-registration.test.ts +0 -409
  98. package/templates/apps/api/src/__tests__/factories/agent-caller.ts +0 -102
  99. package/templates/apps/api/src/__tests__/factories/content-fixture.ts +0 -138
  100. package/templates/apps/api/src/__tests__/factories/in-memory-prisma.ts +0 -441
  101. package/templates/apps/api/src/__tests__/factories/index.ts +0 -70
  102. package/templates/apps/api/src/__tests__/factories/lead-fixture.ts +0 -82
  103. package/templates/apps/api/src/__tests__/leads-forwarded-rate-limit.test.ts +0 -135
  104. package/templates/apps/api/src/__tests__/services/enrichment-shim.test.ts +0 -126
  105. package/templates/apps/api/src/__tests__/stripe-boot.test.ts +0 -132
  106. package/templates/apps/api/src/__tests__/support/hub-sign-in-fake-db.ts +0 -362
  107. package/templates/apps/api/src/bin/__tests__/rate-limit-probe.test.ts +0 -184
  108. package/templates/apps/api/src/bin/abandon-sweep.ts +0 -42
  109. package/templates/apps/api/src/bin/rate-limit-probe.ts +0 -53
  110. package/templates/apps/api/src/bin/spokes.ts +0 -198
  111. package/templates/apps/api/src/bin/stripe-connections-rekey.ts +0 -45
  112. package/templates/apps/api/src/config/__tests__/hub-require-spoke-key.test.ts +0 -196
  113. package/templates/apps/api/src/config/__tests__/index.test.ts +0 -233
  114. package/templates/apps/api/src/config/__tests__/modules.test.ts +0 -76
  115. package/templates/apps/api/src/config/__tests__/stripe-connection-key.test.ts +0 -185
  116. package/templates/apps/api/src/config/__tests__/trusted-origins.test.ts +0 -238
  117. package/templates/apps/api/src/config/index.ts +0 -596
  118. package/templates/apps/api/src/config/modules.ts +0 -83
  119. package/templates/apps/api/src/lib/__tests__/agent-store.test.ts +0 -581
  120. package/templates/apps/api/src/lib/__tests__/auth-email-budget.test.ts +0 -143
  121. package/templates/apps/api/src/lib/__tests__/consent-ledger-double.ts +0 -237
  122. package/templates/apps/api/src/lib/__tests__/consent-store.test.ts +0 -353
  123. package/templates/apps/api/src/lib/__tests__/content-adapter.test.ts +0 -201
  124. package/templates/apps/api/src/lib/__tests__/deliverable-asset-store.test.ts +0 -224
  125. package/templates/apps/api/src/lib/__tests__/error-serializer.test.ts +0 -120
  126. package/templates/apps/api/src/lib/__tests__/errors.test.ts +0 -94
  127. package/templates/apps/api/src/lib/__tests__/file-fallback.test.ts +0 -144
  128. package/templates/apps/api/src/lib/__tests__/fixtures/HomePage/home.mdx +0 -8
  129. package/templates/apps/api/src/lib/__tests__/flow-completion-store.test.ts +0 -149
  130. package/templates/apps/api/src/lib/__tests__/flow-rename-race.db.test.ts +0 -116
  131. package/templates/apps/api/src/lib/__tests__/hub-sign-in-store.test.ts +0 -209
  132. package/templates/apps/api/src/lib/__tests__/lead-capture-store.test.ts +0 -257
  133. package/templates/apps/api/src/lib/__tests__/lead-delivery.test.ts +0 -96
  134. package/templates/apps/api/src/lib/__tests__/outbound-http.test.ts +0 -125
  135. package/templates/apps/api/src/lib/__tests__/prisma.test.ts +0 -165
  136. package/templates/apps/api/src/lib/__tests__/require-commerce-claim.test.ts +0 -317
  137. package/templates/apps/api/src/lib/__tests__/require-paid-tier.test.ts +0 -129
  138. package/templates/apps/api/src/lib/__tests__/site.test.ts +0 -308
  139. package/templates/apps/api/src/lib/__tests__/slice-load.test.ts +0 -89
  140. package/templates/apps/api/src/lib/__tests__/spoke-store.test.ts +0 -202
  141. package/templates/apps/api/src/lib/__tests__/stripe-admission.test.ts +0 -217
  142. package/templates/apps/api/src/lib/__tests__/stripe.test.ts +0 -82
  143. package/templates/apps/api/src/lib/agent-store.ts +0 -613
  144. package/templates/apps/api/src/lib/auth-email-budget.ts +0 -161
  145. package/templates/apps/api/src/lib/consent-store.ts +0 -363
  146. package/templates/apps/api/src/lib/content-adapter.ts +0 -112
  147. package/templates/apps/api/src/lib/deliverable-asset-store.ts +0 -96
  148. package/templates/apps/api/src/lib/error-serializer.ts +0 -164
  149. package/templates/apps/api/src/lib/errors.ts +0 -95
  150. package/templates/apps/api/src/lib/file-fallback.ts +0 -87
  151. package/templates/apps/api/src/lib/flow-completion-store.ts +0 -136
  152. package/templates/apps/api/src/lib/hub-sign-in-store.ts +0 -455
  153. package/templates/apps/api/src/lib/lead-capture-store.ts +0 -122
  154. package/templates/apps/api/src/lib/lead-delivery.ts +0 -52
  155. package/templates/apps/api/src/lib/license-key-store.ts +0 -45
  156. package/templates/apps/api/src/lib/locales.ts +0 -201
  157. package/templates/apps/api/src/lib/outbound-http.ts +0 -127
  158. package/templates/apps/api/src/lib/prisma.ts +0 -21
  159. package/templates/apps/api/src/lib/proposal-paid-store.ts +0 -66
  160. package/templates/apps/api/src/lib/rate-limit-probe.ts +0 -165
  161. package/templates/apps/api/src/lib/rate-limit-store.ts +0 -142
  162. package/templates/apps/api/src/lib/require-commerce-claim.ts +0 -250
  163. package/templates/apps/api/src/lib/require-paid-tier.ts +0 -53
  164. package/templates/apps/api/src/lib/site.ts +0 -257
  165. package/templates/apps/api/src/lib/slice-load.ts +0 -90
  166. package/templates/apps/api/src/lib/spoke-store.ts +0 -180
  167. package/templates/apps/api/src/lib/stripe.ts +0 -321
  168. package/templates/apps/api/src/lib/webhook-idempotency.ts +0 -156
  169. package/templates/apps/api/src/middleware/__tests__/adversarial/bearer-token-format.test.ts +0 -111
  170. package/templates/apps/api/src/middleware/__tests__/adversarial/cookie-or-bearer-precedence.test.ts +0 -172
  171. package/templates/apps/api/src/middleware/__tests__/adversarial/csrf-bearer-skip.test.ts +0 -119
  172. package/templates/apps/api/src/middleware/__tests__/adversarial/csrf-cookie-path.test.ts +0 -138
  173. package/templates/apps/api/src/middleware/__tests__/adversarial/csrf-trusted-origins.test.ts +0 -142
  174. package/templates/apps/api/src/middleware/__tests__/adversarial/session-fixation.test.ts +0 -155
  175. package/templates/apps/api/src/middleware/__tests__/adversarial/session-timeout.test.ts +0 -139
  176. package/templates/apps/api/src/middleware/__tests__/auth.bearer-path.test.ts +0 -562
  177. package/templates/apps/api/src/middleware/__tests__/auth.both-present-precedence.test.ts +0 -76
  178. package/templates/apps/api/src/middleware/__tests__/auth.cookie-path.test.ts +0 -220
  179. package/templates/apps/api/src/middleware/__tests__/auth.database-not-configured.test.ts +0 -97
  180. package/templates/apps/api/src/middleware/__tests__/auth.hub-session-path.test.ts +0 -557
  181. package/templates/apps/api/src/middleware/__tests__/auth.neither-present.test.ts +0 -72
  182. package/templates/apps/api/src/middleware/__tests__/auth.optional-cookie.test.ts +0 -140
  183. package/templates/apps/api/src/middleware/__tests__/default-tenant.test.ts +0 -721
  184. package/templates/apps/api/src/middleware/__tests__/rate-limit-cross-isolate.db.test.ts +0 -220
  185. package/templates/apps/api/src/middleware/__tests__/rate-limit-store.test.ts +0 -430
  186. package/templates/apps/api/src/middleware/__tests__/rate-limit.test.ts +0 -1409
  187. package/templates/apps/api/src/middleware/__tests__/write-budget.test.ts +0 -174
  188. package/templates/apps/api/src/middleware/auth.ts +0 -864
  189. package/templates/apps/api/src/middleware/default-tenant.ts +0 -166
  190. package/templates/apps/api/src/middleware/rate-limit.ts +0 -983
  191. package/templates/apps/api/src/openapi/__tests__/openapi.test.ts +0 -391
  192. package/templates/apps/api/src/openapi/__tests__/spec-identity.test.ts +0 -182
  193. package/templates/apps/api/src/openapi/index.ts +0 -18
  194. package/templates/apps/api/src/openapi/spec.ts +0 -2148
  195. package/templates/apps/api/src/openapi/surface-drift.ts +0 -195
  196. package/templates/apps/api/src/routes/aeo/__tests__/index.test.ts +0 -175
  197. package/templates/apps/api/src/routes/aeo/index.ts +0 -107
  198. package/templates/apps/api/src/routes/auth/__tests__/auth-tokens.functional.test.ts +0 -196
  199. package/templates/apps/api/src/routes/auth/__tests__/auth-user.functional.test.ts +0 -249
  200. package/templates/apps/api/src/routes/auth/__tests__/hub-sign-in.test.ts +0 -532
  201. package/templates/apps/api/src/routes/auth/__tests__/tokens.test.ts +0 -313
  202. package/templates/apps/api/src/routes/auth/__tests__/transactional-email.test.ts +0 -413
  203. package/templates/apps/api/src/routes/auth/__tests__/user.test.ts +0 -609
  204. package/templates/apps/api/src/routes/auth/hub-sign-in.ts +0 -242
  205. package/templates/apps/api/src/routes/auth/tokens.ts +0 -211
  206. package/templates/apps/api/src/routes/auth/transactional-email.ts +0 -301
  207. package/templates/apps/api/src/routes/auth/user.ts +0 -305
  208. package/templates/apps/api/src/routes/billing/plan-checkout.ts +0 -332
  209. package/templates/apps/api/src/routes/checkout/__tests__/live-key.test.ts +0 -178
  210. package/templates/apps/api/src/routes/checkout/__tests__/offerings-authorization.test.ts +0 -1426
  211. package/templates/apps/api/src/routes/checkout/__tests__/session.test.ts +0 -448
  212. package/templates/apps/api/src/routes/checkout/__tests__/sessions.test.ts +0 -1742
  213. package/templates/apps/api/src/routes/checkout/index.ts +0 -34
  214. package/templates/apps/api/src/routes/checkout/session.ts +0 -171
  215. package/templates/apps/api/src/routes/checkout/sessions.ts +0 -540
  216. package/templates/apps/api/src/routes/consent/__tests__/account.test.ts +0 -386
  217. package/templates/apps/api/src/routes/consent/__tests__/sign-up-rate-limit.test.ts +0 -160
  218. package/templates/apps/api/src/routes/consent/account.ts +0 -268
  219. package/templates/apps/api/src/routes/consent/cookie.ts +0 -90
  220. package/templates/apps/api/src/routes/consent/index.ts +0 -26
  221. package/templates/apps/api/src/routes/consent/unsubscribe.ts +0 -127
  222. package/templates/apps/api/src/routes/content/__tests__/get-page.test.ts +0 -853
  223. package/templates/apps/api/src/routes/content/__tests__/list-pages.test.ts +0 -230
  224. package/templates/apps/api/src/routes/content/__tests__/list-types.test.ts +0 -44
  225. package/templates/apps/api/src/routes/content/__tests__/locale.test.ts +0 -118
  226. package/templates/apps/api/src/routes/content/__tests__/offerings.test.ts +0 -731
  227. package/templates/apps/api/src/routes/content/__tests__/pricing.test.ts +0 -753
  228. package/templates/apps/api/src/routes/content/__tests__/rate-limit.test.ts +0 -51
  229. package/templates/apps/api/src/routes/content/__tests__/search.test.ts +0 -450
  230. package/templates/apps/api/src/routes/content/__tests__/shown-offerings.test.ts +0 -762
  231. package/templates/apps/api/src/routes/content/get-page.ts +0 -183
  232. package/templates/apps/api/src/routes/content/index.ts +0 -49
  233. package/templates/apps/api/src/routes/content/list-pages.ts +0 -74
  234. package/templates/apps/api/src/routes/content/list-types.ts +0 -19
  235. package/templates/apps/api/src/routes/content/offerings.ts +0 -184
  236. package/templates/apps/api/src/routes/content/pricing.ts +0 -176
  237. package/templates/apps/api/src/routes/content/rate-limit.ts +0 -22
  238. package/templates/apps/api/src/routes/content/search.ts +0 -100
  239. package/templates/apps/api/src/routes/content/shown-offerings.ts +0 -229
  240. package/templates/apps/api/src/routes/leads/__tests__/capture.test.ts +0 -88
  241. package/templates/apps/api/src/routes/leads/__tests__/list.test.ts +0 -171
  242. package/templates/apps/api/src/routes/leads/__tests__/magnet-completion.test.ts +0 -515
  243. package/templates/apps/api/src/routes/leads/__tests__/spoke.test.ts +0 -392
  244. package/templates/apps/api/src/routes/leads/__tests__/track.test.ts +0 -165
  245. package/templates/apps/api/src/routes/leads/index.ts +0 -639
  246. package/templates/apps/api/src/routes/leads/list.ts +0 -104
  247. package/templates/apps/api/src/routes/project-listings/__tests__/configured-application.test.ts +0 -626
  248. package/templates/apps/api/src/routes/project-listings/__tests__/drafts.test.ts +0 -1268
  249. package/templates/apps/api/src/routes/project-listings/__tests__/founder-identity.test.ts +0 -847
  250. package/templates/apps/api/src/routes/project-listings/__tests__/me.test.ts +0 -491
  251. package/templates/apps/api/src/routes/project-listings/__tests__/public.test.ts +0 -476
  252. package/templates/apps/api/src/routes/project-listings/__tests__/resume-email.test.ts +0 -872
  253. package/templates/apps/api/src/routes/project-listings/__tests__/site-answers.test.ts +0 -1022
  254. package/templates/apps/api/src/routes/project-listings/__tests__/site-key.test.ts +0 -484
  255. package/templates/apps/api/src/routes/project-listings/__tests__/structured-address.test.ts +0 -535
  256. package/templates/apps/api/src/routes/project-listings/index.ts +0 -164
  257. package/templates/apps/api/src/routes/project-listings/me.ts +0 -87
  258. package/templates/apps/api/src/routes/project-listings/patch-copy.ts +0 -224
  259. package/templates/apps/api/src/routes/project-listings/patch-draft.ts +0 -102
  260. package/templates/apps/api/src/routes/project-listings/public.ts +0 -98
  261. package/templates/apps/api/src/routes/project-listings/respond.ts +0 -48
  262. package/templates/apps/api/src/routes/project-listings/resume-token.ts +0 -27
  263. package/templates/apps/api/src/routes/project-listings/start.ts +0 -140
  264. package/templates/apps/api/src/routes/project-listings/submit.ts +0 -130
  265. package/templates/apps/api/src/routes/project-listings/verify-email.ts +0 -150
  266. package/templates/apps/api/src/routes/requests/__tests__/confirm.test.ts +0 -686
  267. package/templates/apps/api/src/routes/requests/confirm.ts +0 -601
  268. package/templates/apps/api/src/routes/requests/index.ts +0 -54
  269. package/templates/apps/api/src/routes/test/auth/__tests__/session.test.ts +0 -306
  270. package/templates/apps/api/src/routes/test/auth/session.ts +0 -143
  271. package/templates/apps/api/src/routes/webhooks/README.md +0 -398
  272. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-checkout-consent.test.ts +0 -649
  273. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-dunning.test.ts +0 -749
  274. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-flow-checkout.test.ts +0 -449
  275. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-idempotency.test.ts +0 -264
  276. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-livemode-live.test.ts +0 -159
  277. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-livemode.test.ts +0 -158
  278. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-offerings.test.ts +0 -814
  279. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-org-billing.test.ts +0 -301
  280. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-proposal-paid.test.ts +0 -369
  281. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-rate-limit.test.ts +0 -215
  282. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-request-paid.test.ts +0 -301
  283. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-site-filter.test.ts +0 -809
  284. package/templates/apps/api/src/routes/webhooks/__tests__/stripe.test.ts +0 -1155
  285. package/templates/apps/api/src/routes/webhooks/index.ts +0 -141
  286. package/templates/apps/api/src/routes/webhooks/stripe-offerings.ts +0 -384
  287. package/templates/apps/api/src/routes/webhooks/stripe.ts +0 -2028
  288. package/templates/apps/api/src/services/__tests__/abandon-email.test.ts +0 -645
  289. package/templates/apps/api/src/services/__tests__/answer-distributions.test.ts +0 -132
  290. package/templates/apps/api/src/services/__tests__/audit-log.test.ts +0 -1028
  291. package/templates/apps/api/src/services/__tests__/checkout-plan.test.ts +0 -313
  292. package/templates/apps/api/src/services/__tests__/consent-ledger.test.ts +0 -503
  293. package/templates/apps/api/src/services/__tests__/consent-migration.test.ts +0 -65
  294. package/templates/apps/api/src/services/__tests__/consent.test.ts +0 -299
  295. package/templates/apps/api/src/services/__tests__/default-tenant.test.ts +0 -147
  296. package/templates/apps/api/src/services/__tests__/deliverable-fulfillment.test.ts +0 -877
  297. package/templates/apps/api/src/services/__tests__/deliverable-resend.test.ts +0 -379
  298. package/templates/apps/api/src/services/__tests__/dunning-policy.test.ts +0 -368
  299. package/templates/apps/api/src/services/__tests__/entitlements.test.ts +0 -142
  300. package/templates/apps/api/src/services/__tests__/hub-sign-in.test.ts +0 -854
  301. package/templates/apps/api/src/services/__tests__/keyless-workspace-predicate.test.ts +0 -234
  302. package/templates/apps/api/src/services/__tests__/lead-accept-user.test.ts +0 -251
  303. package/templates/apps/api/src/services/__tests__/lead-routing.test.ts +0 -2660
  304. package/templates/apps/api/src/services/__tests__/listing-config.test.ts +0 -166
  305. package/templates/apps/api/src/services/__tests__/magnet-completion.test.ts +0 -389
  306. package/templates/apps/api/src/services/__tests__/person.test.ts +0 -1204
  307. package/templates/apps/api/src/services/__tests__/plan-offerings.test.ts +0 -450
  308. package/templates/apps/api/src/services/__tests__/project-listings.counts.test.ts +0 -202
  309. package/templates/apps/api/src/services/__tests__/project-listings.fence.test.ts +0 -151
  310. package/templates/apps/api/src/services/__tests__/public-site-resolver.test.ts +0 -137
  311. package/templates/apps/api/src/services/__tests__/request-confirm.test.ts +0 -531
  312. package/templates/apps/api/src/services/__tests__/revalidation.test.ts +0 -372
  313. package/templates/apps/api/src/services/__tests__/slack-notify.test.ts +0 -348
  314. package/templates/apps/api/src/services/__tests__/spoke-resolution.test.ts +0 -660
  315. package/templates/apps/api/src/services/__tests__/usage-aggregation.test.ts +0 -941
  316. package/templates/apps/api/src/services/__tests__/usage-credits.test.ts +0 -588
  317. package/templates/apps/api/src/services/__tests__/verified-email.test.ts +0 -78
  318. package/templates/apps/api/src/services/abandon-email.ts +0 -336
  319. package/templates/apps/api/src/services/aeo-score.ts +0 -325
  320. package/templates/apps/api/src/services/answer-distributions.ts +0 -138
  321. package/templates/apps/api/src/services/audit-log.ts +0 -961
  322. package/templates/apps/api/src/services/checkout-buyer.ts +0 -168
  323. package/templates/apps/api/src/services/consent.ts +0 -834
  324. package/templates/apps/api/src/services/default-tenant.ts +0 -416
  325. package/templates/apps/api/src/services/deliverable-fulfillment.ts +0 -750
  326. package/templates/apps/api/src/services/dunning-policy.ts +0 -294
  327. package/templates/apps/api/src/services/enrichment-shim.ts +0 -53
  328. package/templates/apps/api/src/services/entitlements.ts +0 -338
  329. package/templates/apps/api/src/services/hub-sign-in.ts +0 -472
  330. package/templates/apps/api/src/services/lead-accept-user.ts +0 -126
  331. package/templates/apps/api/src/services/lead-promotion.ts +0 -160
  332. package/templates/apps/api/src/services/lead-routing.ts +0 -1372
  333. package/templates/apps/api/src/services/leads-inbox.ts +0 -312
  334. package/templates/apps/api/src/services/listing-config.ts +0 -178
  335. package/templates/apps/api/src/services/magnet-completion.ts +0 -242
  336. package/templates/apps/api/src/services/offerings/__tests__/catalog.test.ts +0 -348
  337. package/templates/apps/api/src/services/offerings/__tests__/checkout-session-record.test.ts +0 -268
  338. package/templates/apps/api/src/services/offerings/__tests__/connection.test.ts +0 -975
  339. package/templates/apps/api/src/services/offerings/__tests__/fixtures.ts +0 -416
  340. package/templates/apps/api/src/services/offerings/__tests__/org-products.test.ts +0 -400
  341. package/templates/apps/api/src/services/offerings/__tests__/readers.test.ts +0 -685
  342. package/templates/apps/api/src/services/offerings/__tests__/source.test.ts +0 -231
  343. package/templates/apps/api/src/services/offerings/catalog.ts +0 -318
  344. package/templates/apps/api/src/services/offerings/checkout-authorization.ts +0 -403
  345. package/templates/apps/api/src/services/offerings/checkout-session-record.ts +0 -192
  346. package/templates/apps/api/src/services/offerings/connection.ts +0 -1083
  347. package/templates/apps/api/src/services/offerings/index.ts +0 -614
  348. package/templates/apps/api/src/services/offerings/source.ts +0 -140
  349. package/templates/apps/api/src/services/offerings/store.ts +0 -150
  350. package/templates/apps/api/src/services/owner-workspaces.ts +0 -132
  351. package/templates/apps/api/src/services/person.ts +0 -1211
  352. package/templates/apps/api/src/services/plan-offerings.ts +0 -125
  353. package/templates/apps/api/src/services/project-listing-resume-email.ts +0 -326
  354. package/templates/apps/api/src/services/project-listings.ts +0 -2085
  355. package/templates/apps/api/src/services/public-site-resolver.ts +0 -396
  356. package/templates/apps/api/src/services/request-confirm.ts +0 -698
  357. package/templates/apps/api/src/services/revalidation.ts +0 -235
  358. package/templates/apps/api/src/services/slack-notify.ts +0 -291
  359. package/templates/apps/api/src/services/usage-aggregation.ts +0 -516
  360. package/templates/apps/api/src/services/usage-credits.ts +0 -340
  361. package/templates/apps/api/src/services/verified-email.ts +0 -71
  362. package/templates/apps/mcp/__tests__/abuse/daily-cap.test.ts +0 -52
  363. package/templates/apps/mcp/__tests__/abuse/email-validator.test.ts +0 -46
  364. package/templates/apps/mcp/__tests__/abuse/guard.test.ts +0 -198
  365. package/templates/apps/mcp/__tests__/abuse/honeypot.test.ts +0 -36
  366. package/templates/apps/mcp/__tests__/abuse/user-agent-deny.test.ts +0 -54
  367. package/templates/apps/mcp/__tests__/aeo-cli-parity.test.ts +0 -116
  368. package/templates/apps/mcp/__tests__/audit-single-page.test.ts +0 -299
  369. package/templates/apps/mcp/__tests__/boot.test.ts +0 -280
  370. package/templates/apps/mcp/__tests__/catalog-drift.test.ts +0 -359
  371. package/templates/apps/mcp/__tests__/config/modules.test.ts +0 -78
  372. package/templates/apps/mcp/__tests__/get_business_hours.test.ts +0 -82
  373. package/templates/apps/mcp/__tests__/get_faq.test.ts +0 -80
  374. package/templates/apps/mcp/__tests__/get_locations.test.ts +0 -65
  375. package/templates/apps/mcp/__tests__/get_offerings.test.ts +0 -557
  376. package/templates/apps/mcp/__tests__/get_pricing.test.ts +0 -524
  377. package/templates/apps/mcp/__tests__/get_site_info.test.ts +0 -81
  378. package/templates/apps/mcp/__tests__/http-transport.test.ts +0 -1232
  379. package/templates/apps/mcp/__tests__/index.test.ts +0 -195
  380. package/templates/apps/mcp/__tests__/lib/audit-single-page-readiness-scan.test.ts +0 -191
  381. package/templates/apps/mcp/__tests__/lib/commerce-claim.test.ts +0 -531
  382. package/templates/apps/mcp/__tests__/lib/content-adapter-parity.test.ts +0 -70
  383. package/templates/apps/mcp/__tests__/lib/content-adapter.test.ts +0 -162
  384. package/templates/apps/mcp/__tests__/lib/content-root.test.ts +0 -93
  385. package/templates/apps/mcp/__tests__/lib/errors.test.ts +0 -75
  386. package/templates/apps/mcp/__tests__/lib/fail-closed-tools.test.ts +0 -180
  387. package/templates/apps/mcp/__tests__/lib/public-workspace.test.ts +0 -124
  388. package/templates/apps/mcp/__tests__/list_pages.test.ts +0 -268
  389. package/templates/apps/mcp/__tests__/locale.test.ts +0 -120
  390. package/templates/apps/mcp/__tests__/module-exclusion.test.ts +0 -175
  391. package/templates/apps/mcp/__tests__/purchase-disabled.test.ts +0 -101
  392. package/templates/apps/mcp/__tests__/rate-limit-write.test.ts +0 -189
  393. package/templates/apps/mcp/__tests__/read_content.test.ts +0 -511
  394. package/templates/apps/mcp/__tests__/request_callback.test.ts +0 -160
  395. package/templates/apps/mcp/__tests__/search_content.test.ts +0 -271
  396. package/templates/apps/mcp/__tests__/server.test.ts +0 -388
  397. package/templates/apps/mcp/__tests__/start_purchase.test.ts +0 -448
  398. package/templates/apps/mcp/__tests__/submit_lead.test.ts +0 -222
  399. package/templates/apps/mcp/__tests__/subscribe_newsletter.test.ts +0 -152
  400. package/templates/apps/mcp/__tests__/tools/create_project.test.ts +0 -243
  401. package/templates/apps/mcp/__tests__/tools/purchase.test.ts +0 -451
  402. package/templates/apps/mcp/src/abuse/daily-cap.ts +0 -47
  403. package/templates/apps/mcp/src/abuse/email-validator.ts +0 -25
  404. package/templates/apps/mcp/src/abuse/honeypot.ts +0 -21
  405. package/templates/apps/mcp/src/abuse/index.ts +0 -349
  406. package/templates/apps/mcp/src/abuse/user-agent-deny.ts +0 -58
  407. package/templates/apps/mcp/src/boot.ts +0 -167
  408. package/templates/apps/mcp/src/config/modules.ts +0 -43
  409. package/templates/apps/mcp/src/http-transport.ts +0 -564
  410. package/templates/apps/mcp/src/lib/audit-single-page.ts +0 -308
  411. package/templates/apps/mcp/src/lib/commerce-claim.ts +0 -263
  412. package/templates/apps/mcp/src/lib/content-adapter.ts +0 -116
  413. package/templates/apps/mcp/src/lib/empty-content-adapter.ts +0 -140
  414. package/templates/apps/mcp/src/lib/errors.ts +0 -61
  415. package/templates/apps/mcp/src/lib/license-key-store.ts +0 -45
  416. package/templates/apps/mcp/src/lib/locales.ts +0 -171
  417. package/templates/apps/mcp/src/lib/prisma.ts +0 -39
  418. package/templates/apps/mcp/src/lib/public-workspace.ts +0 -133
  419. package/templates/apps/mcp/src/lib/resolve-locale.ts +0 -30
  420. package/templates/apps/mcp/src/lib/shown-offerings.ts +0 -105
  421. package/templates/apps/mcp/src/lib/site-config.ts +0 -53
  422. package/templates/apps/mcp/src/lib/stripe-tax-signal.ts +0 -59
  423. package/templates/apps/mcp/src/request-context.ts +0 -52
  424. package/templates/apps/mcp/src/server.ts +0 -343
  425. package/templates/apps/mcp/src/serverless-app.ts +0 -88
  426. package/templates/apps/mcp/src/tools/audit.ts +0 -127
  427. package/templates/apps/mcp/src/tools/capture_lead.ts +0 -66
  428. package/templates/apps/mcp/src/tools/create_project.ts +0 -134
  429. package/templates/apps/mcp/src/tools/get_business_hours.ts +0 -68
  430. package/templates/apps/mcp/src/tools/get_faq.ts +0 -71
  431. package/templates/apps/mcp/src/tools/get_locations.ts +0 -88
  432. package/templates/apps/mcp/src/tools/get_offerings.ts +0 -96
  433. package/templates/apps/mcp/src/tools/get_pricing.ts +0 -94
  434. package/templates/apps/mcp/src/tools/get_site_info.ts +0 -86
  435. package/templates/apps/mcp/src/tools/index.ts +0 -138
  436. package/templates/apps/mcp/src/tools/list_pages.ts +0 -68
  437. package/templates/apps/mcp/src/tools/person_notes.ts +0 -25
  438. package/templates/apps/mcp/src/tools/proposals.ts +0 -27
  439. package/templates/apps/mcp/src/tools/purchase.ts +0 -205
  440. package/templates/apps/mcp/src/tools/read_content.ts +0 -81
  441. package/templates/apps/mcp/src/tools/request_callback.ts +0 -52
  442. package/templates/apps/mcp/src/tools/search_content.ts +0 -63
  443. package/templates/apps/mcp/src/tools/subscribe_newsletter.ts +0 -54
  444. package/templates/apps/mcp/src/workspace-server.ts +0 -224
  445. package/templates/database/CHANGELOG.md +0 -981
  446. package/templates/database/LICENSE +0 -202
  447. package/templates/database/NOTICE +0 -2
  448. package/templates/database/README.md +0 -243
  449. package/templates/database/__tests__/agents.db.test.ts +0 -320
  450. package/templates/database/__tests__/appointment.db.test.ts +0 -106
  451. package/templates/database/__tests__/artifact-content-store.db.test.ts +0 -316
  452. package/templates/database/__tests__/composite-fence.db.test.ts +0 -206
  453. package/templates/database/__tests__/consent-ledger.db.test.ts +0 -345
  454. package/templates/database/__tests__/consent-source-checkout-migration.test.ts +0 -79
  455. package/templates/database/__tests__/fence-fan-out.db.test.ts +0 -715
  456. package/templates/database/__tests__/fixtures/appointment-create-probe.ts +0 -79
  457. package/templates/database/__tests__/fixtures/person-backfill.json +0 -264
  458. package/templates/database/__tests__/fixtures/person-contact-backfill.json +0 -182
  459. package/templates/database/__tests__/fixtures/project-listing-consent-probe.ts +0 -100
  460. package/templates/database/__tests__/flow-completion-migration.test.ts +0 -115
  461. package/templates/database/__tests__/flow-completion.db.test.ts +0 -136
  462. package/templates/database/__tests__/flow-workspace-key.db.test.ts +0 -263
  463. package/templates/database/__tests__/flows-listing-diagnostic.test.ts +0 -392
  464. package/templates/database/__tests__/flows-presets.test.ts +0 -173
  465. package/templates/database/__tests__/in-page-magnets-migration.test.ts +0 -161
  466. package/templates/database/__tests__/lead-idempotency-key.db.test.ts +0 -92
  467. package/templates/database/__tests__/member-area.db.test.ts +0 -257
  468. package/templates/database/__tests__/member-contract-migration.test.ts +0 -85
  469. package/templates/database/__tests__/member-contract.db.test.ts +0 -413
  470. package/templates/database/__tests__/offerings-checkout-session.db.test.ts +0 -270
  471. package/templates/database/__tests__/offerings-migration.test.ts +0 -197
  472. package/templates/database/__tests__/offerings-shown-price-ids-migration.test.ts +0 -86
  473. package/templates/database/__tests__/offerings.db.test.ts +0 -303
  474. package/templates/database/__tests__/outbound-message-action.db.test.ts +0 -80
  475. package/templates/database/__tests__/person-contact.db.test.ts +0 -563
  476. package/templates/database/__tests__/person-notes.db.test.ts +0 -249
  477. package/templates/database/__tests__/person.db.test.ts +0 -586
  478. package/templates/database/__tests__/piece-kind-migration.test.ts +0 -67
  479. package/templates/database/__tests__/piece-kind.db.test.ts +0 -208
  480. package/templates/database/__tests__/prefixed-ids.db.test.ts +0 -222
  481. package/templates/database/__tests__/project-listing-consent-at.db.test.ts +0 -111
  482. package/templates/database/__tests__/seed.test.ts +0 -272
  483. package/templates/database/__tests__/spoke-registry.db.test.ts +0 -191
  484. package/templates/database/__tests__/tenancy.test.ts +0 -141
  485. package/templates/database/__tests__/trial-magnet-migration.test.ts +0 -186
  486. package/templates/database/__tests__/user-cascade.test.ts +0 -140
  487. package/templates/database/_gitignore +0 -8
  488. package/templates/database/auth/.gitkeep +0 -0
  489. package/templates/database/auth/schema.prisma +0 -641
  490. package/templates/database/config/.gitkeep +0 -0
  491. package/templates/database/config/schema.prisma +0 -441
  492. package/templates/database/content/.gitkeep +0 -0
  493. package/templates/database/content/schema.prisma +0 -339
  494. package/templates/database/eslint.config.mjs +0 -69
  495. package/templates/database/flows/listing-diagnostic.ts +0 -182
  496. package/templates/database/flows/presets.ts +0 -315
  497. package/templates/database/inbox/.gitkeep +0 -0
  498. package/templates/database/inbox/README.md +0 -3
  499. package/templates/database/inbox/__tests__/schema.test.ts +0 -44
  500. package/templates/database/inbox/schema.prisma +0 -1447
  501. package/templates/database/jest.config.cjs +0 -36
  502. package/templates/database/migrations/20260508000000_add_inbox_namespace/migration.sql +0 -328
  503. package/templates/database/migrations/20260513000000_better_auth_migration/migration.sql +0 -100
  504. package/templates/database/migrations/20260515000000_add_user_billing_fields/migration.sql +0 -28
  505. package/templates/database/migrations/20260516000000_add_user_tier_care_plan_seat/migration.sql +0 -25
  506. package/templates/database/migrations/20260518000000_add_telemetry_records/migration.sql +0 -42
  507. package/templates/database/migrations/20260525000000_theme_wiring/migration.sql +0 -67
  508. package/templates/database/migrations/20260710000000_retire_commercial_tier/migration.sql +0 -21
  509. package/templates/database/migrations/20260712215647_add_multi_tenant_tenancy/migration.sql +0 -201
  510. package/templates/database/migrations/20260713143320_reanchor_site_config_to_workspace/migration.sql +0 -67
  511. package/templates/database/migrations/20260713174000_add_audit_logs/migration.sql +0 -46
  512. package/templates/database/migrations/20260713190000_drop_telemetry_records/migration.sql +0 -25
  513. package/templates/database/migrations/20260713192000_add_uuidv7_function/migration.sql +0 -49
  514. package/templates/database/migrations/20260713192429_prefixed_uuid_entity_ids/migration.sql +0 -197
  515. package/templates/database/migrations/20260713200000_add_org_billing/migration.sql +0 -32
  516. package/templates/database/migrations/20260714000000_add_lead_promotion_fields/migration.sql +0 -22
  517. package/templates/database/migrations/20260714010000_add_usage_billing_content_models/migration.sql +0 -151
  518. package/templates/database/migrations/20260714020000_add_usage_billing_auth_config_models/migration.sql +0 -223
  519. package/templates/database/migrations/20260714030000_credit_balance_non_negative/migration.sql +0 -22
  520. package/templates/database/migrations/20260714030000_widen_usage_billing_report_aggregates/migration.sql +0 -32
  521. package/templates/database/migrations/20260810233516_add_flow_engine_models/migration.sql +0 -40
  522. package/templates/database/migrations/20260811020000_add_flow_session_abandon_email_columns/migration.sql +0 -4
  523. package/templates/database/migrations/20260811030000_add_flow_session_abandon_email_index/migration.sql +0 -2
  524. package/templates/database/migrations/20260811040000_add_flow_session_segment/migration.sql +0 -2
  525. package/templates/database/migrations/20260811050000_add_deliverable_models/migration.sql +0 -29
  526. package/templates/database/migrations/20260812000000_add_deliverable_grant_send_columns/migration.sql +0 -6
  527. package/templates/database/migrations/20260902222948_add_waitlist_experiment_models/migration.sql +0 -39
  528. package/templates/database/migrations/20260902224500_add_waitlist_id_format_checks/migration.sql +0 -24
  529. package/templates/database/migrations/20260903004112_add_flow_session_flags_aeo_score/migration.sql +0 -3
  530. package/templates/database/migrations/20260903010000_add_playbook_instance/migration.sql +0 -33
  531. package/templates/database/migrations/20260904000000_add_waitlist_followup_send/migration.sql +0 -30
  532. package/templates/database/migrations/20260905230000_add_flow_checkout/migration.sql +0 -47
  533. package/templates/database/migrations/20260906000000_add_flow_checkout_idempotency/migration.sql +0 -16
  534. package/templates/database/migrations/20260907120000_add_project_listing/migration.sql +0 -47
  535. package/templates/database/migrations/20260907130000_add_project_listing_slack_columns/migration.sql +0 -10
  536. package/templates/database/migrations/20260907180000_add_listing_csv_send/migration.sql +0 -26
  537. package/templates/database/migrations/20260909120000_project_listings_platform/migration.sql +0 -90
  538. package/templates/database/migrations/20260909180000_listing_draft_and_fields/migration.sql +0 -174
  539. package/templates/database/migrations/20260910120000_listing_public_site_key/migration.sql +0 -14
  540. package/templates/database/migrations/20260911120000_listing_copy_edit_audit/migration.sql +0 -25
  541. package/templates/database/migrations/20260911140000_listing_structured_address/migration.sql +0 -32
  542. package/templates/database/migrations/20260911180000_consent_grants/migration.sql +0 -71
  543. package/templates/database/migrations/20260911200000_listing_site_answers/migration.sql +0 -30
  544. package/templates/database/migrations/20260912120000_listing_owner_link/migration.sql +0 -49
  545. package/templates/database/migrations/20260914120000_listing_founder_identity/migration.sql +0 -123
  546. package/templates/database/migrations/20260915120000_project_listing_solution/migration.sql +0 -15
  547. package/templates/database/migrations/20260916120000_artifact_content_store/migration.sql +0 -158
  548. package/templates/database/migrations/20260917120000_callback_request_confirm/migration.sql +0 -40
  549. package/templates/database/migrations/20260918120000_add_appointment/migration.sql +0 -67
  550. package/templates/database/migrations/20260918120000_asset_metadata_columns/migration.sql +0 -70
  551. package/templates/database/migrations/20260919120000_flow_workspace_key/migration.sql +0 -181
  552. package/templates/database/migrations/20260919130000_flow_definition_admin_columns/migration.sql +0 -172
  553. package/templates/database/migrations/20260919130000_workspace_meetings/migration.sql +0 -41
  554. package/templates/database/migrations/20260919140000_inbox_workspace_key/migration.sql +0 -185
  555. package/templates/database/migrations/20260920120000_lead_handled_at/migration.sql +0 -70
  556. package/templates/database/migrations/20260920130000_lead_workspace_source_index/migration.sql +0 -57
  557. package/templates/database/migrations/20260921120000_deliverable_grant_workspace_key/migration.sql +0 -68
  558. package/templates/database/migrations/20260922120000_tenancy_fence/migration.sql +0 -1067
  559. package/templates/database/migrations/20260923120000_listing_capturing_magnet/migration.sql +0 -210
  560. package/templates/database/migrations/20261003120000_spoke_registry/migration.sql +0 -80
  561. package/templates/database/migrations/20261003130000_scheduling_connection/migration.sql +0 -49
  562. package/templates/database/migrations/20261005120000_agents/migration.sql +0 -84
  563. package/templates/database/migrations/20261008120000_user_last_workspace/migration.sql +0 -35
  564. package/templates/database/migrations/20261008130000_lead_idempotency_key/migration.sql +0 -20
  565. package/templates/database/migrations/20261009120000_agent_grants/migration.sql +0 -33
  566. package/templates/database/migrations/20261010120000_person/migration.sql +0 -106
  567. package/templates/database/migrations/20261010121000_person_backfill/migration.sql +0 -132
  568. package/templates/database/migrations/20261010130000_agent_grants_people_read/migration.sql +0 -20
  569. package/templates/database/migrations/20261011120000_member_area/migration.sql +0 -158
  570. package/templates/database/migrations/20261011130000_agent_grants_member_pieces_manage/migration.sql +0 -21
  571. package/templates/database/migrations/20261012120000_member_contract/migration.sql +0 -192
  572. package/templates/database/migrations/20261013120000_lead_spoke_checkout/migration.sql +0 -20
  573. package/templates/database/migrations/20261014120000_consent_ledger/migration.sql +0 -122
  574. package/templates/database/migrations/20261014120000_person_contact/migration.sql +0 -231
  575. package/templates/database/migrations/20261015120000_person_notes/migration.sql +0 -77
  576. package/templates/database/migrations/20261015120000_rate_limit_counters/migration.sql +0 -43
  577. package/templates/database/migrations/20261016120000_piece_kind/migration.sql +0 -95
  578. package/templates/database/migrations/20261017120000_outbound_message_action/migration.sql +0 -30
  579. package/templates/database/migrations/20261018120000_flow_completion/migration.sql +0 -52
  580. package/templates/database/migrations/20261019120000_consent_source_checkout/migration.sql +0 -27
  581. package/templates/database/migrations/20261020120000_offerings_data_model/migration.sql +0 -146
  582. package/templates/database/migrations/20261021120000_offerings_checkout_session/migration.sql +0 -77
  583. package/templates/database/migrations/20261022120000_in_page_magnets/migration.sql +0 -45
  584. package/templates/database/migrations/20261023120000_offerings_shown_price_ids/migration.sql +0 -47
  585. package/templates/database/migrations/20261024120000_organization_plan_checkout_session/migration.sql +0 -16
  586. package/templates/database/migrations/20261025120000_trial_magnet/migration.sql +0 -28
  587. package/templates/database/migrations/20261026120000_trial_magnet_proof_line/migration.sql +0 -23
  588. package/templates/database/migrations/migration_lock.toml +0 -3
  589. package/templates/database/ops/.gitkeep +0 -0
  590. package/templates/database/ops/schema.prisma +0 -43
  591. package/templates/database/package.json +0 -89
  592. package/templates/database/schema.prisma +0 -71
  593. package/templates/database/scripts/db-generate-locked.sh +0 -80
  594. package/templates/database/scripts/person-backfill.sql +0 -132
  595. package/templates/database/tenancy.ts +0 -183
  596. package/templates/database/tsconfig.build.json +0 -16
  597. package/templates/database/tsconfig.flows.json +0 -15
  598. package/templates/database/tsconfig.json +0 -16
  599. package/templates/database/tsconfig.tenancy.json +0 -14
@@ -1,1409 +0,0 @@
1
- /**
2
- * @file rate-limit.test.ts
3
- * Unit tests for the per-IP rate limit middleware (B5).
4
- *
5
- * Test runner: Jest (repo convention — jest.config.cjs uses ts-jest).
6
- * Time control: jest.spyOn(Date, 'now') for the window-rolls case. We
7
- * intentionally avoid jest.useFakeTimers() because it intercepts setImmediate,
8
- * which Fastify's avvio plugin system uses during app.ready() — causing all
9
- * tests to hang. Controlling Date.now() directly is sufficient since the
10
- * middleware's window logic only calls Date.now().
11
- * IP mocking: x-forwarded-for header on a trustProxy:true test server.
12
- *
13
- * Spec: docs/internal/specs/draft/ailk-mcp-mvp-pb-b5-rate-limit-spec.md
14
- */
15
-
16
- import Fastify, { type FastifyInstance } from "fastify";
17
- import {
18
- rateLimitMiddleware,
19
- __resetBuckets,
20
- __bucketCount,
21
- FORWARDED_VISITOR_ROUTES,
22
- buildTrustedKeyDigests,
23
- DEFAULT_PER_IP_PER_MINUTE_STRICT,
24
- resolveRateLimitIdentity,
25
- siteKeyReader,
26
- SITE_KEYED_ROUTES,
27
- DEFAULT_SIGNUPEVIDENCE_PER_KEY_PER_MINUTE,
28
- type RateLimitOptions,
29
- } from "../rate-limit.js";
30
-
31
- function buildApp(
32
- opts: { perIpPerMinute?: number; windowMs?: number; maxBuckets?: number } = {},
33
- ) {
34
- const app = Fastify({ trustProxy: true });
35
- app.register(rateLimitMiddleware, opts);
36
- app.get("/test", async () => ({ ok: true }));
37
- return app;
38
- }
39
-
40
- describe("per-IP rate limit middleware", () => {
41
- let app: ReturnType<typeof buildApp>;
42
-
43
- beforeEach(async () => {
44
- __resetBuckets();
45
- });
46
-
47
- afterEach(async () => {
48
- await app.close();
49
- });
50
-
51
- it("allows requests within the per-minute budget (5 under default)", async () => {
52
- app = buildApp({ perIpPerMinute: 10 });
53
- await app.ready();
54
-
55
- for (let i = 0; i < 5; i++) {
56
- const res = await app.inject({
57
- method: "GET",
58
- url: "/test",
59
- headers: { "x-forwarded-for": "1.2.3.4" },
60
- });
61
- expect(res.statusCode).toBe(200);
62
- }
63
- });
64
-
65
- it("returns 429 on the 11th request within the window", async () => {
66
- app = buildApp({ perIpPerMinute: 10 });
67
- await app.ready();
68
-
69
- for (let i = 0; i < 10; i++) {
70
- const res = await app.inject({
71
- method: "GET",
72
- url: "/test",
73
- headers: { "x-forwarded-for": "1.2.3.4" },
74
- });
75
- expect(res.statusCode).toBe(200);
76
- }
77
-
78
- const overLimit = await app.inject({
79
- method: "GET",
80
- url: "/test",
81
- headers: { "x-forwarded-for": "1.2.3.4" },
82
- });
83
- expect(overLimit.statusCode).toBe(429);
84
- const body = JSON.parse(overLimit.body);
85
- expect(body).toMatchObject({ error: "rate_limited" });
86
- expect(typeof body.retryAfterSeconds).toBe("number");
87
- });
88
-
89
- it("resets the budget after the window expires", async () => {
90
- // windowMs is passed explicitly so the spy's return value uses the same window the middleware sees.
91
- const windowMs = 60_000;
92
- app = buildApp({ perIpPerMinute: 2, windowMs });
93
- await app.ready();
94
-
95
- const origin = Date.now();
96
- const dateSpy = jest.spyOn(Date, "now").mockReturnValue(origin);
97
-
98
- try {
99
- // Exhaust the budget.
100
- for (let i = 0; i < 2; i++) {
101
- await app.inject({
102
- method: "GET",
103
- url: "/test",
104
- headers: { "x-forwarded-for": "1.2.3.4" },
105
- });
106
- }
107
-
108
- // Advance virtual time past the window.
109
- dateSpy.mockReturnValue(origin + windowMs + 1);
110
-
111
- // First request in the new window should succeed.
112
- const afterRoll = await app.inject({
113
- method: "GET",
114
- url: "/test",
115
- headers: { "x-forwarded-for": "1.2.3.4" },
116
- });
117
- expect(afterRoll.statusCode).toBe(200);
118
- } finally {
119
- dateSpy.mockRestore();
120
- }
121
- });
122
-
123
- it("includes Retry-After header <= 60 on 429 responses", async () => {
124
- app = buildApp({ perIpPerMinute: 1 });
125
- await app.ready();
126
-
127
- // Use the budget.
128
- await app.inject({
129
- method: "GET",
130
- url: "/test",
131
- headers: { "x-forwarded-for": "10.0.0.1" },
132
- });
133
-
134
- // Trigger 429.
135
- const over = await app.inject({
136
- method: "GET",
137
- url: "/test",
138
- headers: { "x-forwarded-for": "10.0.0.1" },
139
- });
140
-
141
- expect(over.statusCode).toBe(429);
142
- const retryAfter = Number(over.headers["retry-after"]);
143
- expect(Number.isInteger(retryAfter)).toBe(true);
144
- expect(retryAfter).toBeGreaterThanOrEqual(1);
145
- expect(retryAfter).toBeLessThanOrEqual(60);
146
- });
147
-
148
- it("tracks independent buckets per IP", async () => {
149
- app = buildApp({ perIpPerMinute: 2 });
150
- await app.ready();
151
-
152
- // Exhaust IP A.
153
- for (let i = 0; i < 2; i++) {
154
- await app.inject({
155
- method: "GET",
156
- url: "/test",
157
- headers: { "x-forwarded-for": "192.168.1.1" },
158
- });
159
- }
160
- const ipA429 = await app.inject({
161
- method: "GET",
162
- url: "/test",
163
- headers: { "x-forwarded-for": "192.168.1.1" },
164
- });
165
- expect(ipA429.statusCode).toBe(429);
166
-
167
- // IP B should still have a fresh budget.
168
- const ipB = await app.inject({
169
- method: "GET",
170
- url: "/test",
171
- headers: { "x-forwarded-for": "192.168.1.2" },
172
- });
173
- expect(ipB.statusCode).toBe(200);
174
- });
175
-
176
- it("derives independent buckets from the ORIGINATING address when two visitors share a proxy hop (#4730)", async () => {
177
- // Simulates a consumer site's Next.js server action forwarding the
178
- // visitor's real IP as x-forwarded-for, with this API's own edge then
179
- // appending the calling web function's shared egress IP as a second
180
- // hop — the exact multi-hop shape a consumer double-hop produces
181
- // (apps/web/app/[locale]/flows/[slug]/flow.actions.ts). With
182
- // trustProxy:true, req.ip resolves to the LEFTMOST (originating)
183
- // address, so two visitors sharing the same egress hop still get
184
- // independent buckets — this is the failure #4730 reports: before the
185
- // fix, ALL visitors behind one web function's egress IP shared ONE
186
- // bucket.
187
- app = buildApp({ perIpPerMinute: 1 });
188
- await app.ready();
189
- const SHARED_EGRESS = "9.9.9.9";
190
-
191
- const visitorA = await app.inject({
192
- method: "GET",
193
- url: "/test",
194
- headers: { "x-forwarded-for": `20.0.0.1, ${SHARED_EGRESS}` },
195
- });
196
- expect(visitorA.statusCode).toBe(200);
197
-
198
- // Visitor A's own second request, still behind the shared egress hop,
199
- // correctly trips ITS OWN (now-exhausted) bucket.
200
- const visitorAOverLimit = await app.inject({
201
- method: "GET",
202
- url: "/test",
203
- headers: { "x-forwarded-for": `20.0.0.1, ${SHARED_EGRESS}` },
204
- });
205
- expect(visitorAOverLimit.statusCode).toBe(429);
206
-
207
- // Visitor B, behind the SAME shared egress hop, still has a fresh
208
- // budget — the two are bucketed on the leftmost (visitor) address, not
209
- // the shared egress IP.
210
- const visitorB = await app.inject({
211
- method: "GET",
212
- url: "/test",
213
- headers: { "x-forwarded-for": `20.0.0.2, ${SHARED_EGRESS}` },
214
- });
215
- expect(visitorB.statusCode).toBe(200);
216
- });
217
-
218
- it("respects custom perIpPerMinute option over env/default", async () => {
219
- app = buildApp({ perIpPerMinute: 3 });
220
- await app.ready();
221
-
222
- // 3 requests should succeed.
223
- for (let i = 0; i < 3; i++) {
224
- const res = await app.inject({
225
- method: "GET",
226
- url: "/test",
227
- headers: { "x-forwarded-for": "5.5.5.5" },
228
- });
229
- expect(res.statusCode).toBe(200);
230
- }
231
-
232
- // 4th exceeds the custom limit of 3.
233
- const fourth = await app.inject({
234
- method: "GET",
235
- url: "/test",
236
- headers: { "x-forwarded-for": "5.5.5.5" },
237
- });
238
- expect(fourth.statusCode).toBe(429);
239
- });
240
-
241
- it("reads perIpPerMinute from AILK_RATE_LIMIT_PER_IP_PER_MINUTE env var when option is absent", async () => {
242
- // Cover `Number(process.env.AILK_RATE_LIMIT_PER_IP_PER_MINUTE) || 20` left-side truthy arm
243
- // Build the app without a perIpPerMinute option so the env var path is taken
244
- const prev = process.env.AILK_RATE_LIMIT_PER_IP_PER_MINUTE;
245
- process.env.AILK_RATE_LIMIT_PER_IP_PER_MINUTE = "2";
246
- try {
247
- app = buildApp({}); // no perIpPerMinute — env var drives the limit
248
- await app.ready();
249
-
250
- // 2 requests should succeed (env-configured limit).
251
- for (let i = 0; i < 2; i++) {
252
- const res = await app.inject({
253
- method: "GET",
254
- url: "/test",
255
- headers: { "x-forwarded-for": "7.7.7.7" },
256
- });
257
- expect(res.statusCode).toBe(200);
258
- }
259
-
260
- // 3rd request exceeds the env-configured limit of 2.
261
- const third = await app.inject({
262
- method: "GET",
263
- url: "/test",
264
- headers: { "x-forwarded-for": "7.7.7.7" },
265
- });
266
- expect(third.statusCode).toBe(429);
267
- } finally {
268
- if (prev === undefined) {
269
- delete process.env.AILK_RATE_LIMIT_PER_IP_PER_MINUTE;
270
- } else {
271
- process.env.AILK_RATE_LIMIT_PER_IP_PER_MINUTE = prev;
272
- }
273
- }
274
- });
275
-
276
- it("evicts stale buckets when cleanup is triggered on 429 with a stale IP in store", async () => {
277
- // Cover the stale-bucket delete arm inside evictStaleBuckets (line 54)
278
- // Scenario: IP A exhausts budget at t=0, time advances past window, IP B hits 429 — cleanup evicts A's stale bucket
279
- const windowMs = 60_000;
280
- app = buildApp({ perIpPerMinute: 1, windowMs });
281
- await app.ready();
282
-
283
- const origin = Date.now();
284
- const dateSpy = jest.spyOn(Date, "now").mockReturnValue(origin);
285
-
286
- try {
287
- // Exhaust IP A's budget at t=0.
288
- await app.inject({
289
- method: "GET",
290
- url: "/test",
291
- headers: { "x-forwarded-for": "11.0.0.1" },
292
- });
293
-
294
- // Advance virtual time past the window so IP A's bucket is now stale.
295
- dateSpy.mockReturnValue(origin + windowMs + 1);
296
-
297
- // Exhaust IP B's budget (fresh window).
298
- await app.inject({
299
- method: "GET",
300
- url: "/test",
301
- headers: { "x-forwarded-for": "11.0.0.2" },
302
- });
303
-
304
- // IP B's 2nd request triggers 429 → calls evictStaleBuckets → deletes IP A's stale bucket.
305
- const res = await app.inject({
306
- method: "GET",
307
- url: "/test",
308
- headers: { "x-forwarded-for": "11.0.0.2" },
309
- });
310
-
311
- expect(res.statusCode).toBe(429);
312
- // Cleanup ran — IP A's stale bucket was deleted. IP A can now make fresh requests.
313
- const resA = await app.inject({
314
- method: "GET",
315
- url: "/test",
316
- headers: { "x-forwarded-for": "11.0.0.1" },
317
- });
318
- expect(resA.statusCode).toBe(200);
319
- } finally {
320
- dateSpy.mockRestore();
321
- }
322
- });
323
-
324
- it("triggers periodic cleanup after 100 requests in a single window", async () => {
325
- // Cover `requestsSinceLastClean >= CLEAN_INTERVAL_REQUESTS` true arm (line 93)
326
- // 100 requests from distinct IPs fill the bucket store; the 101st triggers eviction
327
- app = buildApp({ perIpPerMinute: 200 }); // high limit so no 429 for first 100 requests
328
- await app.ready();
329
-
330
- // Send 100 requests from distinct IPs to advance requestsSinceLastClean to 100.
331
- for (let i = 0; i < 100; i++) {
332
- await app.inject({
333
- method: "GET",
334
- url: "/test",
335
- headers: { "x-forwarded-for": `10.${Math.floor(i / 255)}.${i % 255}.1` },
336
- });
337
- }
338
-
339
- // The 101st request (any IP) crosses the CLEAN_INTERVAL_REQUESTS threshold.
340
- const res = await app.inject({
341
- method: "GET",
342
- url: "/test",
343
- headers: { "x-forwarded-for": "10.1.0.99" },
344
- });
345
- // Cleanup fired — the route still responds normally.
346
- expect(res.statusCode).toBe(200);
347
- });
348
-
349
- it("caps total distinct buckets at maxBuckets, evicting the oldest-inserted entry on overflow (#5111/#4780 AC-3)", async () => {
350
- // A caller minting a fresh identity every request (e.g. a spoofed
351
- // X-Forwarded-For under trustProxy:true) must not grow the in-house
352
- // buckets Map without bound — independent of the EXISTING time-based
353
- // eviction (which only fires on stale/expired windows). This test
354
- // never lets any window expire, so ONLY the new entry-count cap can
355
- // be responsible for keeping distinct-bucket growth bounded. A small
356
- // maxBuckets is passed explicitly so the test doesn't need thousands
357
- // of injected requests to reach the real production default.
358
- const maxBuckets = 3;
359
- app = buildApp({ perIpPerMinute: 200, maxBuckets });
360
- await app.ready();
361
-
362
- for (let i = 0; i < maxBuckets; i++) {
363
- const res = await app.inject({
364
- method: "GET",
365
- url: "/test",
366
- headers: { "x-forwarded-for": `172.16.0.${i}` },
367
- });
368
- expect(res.statusCode).toBe(200);
369
- expect(__bucketCount()).toBe(i + 1);
370
- }
371
-
372
- // A 4th distinct identity must not push the store past maxBuckets —
373
- // the oldest-inserted bucket is evicted to make room.
374
- const overflowRes = await app.inject({
375
- method: "GET",
376
- url: "/test",
377
- headers: { "x-forwarded-for": "203.0.113.99" },
378
- });
379
- expect(overflowRes.statusCode).toBe(200);
380
- expect(__bucketCount()).toBe(maxBuckets);
381
- });
382
-
383
- it("exposes DEFAULT_PER_IP_PER_MINUTE_STRICT as the pre-#4730 per-scope default (10/min)", () => {
384
- expect(DEFAULT_PER_IP_PER_MINUTE_STRICT).toBe(10);
385
- });
386
- });
387
-
388
- /**
389
- * Cross-isolate demonstration (#5040 AC-1).
390
- *
391
- * The middleware's `buckets` store is module-scoped (see the module
392
- * docstring's SINGLE-REPLICA CAVEAT) — it is per-process state, not a
393
- * shared external store. On the real deployment target this means: each
394
- * serverless isolate that cold-loads this module gets its own empty Map,
395
- * so the same visitor IP is tracked independently per isolate rather than
396
- * against one shared counter.
397
- *
398
- * This process cannot spin up two real Vercel isolates (no live target —
399
- * see #5040's issue comment + docs/specs/5111-limiter-surface-spec.md §8
400
- * for the exact probe attempted and why it could not reach one as of
401
- * 2026-09-15). What IS fully within this process's control is the root
402
- * mechanism itself: module-scoped state does not survive a fresh module
403
- * load. `jest.isolateModules` gives each block below its own Jest module
404
- * registry, so requiring the middleware module inside each returns a
405
- * DISTINCT module instance with its own private `buckets` Map — the same
406
- * state-isolation shape a serverless cold start produces (a fresh module
407
- * load with an empty Map), reproduced deterministically in-process.
408
- *
409
- * This demonstrates — rather than merely asserts, per AC-1's own wording —
410
- * that the per-IP limit, UNDER THE MEMORY STORE, does NOT hold across
411
- * separate execution contexts: the same IP, already rate-limited to
412
- * exhaustion on one instance, is granted a fresh budget on another. This
413
- * pins the memory store's own documented trade-off (the SINGLE-REPLICA
414
- * CAVEAT) now that a database deployment defaults to the shared store
415
- * instead (#5040 D1/D4) — this test makes that trade-off provable rather
416
- * than only claimed in a comment, and will fail (correctly) if the memory
417
- * store's isolation is ever accidentally narrowed.
418
- *
419
- * What this test does NOT demonstrate: whether the LIVE deployment
420
- * actually runs more than one concurrent isolate for a given route today,
421
- * nor the database store's own cross-isolate behavior — that is
422
- * `rate-limit-cross-isolate.db.test.ts`'s job (#5040 AC-1).
423
- */
424
- describe("cross-isolate limit — the memory store does not hold by design (#5040, SINGLE-REPLICA CAVEAT)", () => {
425
- it("the same IP, exhausted on one module instance, is freshly allowed on an independently-loaded instance", async () => {
426
- const perIpPerMinute = 5;
427
- const ip = "198.51.100.7";
428
-
429
- let isolateAppA: ReturnType<typeof buildApp> | undefined;
430
- let isolateAppB: ReturnType<typeof buildApp> | undefined;
431
-
432
- // Each isolateModules block gets a fresh require cache: requiring the
433
- // middleware module inside it yields a module instance distinct from
434
- // the top-level `rateLimitMiddleware` import used by every other test
435
- // in this file (and distinct from each other).
436
- jest.isolateModules(() => {
437
- const isolateA: typeof import("../rate-limit") = require("../rate-limit");
438
- const app = Fastify({ trustProxy: true });
439
- app.register(isolateA.rateLimitMiddleware, { perIpPerMinute });
440
- app.get("/test", async () => ({ ok: true }));
441
- isolateAppA = app;
442
- });
443
-
444
- jest.isolateModules(() => {
445
- const isolateB: typeof import("../rate-limit") = require("../rate-limit");
446
- const app = Fastify({ trustProxy: true });
447
- app.register(isolateB.rateLimitMiddleware, { perIpPerMinute });
448
- app.get("/test", async () => ({ ok: true }));
449
- isolateAppB = app;
450
- });
451
-
452
- if (!isolateAppA || !isolateAppB) {
453
- throw new Error("isolateModules did not synchronously assign both apps");
454
- }
455
-
456
- await isolateAppA.ready();
457
- await isolateAppB.ready();
458
-
459
- try {
460
- // Exhaust isolate A's per-IP budget entirely.
461
- for (let i = 0; i < perIpPerMinute; i++) {
462
- const res = await isolateAppA.inject({
463
- method: "GET",
464
- url: "/test",
465
- headers: { "x-forwarded-for": ip },
466
- });
467
- expect(res.statusCode).toBe(200);
468
- }
469
- const exhaustedOnA = await isolateAppA.inject({
470
- method: "GET",
471
- url: "/test",
472
- headers: { "x-forwarded-for": ip },
473
- });
474
- expect(exhaustedOnA.statusCode).toBe(429);
475
-
476
- // The SAME ip, already 429'd on A, hits an independently-loaded
477
- // instance (B) for the first time — B's own buckets Map has never
478
- // seen this IP, so it is granted a full fresh budget rather than
479
- // being held to the aggregate limit across A+B. This is the
480
- // cross-isolate gap: (perIpPerMinute × isolate count) requests
481
- // succeed in aggregate for one IP, not perIpPerMinute.
482
- const firstOnB = await isolateAppB.inject({
483
- method: "GET",
484
- url: "/test",
485
- headers: { "x-forwarded-for": ip },
486
- });
487
- expect(firstOnB.statusCode).toBe(200);
488
- } finally {
489
- await isolateAppA.close();
490
- await isolateAppB.close();
491
- }
492
- });
493
- });
494
-
495
- // #6019 AC-2 — the `pathOnly` split (#5970 security review, finding 1): a
496
- // route may carry its credential in the query string
497
- // (`/v1/requests/:id/confirm?token=…` does), and a 429 is a line an attacker
498
- // can provoke at will by tripping the limiter — logging the raw target would
499
- // let them farm credentials out of the operator's own log that way.
500
- describe("rate-limit warn log — no query-string credential (#5970)", () => {
501
- it("scrubs the query string from the logged path on a 429", async () => {
502
- __resetBuckets();
503
- const logLines: Array<Record<string, unknown>> = [];
504
- const app = Fastify({
505
- trustProxy: true,
506
- logger: {
507
- level: "warn",
508
- stream: {
509
- write(msg: string) {
510
- logLines.push(JSON.parse(msg) as Record<string, unknown>);
511
- },
512
- },
513
- },
514
- });
515
- app.register(rateLimitMiddleware, { perIpPerMinute: 1 });
516
- app.get("/v1/requests/:id/confirm", async () => ({ ok: true }));
517
- await app.ready();
518
-
519
- try {
520
- const url = "/v1/requests/callbk_1/confirm?token=SUPERSECRETTOKEN";
521
- const headers = { "x-forwarded-for": "1.2.3.4" };
522
- await app.inject({ method: "GET", url, headers });
523
- const limited = await app.inject({ method: "GET", url, headers });
524
- expect(limited.statusCode).toBe(429);
525
-
526
- const logged = logLines.find((line) => line["msg"] === "rate_limited");
527
- expect(logged?.["path"]).toBe("/v1/requests/callbk_1/confirm");
528
- const text = JSON.stringify(logLines);
529
- expect(text).not.toContain("SUPERSECRETTOKEN");
530
- expect(text).not.toContain("token=");
531
- } finally {
532
- await app.close();
533
- }
534
- });
535
- });
536
-
537
- // #7394 — per-visitor leads limit for a server-to-server spoke
538
- // (docs/specs/7394-the-leads-rate-limit-scope-spec.md). Every route below is
539
- // `POST /v1/leads/submit` unless a case says otherwise, so it is in
540
- // `FORWARDED_VISITOR_ROUTES`. "The key" is one 64-character key passed
541
- // through `buildTrustedKeyDigests`.
542
- describe("per-visitor forwarding, scope namespace and per-scope env limit (#7394)", () => {
543
- const KEY = "0123456789abcdef".repeat(4); // gitleaks:allow — test fixture, not a credential (#7394)
544
- const SPOKE_HOST = "198.51.100.7";
545
- const LEADS_SUBMIT = "/v1/leads/submit";
546
- const ENV_KEYS = [
547
- "AILK_RATE_LIMIT_LEADS_PER_MINUTE",
548
- "AILK_RATE_LIMIT_LEADS_PER_KEY_PER_MINUTE",
549
- "AILK_RATE_LIMIT_PER_IP_PER_MINUTE",
550
- ] as const;
551
- const priorEnv = new Map<string, string | undefined>(
552
- ENV_KEYS.map((name) => [name, process.env[name]]),
553
- );
554
-
555
- const noWarn = () => undefined;
556
- const digests = () => buildTrustedKeyDigests(KEY, noWarn);
557
-
558
- let app: FastifyInstance | undefined;
559
- let logLines: Array<Record<string, unknown>>;
560
-
561
- function forwardApp(
562
- opts: RateLimitOptions,
563
- routes: readonly string[] = [LEADS_SUBMIT],
564
- ): FastifyInstance {
565
- const instance = Fastify({
566
- trustProxy: true,
567
- logger: {
568
- level: "warn",
569
- stream: {
570
- write(msg: string) {
571
- logLines.push(JSON.parse(msg) as Record<string, unknown>);
572
- },
573
- },
574
- },
575
- });
576
- instance.register(rateLimitMiddleware, opts);
577
- for (const url of routes) instance.post(url, async () => ({ ok: true }));
578
- return instance;
579
- }
580
-
581
- function keyed(visitorIp: string, key: string = KEY): Record<string, string> {
582
- return {
583
- "x-forwarded-for": SPOKE_HOST,
584
- "x-ailk-visitor-forward-key": key,
585
- "x-ailk-visitor-ip": visitorIp,
586
- };
587
- }
588
-
589
- async function post(
590
- headers: Record<string, string>,
591
- url: string = LEADS_SUBMIT,
592
- ): Promise<number> {
593
- if (!app) throw new Error("no app");
594
- const res = await app.inject({ method: "POST", url, headers });
595
- return res.statusCode;
596
- }
597
-
598
- function rateLimitedLines(): Array<Record<string, unknown>> {
599
- return logLines.filter((line) => line["msg"] === "rate_limited");
600
- }
601
-
602
- beforeEach(() => {
603
- __resetBuckets();
604
- logLines = [];
605
- for (const name of ENV_KEYS) delete process.env[name];
606
- });
607
-
608
- afterEach(async () => {
609
- if (app) await app.close();
610
- app = undefined;
611
- });
612
-
613
- afterAll(() => {
614
- for (const [name, value] of priorEnv) {
615
- if (value === undefined) delete process.env[name];
616
- else process.env[name] = value;
617
- }
618
- });
619
-
620
- describe("AC-1 — AILK_RATE_LIMIT_<SCOPE>_PER_MINUTE overrides the code value", () => {
621
- async function firstRefused(): Promise<number> {
622
- const headers = { "x-forwarded-for": "203.0.113.50" };
623
- for (let i = 1; i <= 50; i++) {
624
- if ((await post(headers)) === 429) return i;
625
- }
626
- return -1;
627
- }
628
-
629
- it("the env var wins over perIpPerMinute", async () => {
630
- process.env.AILK_RATE_LIMIT_LEADS_PER_MINUTE = "3";
631
- app = forwardApp({ scope: "leads", perIpPerMinute: 10 });
632
- await app.ready();
633
- expect(await firstRefused()).toBe(4);
634
- });
635
-
636
- it("with the env var unset, the code value applies", async () => {
637
- app = forwardApp({ scope: "leads", perIpPerMinute: 10 });
638
- await app.ready();
639
- expect(await firstRefused()).toBe(11);
640
- });
641
-
642
- it("an invalid env var is ignored, with one warning naming the variable", async () => {
643
- process.env.AILK_RATE_LIMIT_LEADS_PER_MINUTE = "abc";
644
- app = forwardApp({ scope: "leads", perIpPerMinute: 10 });
645
- await app.ready();
646
- expect(await firstRefused()).toBe(11);
647
- const warnings = logLines.filter((line) =>
648
- String(line["msg"]).includes("AILK_RATE_LIMIT_LEADS_PER_MINUTE"),
649
- );
650
- expect(warnings).toHaveLength(1);
651
- });
652
-
653
- it.each(["0", "-5", "2.5", "1000000"])(
654
- "ignores the out-of-range value %s",
655
- async (value) => {
656
- process.env.AILK_RATE_LIMIT_LEADS_PER_MINUTE = value;
657
- app = forwardApp({ scope: "leads", perIpPerMinute: 10 });
658
- await app.ready();
659
- expect(await firstRefused()).toBe(11);
660
- },
661
- );
662
-
663
- it("does not read AILK_RATE_LIMIT_PER_IP_PER_MINUTE for a named scope with a code value", async () => {
664
- process.env.AILK_RATE_LIMIT_PER_IP_PER_MINUTE = "2";
665
- app = forwardApp({ scope: "leads", perIpPerMinute: 10 });
666
- await app.ready();
667
- expect(await firstRefused()).toBe(11);
668
- });
669
- });
670
-
671
- describe("AC-2 — a named scope gets its own bucket namespace", () => {
672
- function twoScopes(second: RateLimitOptions): FastifyInstance {
673
- const instance = Fastify({ trustProxy: true });
674
- instance.register(async (child) => {
675
- child.register(rateLimitMiddleware, { perIpPerMinute: 10 });
676
- child.post("/a", async () => ({ ok: true }));
677
- });
678
- instance.register(async (child) => {
679
- child.register(rateLimitMiddleware, second);
680
- child.post("/b", async () => ({ ok: true }));
681
- });
682
- return instance;
683
- }
684
- const headers = { "x-forwarded-for": "203.0.113.60" };
685
-
686
- it("ten /a requests do not spend the leads scope's budget", async () => {
687
- app = twoScopes({ scope: "leads", perIpPerMinute: 10 });
688
- await app.ready();
689
- for (let i = 0; i < 10; i++) expect(await post(headers, "/a")).toBe(200);
690
- for (let i = 0; i < 10; i++) expect(await post(headers, "/b")).toBe(200);
691
- expect(await post(headers, "/b")).toBe(429);
692
- });
693
-
694
- it("two unnamed registrations still share their count, as at the pin", async () => {
695
- app = twoScopes({ perIpPerMinute: 10 });
696
- await app.ready();
697
- for (let i = 0; i < 10; i++) expect(await post(headers, "/a")).toBe(200);
698
- expect(await post(headers, "/b")).toBe(429);
699
- });
700
- });
701
-
702
- describe("AC-3 — a keyed lead write is counted per visitor", () => {
703
- it("limits each forwarded visitor separately behind one spoke host", async () => {
704
- app = forwardApp({
705
- scope: "leads",
706
- perIpPerMinute: 10,
707
- perKeyPerMinute: 300,
708
- trustedKeyDigests: digests(),
709
- });
710
- await app.ready();
711
- for (let i = 0; i < 10; i++) expect(await post(keyed("203.0.113.1"))).toBe(200);
712
- expect(await post(keyed("203.0.113.1"))).toBe(429);
713
- expect(await post(keyed("203.0.113.2"))).toBe(200);
714
- });
715
- });
716
-
717
- describe("AC-4 — the visitor header is ignored without the key, or off the lead writes", () => {
718
- const WRONG_SAME_LENGTH = "f".repeat(64);
719
- const ONE_CHAR_CHANGED = `${KEY.slice(0, -1)}0`;
720
-
721
- async function elevenDistinctVisitors(
722
- headersFor: (visitorIp: string) => Record<string, string>,
723
- url: string = LEADS_SUBMIT,
724
- ): Promise<number[]> {
725
- const codes: number[] = [];
726
- for (let i = 1; i <= 11; i++) codes.push(await post(headersFor(`203.0.113.${i}`), url));
727
- return codes;
728
- }
729
-
730
- const base = {
731
- scope: "leads",
732
- perIpPerMinute: 10,
733
- perKeyPerMinute: 300,
734
- } as const;
735
-
736
- it.each([
737
- [
738
- "(i) no key",
739
- (ip: string) => ({ "x-forwarded-for": SPOKE_HOST, "x-ailk-visitor-ip": ip }),
740
- ],
741
- ["(ii) a wrong key of the same length", (ip: string) => keyed(ip, WRONG_SAME_LENGTH)],
742
- ["(iii) the right key with one character changed", (ip: string) => keyed(ip, ONE_CHAR_CHANGED)],
743
- ])("%s: the eleventh request is 429", async (_label, headersFor) => {
744
- app = forwardApp({ ...base, trustedKeyDigests: digests() });
745
- await app.ready();
746
- const codes = await elevenDistinctVisitors(headersFor);
747
- expect(codes.slice(0, 10).every((code) => code === 200)).toBe(true);
748
- expect(codes[10]).toBe(429);
749
- });
750
-
751
- it("(iv) the valid key, but no trustedKeyDigests passed: the eleventh request is 429", async () => {
752
- app = forwardApp(base);
753
- await app.ready();
754
- const codes = await elevenDistinctVisitors((ip) => keyed(ip));
755
- expect(codes[10]).toBe(429);
756
- });
757
-
758
- // `POST /v1/project-listings` joined the list with #7479; the resume
759
- // link's verification write shares its scope and stays off the list.
760
- it("(v) the valid key on POST /v1/project-listings/drafts/:id/verify-email in the same scope: the eleventh request is 429", async () => {
761
- app = forwardApp({ ...base, trustedKeyDigests: digests() }, [
762
- LEADS_SUBMIT,
763
- "/v1/project-listings/drafts/:id/verify-email",
764
- ]);
765
- await app.ready();
766
- const codes = await elevenDistinctVisitors(
767
- (ip) => keyed(ip),
768
- "/v1/project-listings/drafts/listing_abc/verify-email",
769
- );
770
- expect(codes.slice(0, 10).every((code) => code === 200)).toBe(true);
771
- expect(codes[10]).toBe(429);
772
- });
773
- });
774
-
775
- // #7633 conductor amendment (the relay's security review, #7644): once a
776
- // site relays its visitors' booking calls, every one reaches the hub from
777
- // the site's server. The two relayed schedule routes join the keyed-visitor
778
- // list, each under its own method only.
779
- describe("the two relayed schedule routes count each keyed visitor separately (#7633)", () => {
780
- const AVAILABILITY = "/v1/schedule/availability";
781
- const BOOK = "/v1/schedule/book";
782
- const EVENT_META = "/v1/schedule/event-meta";
783
-
784
- /** A schedule-shaped scope: the four routes, each under GET and POST. */
785
- function scheduleApp(): FastifyInstance {
786
- const instance = Fastify({ trustProxy: true });
787
- instance.register(rateLimitMiddleware, {
788
- scope: "schedule",
789
- perIpPerMinute: 10,
790
- perKeyPerMinute: 300,
791
- trustedKeyDigests: digests(),
792
- });
793
- for (const url of [AVAILABILITY, BOOK, EVENT_META, "/v1/schedule/meeting-types"]) {
794
- instance.get(url, async () => ({ ok: true }));
795
- instance.post(url, async () => ({ ok: true }));
796
- }
797
- return instance;
798
- }
799
-
800
- async function call(
801
- method: "GET" | "POST",
802
- url: string,
803
- headers: Record<string, string>,
804
- ): Promise<number> {
805
- if (!app) throw new Error("no app");
806
- const res = await app.inject({ method, url, headers });
807
- return res.statusCode;
808
- }
809
-
810
- it.each<["GET" | "POST", string]>([
811
- ["GET", AVAILABILITY],
812
- ["POST", BOOK],
813
- ])("%s %s: two visitors behind one site key are counted separately", async (method, url) => {
814
- app = scheduleApp();
815
- await app.ready();
816
- for (let i = 0; i < 10; i++) {
817
- expect(await call(method, url, keyed("203.0.113.1"))).toBe(200);
818
- }
819
- expect(await call(method, url, keyed("203.0.113.1"))).toBe(429);
820
- expect(await call(method, url, keyed("203.0.113.2"))).toBe(200);
821
- });
822
-
823
- it.each<["GET" | "POST", string]>([
824
- ["POST", AVAILABILITY],
825
- ["GET", BOOK],
826
- ["GET", EVENT_META],
827
- ["GET", "/v1/schedule/meeting-types"],
828
- ])("%s %s is not on the list: the key is ignored and the eleventh distinct visitor is 429", async (method, url) => {
829
- app = scheduleApp();
830
- await app.ready();
831
- const codes: number[] = [];
832
- for (let i = 1; i <= 11; i++) {
833
- codes.push(await call(method, url, keyed(`203.0.113.${i}`)));
834
- }
835
- expect(codes.slice(0, 10).every((code) => code === 200)).toBe(true);
836
- expect(codes[10]).toBe(429);
837
- });
838
-
839
- it("lists each route under its own method", () => {
840
- expect(FORWARDED_VISITOR_ROUTES).toEqual([
841
- { method: "POST", url: "/v1/leads/submit" },
842
- { method: "POST", url: "/v1/leads/subscribe" },
843
- { method: "POST", url: "/v1/leads/callback" },
844
- { method: "GET", url: AVAILABILITY },
845
- { method: "POST", url: BOOK },
846
- { method: "POST", url: "/v1/consent/cookie" },
847
- { method: "POST", url: "/v1/consent/unsubscribe" },
848
- { method: "POST", url: "/v1/project-listings" },
849
- { method: "PATCH", url: "/v1/project-listings/drafts/:id" },
850
- { method: "POST", url: "/v1/project-listings/drafts/:id/submit" },
851
- { method: "GET", url: "/v1/deliverables/open/:slug" },
852
- ]);
853
- });
854
- });
855
-
856
- // #8438 D5/D9 — the cookie banner's log and the unsubscribe landing. Each
857
- // is registered in its OWN scope (`consent`, `unsubscribe`), exactly as
858
- // server.ts does, and both are on the forwarded-visitor list.
859
- describe("the consent routes count each keyed visitor separately, in scopes of their own (#8438)", () => {
860
- const COOKIE = "/v1/consent/cookie";
861
- const UNSUBSCRIBE = "/v1/consent/unsubscribe";
862
-
863
- function consentApp(): FastifyInstance {
864
- const instance = Fastify({ trustProxy: true });
865
- for (const [scope, url] of [
866
- ["consent", COOKIE],
867
- ["unsubscribe", UNSUBSCRIBE],
868
- ] as const) {
869
- instance.register(async (scoped) => {
870
- scoped.register(rateLimitMiddleware, {
871
- scope,
872
- perIpPerMinute: 10,
873
- trustedKeyDigests: digests(),
874
- });
875
- scoped.post(url, async () => ({ ok: true }));
876
- });
877
- }
878
- return instance;
879
- }
880
-
881
- async function post(url: string, headers: Record<string, string>): Promise<number> {
882
- if (!app) throw new Error("no app");
883
- return (await app.inject({ method: "POST", url, headers })).statusCode;
884
- }
885
-
886
- it.each([COOKIE, UNSUBSCRIBE])("%s: two visitors behind one site key are counted separately", async (url) => {
887
- app = consentApp();
888
- await app.ready();
889
- for (let i = 0; i < 10; i++) {
890
- expect(await post(url, keyed("203.0.113.1"))).toBe(200);
891
- }
892
- expect(await post(url, keyed("203.0.113.1"))).toBe(429);
893
- expect(await post(url, keyed("203.0.113.2"))).toBe(200);
894
- });
895
-
896
- it("an exhausted consent bucket leaves unsubscribe answering", async () => {
897
- app = consentApp();
898
- await app.ready();
899
- for (let i = 0; i < 10; i++) await post(COOKIE, keyed("203.0.113.1"));
900
- expect(await post(COOKIE, keyed("203.0.113.1"))).toBe(429);
901
- expect(await post(UNSUBSCRIBE, keyed("203.0.113.1"))).toBe(200);
902
- });
903
- });
904
-
905
- describe("AC-5 — visitor IP validation and normalisation", () => {
906
- function identityApp(): FastifyInstance {
907
- const instance = Fastify({ trustProxy: true });
908
- const trusted = digests();
909
- instance.post(LEADS_SUBMIT, async (req) => resolveRateLimitIdentity(req, trusted));
910
- return instance;
911
- }
912
-
913
- async function identityFor(visitorIp: string): Promise<unknown> {
914
- if (!app) throw new Error("no app");
915
- const res = await app.inject({ method: "POST", url: LEADS_SUBMIT, headers: keyed(visitorIp) });
916
- return res.json();
917
- }
918
-
919
- it.each(["not-an-ip", "203.0.113.1, 198.51.100.1", "a".repeat(46), "fe80::1%eth0", ""])(
920
- "falls back to req.ip for %j",
921
- async (visitorIp) => {
922
- app = identityApp();
923
- await app.ready();
924
- expect(await identityFor(visitorIp)).toEqual({ identity: SPOKE_HOST, keyIndex: null });
925
- },
926
- );
927
-
928
- it("maps an IPv4-mapped IPv6 address to its IPv4 form", async () => {
929
- app = identityApp();
930
- await app.ready();
931
- expect(await identityFor("::ffff:203.0.113.9")).toEqual({
932
- identity: "v0,203.0.113.9",
933
- keyIndex: 0,
934
- });
935
- });
936
-
937
- it.each(["2001:db8:1:2::1", "2001:DB8:1:2::ffff"])(
938
- "groups the IPv6 address %s by its /64",
939
- async (visitorIp) => {
940
- app = identityApp();
941
- await app.ready();
942
- expect(await identityFor(visitorIp)).toEqual({
943
- identity: "v0,2001:0db8:0001:0002::/64",
944
- keyIndex: 0,
945
- });
946
- },
947
- );
948
-
949
- it("keeps a valid IPv4 address as it is", async () => {
950
- app = identityApp();
951
- await app.ready();
952
- expect(await identityFor(" 203.0.113.10 ")).toEqual({
953
- identity: "v0,203.0.113.10",
954
- keyIndex: 0,
955
- });
956
- });
957
-
958
- it("ignores the key on a method other than POST", async () => {
959
- const trusted = digests();
960
- app = Fastify({ trustProxy: true });
961
- app.get(LEADS_SUBMIT, async (req) => resolveRateLimitIdentity(req, trusted));
962
- await app.ready();
963
- const res = await app.inject({ method: "GET", url: LEADS_SUBMIT, headers: keyed("203.0.113.1") });
964
- expect(res.json()).toEqual({ identity: SPOKE_HOST, keyIndex: null });
965
- });
966
- });
967
-
968
- describe("AC-6 — buildTrustedKeyDigests keeps positions and never logs an entry", () => {
969
- it("drops a short entry with one warning, keeps empty slots, and digests the real key", () => {
970
- const warn = jest.fn();
971
- const slots = buildTrustedKeyDigests(`short, ,${KEY}`, warn);
972
- expect(slots).toHaveLength(3);
973
- expect(slots[0]).toBeNull();
974
- expect(slots[1]).toBeNull();
975
- expect(Buffer.isBuffer(slots[2])).toBe(true);
976
- expect(warn).toHaveBeenCalledTimes(1);
977
- const message = String(warn.mock.calls[0]?.[0]);
978
- expect(message).toContain("AILK_VISITOR_FORWARD_KEYS");
979
- expect(message).not.toContain("short");
980
- });
981
-
982
- it("returns [] and warns nothing when the variable is unset or empty", () => {
983
- const warn = jest.fn();
984
- expect(buildTrustedKeyDigests(undefined, warn)).toEqual([]);
985
- expect(buildTrustedKeyDigests("", warn)).toEqual([]);
986
- expect(warn).not.toHaveBeenCalled();
987
- });
988
-
989
- it("counts a request presenting the short entry under req.ip", async () => {
990
- app = forwardApp({
991
- scope: "leads",
992
- perIpPerMinute: 1,
993
- trustedKeyDigests: buildTrustedKeyDigests(`short, ,${KEY}`, noWarn),
994
- });
995
- await app.ready();
996
- expect(await post(keyed("203.0.113.1", "short"))).toBe(200);
997
- expect(await post(keyed("203.0.113.2", "short"))).toBe(429);
998
- });
999
-
1000
- it("gives the third entry's visitors a v2, identity and their own buckets", async () => {
1001
- const trusted = buildTrustedKeyDigests(`short, ,${KEY}`, noWarn);
1002
- app = Fastify({ trustProxy: true });
1003
- app.register(async (child) => {
1004
- child.register(rateLimitMiddleware, {
1005
- scope: "leads",
1006
- perIpPerMinute: 10,
1007
- trustedKeyDigests: trusted,
1008
- });
1009
- child.post(LEADS_SUBMIT, async (req) => resolveRateLimitIdentity(req, trusted));
1010
- });
1011
- await app.ready();
1012
- const first = await app.inject({ method: "POST", url: LEADS_SUBMIT, headers: keyed("203.0.113.1") });
1013
- expect((first.json() as { identity: string }).identity).toBe("v2,203.0.113.1");
1014
- for (let i = 0; i < 9; i++) expect(await post(keyed("203.0.113.1"))).toBe(200);
1015
- expect(await post(keyed("203.0.113.1"))).toBe(429);
1016
- expect(await post(keyed("203.0.113.2"))).toBe(200);
1017
- });
1018
- });
1019
-
1020
- describe("AC-10 — the 429 log line names the bucket and key position, never the key", () => {
1021
- it("logs the namespaced identity, bucket and keyIndex for a visitor-bucket 429", async () => {
1022
- app = forwardApp({
1023
- scope: "leads",
1024
- perIpPerMinute: 10,
1025
- perKeyPerMinute: 300,
1026
- trustedKeyDigests: digests(),
1027
- });
1028
- await app.ready();
1029
- for (let i = 0; i < 10; i++) await post(keyed("203.0.113.1"));
1030
- expect(await post(keyed("203.0.113.1"))).toBe(429);
1031
-
1032
- const [line] = rateLimitedLines();
1033
- expect(line?.["ip"]).toBe("v0,203.0.113.1");
1034
- expect(line?.["bucket"]).toBe("visitor");
1035
- expect(line?.["keyIndex"]).toBe(0);
1036
- const text = JSON.stringify(logLines);
1037
- expect(text).not.toContain(KEY);
1038
- expect(text).not.toContain("forward-key");
1039
- });
1040
- });
1041
-
1042
- describe("AC-11 — each key has its own ceiling", () => {
1043
- const options = (): RateLimitOptions => ({
1044
- scope: "leads",
1045
- perIpPerMinute: 10,
1046
- perKeyPerMinute: 5,
1047
- trustedKeyDigests: digests(),
1048
- });
1049
-
1050
- it("refuses the sixth keyed request across distinct visitors, with bucket: key", async () => {
1051
- app = forwardApp(options());
1052
- await app.ready();
1053
- for (let i = 1; i <= 5; i++) expect(await post(keyed(`203.0.113.${i}`))).toBe(200);
1054
- const sixth = await app.inject({
1055
- method: "POST",
1056
- url: LEADS_SUBMIT,
1057
- headers: keyed("203.0.113.6"),
1058
- });
1059
- expect(sixth.statusCode).toBe(429);
1060
- const retryAfter = Number(sixth.headers["retry-after"]);
1061
- expect(retryAfter).toBeGreaterThanOrEqual(1);
1062
- expect(retryAfter).toBeLessThanOrEqual(60);
1063
- const [line] = rateLimitedLines();
1064
- expect(line?.["bucket"]).toBe("key");
1065
- expect(line?.["keyIndex"]).toBe(0);
1066
- expect(line?.["ip"]).toBe("v0,203.0.113.6");
1067
-
1068
- // A request with no key, from a seventh visitor, is unaffected.
1069
- expect(await post({ "x-forwarded-for": "203.0.113.7" })).toBe(200);
1070
- });
1071
-
1072
- it("reads AILK_RATE_LIMIT_LEADS_PER_KEY_PER_MINUTE over the option", async () => {
1073
- process.env.AILK_RATE_LIMIT_LEADS_PER_KEY_PER_MINUTE = "7";
1074
- app = forwardApp(options());
1075
- await app.ready();
1076
- for (let i = 1; i <= 7; i++) expect(await post(keyed(`203.0.113.${i}`))).toBe(200);
1077
- expect(await post(keyed("203.0.113.8"))).toBe(429);
1078
- });
1079
-
1080
- it("does not read the per-visitor variable for the per-key ceiling", async () => {
1081
- process.env.AILK_RATE_LIMIT_LEADS_PER_MINUTE = "50";
1082
- app = forwardApp(options());
1083
- await app.ready();
1084
- for (let i = 1; i <= 5; i++) expect(await post(keyed(`203.0.113.${i}`))).toBe(200);
1085
- expect(await post(keyed("203.0.113.6"))).toBe(429);
1086
- });
1087
-
1088
- it("visitor churn past maxBuckets cannot evict the key bucket and reset its ceiling", async () => {
1089
- app = forwardApp({ ...options(), maxBuckets: 3 });
1090
- await app.ready();
1091
- for (let i = 1; i <= 5; i++) expect(await post(keyed(`203.0.113.${i}`))).toBe(200);
1092
- // Each refused request still adds a visitor bucket; with maxBuckets 3
1093
- // the oldest entries are evicted over and over.
1094
- for (let i = 6; i <= 20; i++) expect(await post(keyed(`203.0.113.${i}`))).toBe(429);
1095
- });
1096
-
1097
- it("a key over its ceiling opens no new visitor bucket, so it cannot evict another scope's counter (security review R-1)", async () => {
1098
- app = Fastify({ trustProxy: true });
1099
- app.register(async (child) => {
1100
- child.register(rateLimitMiddleware, { perIpPerMinute: 1, maxBuckets: 10 });
1101
- child.post("/v1/auth/email", async () => ({ ok: true }));
1102
- });
1103
- app.register(async (child) => {
1104
- child.register(rateLimitMiddleware, { ...options(), maxBuckets: 10 });
1105
- child.post(LEADS_SUBMIT, async () => ({ ok: true }));
1106
- });
1107
- await app.ready();
1108
- const victim = { "x-forwarded-for": "198.51.100.99" };
1109
- expect(await post(victim, "/v1/auth/email")).toBe(200);
1110
- expect(await post(victim, "/v1/auth/email")).toBe(429);
1111
-
1112
- for (let i = 1; i <= 5; i++) expect(await post(keyed(`203.0.113.${i}`))).toBe(200);
1113
- for (let i = 6; i <= 60; i++) expect(await post(keyed(`203.0.113.${i}`))).toBe(429);
1114
-
1115
- // The victim's exhausted counter survived the keyed churn.
1116
- expect(await post(victim, "/v1/auth/email")).toBe(429);
1117
- });
1118
-
1119
- it("a key over its ceiling still counts a visitor whose bucket is already open", async () => {
1120
- app = forwardApp({ ...options(), perIpPerMinute: 2 });
1121
- await app.ready();
1122
- expect(await post(keyed("203.0.113.1"))).toBe(200);
1123
- for (let i = 2; i <= 5; i++) expect(await post(keyed(`203.0.113.${i}`))).toBe(200);
1124
- // Key now at its ceiling of 5; visitor 1 has an open bucket at count 1.
1125
- expect(await post(keyed("203.0.113.1"))).toBe(429);
1126
- const [line] = rateLimitedLines();
1127
- expect(line?.["bucket"]).toBe("key");
1128
- // Visitor 1's own bucket was counted (now 2), so a third request trips
1129
- // the visitor bucket even once the key bucket is ignored.
1130
- expect(await post(keyed("203.0.113.1"))).toBe(429);
1131
- expect(rateLimitedLines()[1]?.["bucket"]).toBe("visitor");
1132
- });
1133
-
1134
- it("defaults the per-key ceiling to 300 when no option is passed", async () => {
1135
- app = forwardApp({ scope: "leads", perIpPerMinute: 10, trustedKeyDigests: digests() });
1136
- await app.ready();
1137
- const codes: number[] = [];
1138
- for (let i = 0; i < 301; i++) {
1139
- codes.push(await post(keyed(`10.${Math.floor(i / 250)}.${i % 250}.1`)));
1140
- }
1141
- expect(codes.slice(0, 300).every((code) => code === 200)).toBe(true);
1142
- expect(codes[300]).toBe(429);
1143
- });
1144
- });
1145
-
1146
- describe("AC-12 — no unkeyed req.ip can reach a keyed bucket", () => {
1147
- const options = (): RateLimitOptions => ({
1148
- scope: "leads",
1149
- perIpPerMinute: 10,
1150
- perKeyPerMinute: 5,
1151
- trustedKeyDigests: digests(),
1152
- });
1153
-
1154
- it("unkeyed traffic shaped like a keyed bucket key adds nothing to the per-key bucket", async () => {
1155
- app = forwardApp(options());
1156
- await app.ready();
1157
- for (const forwarded of ["key:0", "key", "v0:203.0.113.1", "v0"]) {
1158
- for (let i = 0; i < 6; i++) await post({ "x-forwarded-for": forwarded });
1159
- }
1160
- for (let i = 1; i <= 5; i++) expect(await post(keyed(`203.0.113.${i}`))).toBe(200);
1161
- expect(await post(keyed("203.0.113.6"))).toBe(429);
1162
- });
1163
-
1164
- it("ten unkeyed requests from v0:203.0.113.1 do not stop that keyed visitor", async () => {
1165
- app = forwardApp(options());
1166
- await app.ready();
1167
- for (let i = 0; i < 10; i++) await post({ "x-forwarded-for": "v0:203.0.113.1" });
1168
- expect(await post(keyed("203.0.113.1"))).toBe(200);
1169
- });
1170
- });
1171
-
1172
- describe("registration guards", () => {
1173
- it.each(["Leads", "1leads", "le-ads", ""])("rejects the scope name %j", async (scope) => {
1174
- app = forwardApp({ scope });
1175
- await expect(app.ready()).rejects.toThrow(/scope/);
1176
- });
1177
-
1178
- it("rejects trustedKeyDigests without a scope", async () => {
1179
- app = forwardApp({ trustedKeyDigests: digests() });
1180
- await expect(app.ready()).rejects.toThrow(/scope/);
1181
- });
1182
-
1183
- it("lets a caller-supplied ipFromRequest win over the forwarded identity", async () => {
1184
- app = forwardApp({
1185
- scope: "leads",
1186
- perIpPerMinute: 1,
1187
- trustedKeyDigests: digests(),
1188
- ipFromRequest: () => "fixed",
1189
- });
1190
- await app.ready();
1191
- expect(await post(keyed("203.0.113.1"))).toBe(200);
1192
- expect(await post(keyed("203.0.113.2"))).toBe(429);
1193
- });
1194
- });
1195
- });
1196
-
1197
- describe("the sign-up evidence read is counted per site key (#8805)", () => {
1198
- const SIGN_UP = "/v1/consent/sign-up";
1199
- const WEB_EGRESS = "198.51.100.20";
1200
- const VALID = "ailk_spk_valid-site-key";
1201
- const SPOKE_ID = "spoke_01920000-0000-7000-8000-0000000000b1";
1202
- const ENV_KEYS = [
1203
- "AILK_RATE_LIMIT_SIGNUPEVIDENCE_PER_MINUTE",
1204
- "AILK_RATE_LIMIT_SIGNUPEVIDENCE_PER_KEY_PER_MINUTE",
1205
- ] as const;
1206
- const priorEnv = new Map<string, string | undefined>(
1207
- ENV_KEYS.map((name) => [name, process.env[name]]),
1208
- );
1209
-
1210
- let app: FastifyInstance | undefined;
1211
- let verify: jest.Mock<Promise<string | null>, [unknown]>;
1212
- let logLines: Array<Record<string, unknown>>;
1213
-
1214
- function signUpApp(opts: Partial<RateLimitOptions> = {}): FastifyInstance {
1215
- const instance = Fastify({
1216
- trustProxy: true,
1217
- logger: {
1218
- level: "warn",
1219
- stream: {
1220
- write(msg: string) {
1221
- logLines.push(JSON.parse(msg) as Record<string, unknown>);
1222
- },
1223
- },
1224
- },
1225
- });
1226
- instance.register(rateLimitMiddleware, {
1227
- perIpPerMinute: DEFAULT_PER_IP_PER_MINUTE_STRICT,
1228
- perKeyPerMinute: 25,
1229
- scope: "signupevidence",
1230
- siteKeyOf: siteKeyReader(verify),
1231
- ...opts,
1232
- });
1233
- instance.get(SIGN_UP, async () => ({ ok: true }));
1234
- instance.get("/v1/other", async () => ({ ok: true }));
1235
- return instance;
1236
- }
1237
-
1238
- async function statuses(
1239
- count: number,
1240
- headers: Record<string, string>,
1241
- url: string = SIGN_UP,
1242
- ): Promise<number[]> {
1243
- if (!app) throw new Error("no app");
1244
- const codes: number[] = [];
1245
- for (let i = 0; i < count; i++) {
1246
- const res = await app.inject({ method: "GET", url, headers });
1247
- codes.push(res.statusCode);
1248
- }
1249
- return codes;
1250
- }
1251
-
1252
- const keyed = (ip: string = WEB_EGRESS, key: string = VALID) => ({
1253
- "x-forwarded-for": ip,
1254
- "x-ailk-spoke-key": key,
1255
- });
1256
-
1257
- beforeEach(() => {
1258
- __resetBuckets();
1259
- logLines = [];
1260
- for (const name of ENV_KEYS) delete process.env[name];
1261
- verify = jest.fn((req: unknown) => {
1262
- const headers = (req as { headers: Record<string, unknown> }).headers;
1263
- return Promise.resolve(
1264
- headers["x-ailk-spoke-key"] === VALID ? SPOKE_ID : null,
1265
- );
1266
- });
1267
- });
1268
-
1269
- afterEach(async () => {
1270
- if (app) await app.close();
1271
- app = undefined;
1272
- });
1273
-
1274
- afterAll(() => {
1275
- for (const [name, value] of priorEnv) {
1276
- if (value === undefined) delete process.env[name];
1277
- else process.env[name] = value;
1278
- }
1279
- });
1280
-
1281
- it("lists GET /v1/consent/sign-up as the one site-keyed route", () => {
1282
- expect(SITE_KEYED_ROUTES).toEqual([{ method: "GET", url: SIGN_UP }]);
1283
- });
1284
-
1285
- it("names a per-key default well above the per-IP 10", () => {
1286
- expect(DEFAULT_SIGNUPEVIDENCE_PER_KEY_PER_MINUTE).toBe(120);
1287
- });
1288
-
1289
- it("admits keyed requests from one IP past 10 a minute, up to the key ceiling, then 429", async () => {
1290
- app = signUpApp();
1291
- await app.ready();
1292
- const codes = await statuses(26, keyed());
1293
- expect(codes.slice(0, 25).every((code) => code === 200)).toBe(true);
1294
- expect(codes[25]).toBe(429);
1295
- });
1296
-
1297
- it("refuses the eleventh keyless request from one IP with 429", async () => {
1298
- app = signUpApp();
1299
- await app.ready();
1300
- const codes = await statuses(11, { "x-forwarded-for": WEB_EGRESS });
1301
- expect(codes.slice(0, 10).every((code) => code === 200)).toBe(true);
1302
- expect(codes[10]).toBe(429);
1303
- expect(verify).not.toHaveBeenCalled();
1304
- });
1305
-
1306
- it("keeps an invalid key on the per-IP 10 a minute", async () => {
1307
- app = signUpApp();
1308
- await app.ready();
1309
- const codes = await statuses(11, keyed(WEB_EGRESS, "ailk_spk_forged"));
1310
- expect(codes.slice(0, 10).every((code) => code === 200)).toBe(true);
1311
- expect(codes[10]).toBe(429);
1312
- });
1313
-
1314
- it("an anonymous caller spoofing the web's X-Forwarded-For cannot spend the keyed budget", async () => {
1315
- app = signUpApp();
1316
- await app.ready();
1317
- // The spoofer fills the per-IP bucket of the web's own egress address…
1318
- const spoofed = await statuses(30, { "x-forwarded-for": WEB_EGRESS });
1319
- expect(spoofed[10]).toBe(429);
1320
- // …and with a forged key too.
1321
- await statuses(30, keyed(WEB_EGRESS, "ailk_spk_forged"));
1322
- // The keyed caller behind that address still has its whole budget.
1323
- const codes = await statuses(25, keyed());
1324
- expect(codes.every((code) => code === 200)).toBe(true);
1325
- });
1326
-
1327
- it("many web instances behind one egress share the key bucket, not an IP bucket", async () => {
1328
- app = signUpApp();
1329
- await app.ready();
1330
- const codes: number[] = [];
1331
- for (let i = 0; i < 26; i++) {
1332
- codes.push(...(await statuses(1, keyed(`203.0.113.${i + 1}`))));
1333
- }
1334
- expect(codes.slice(0, 25).every((code) => code === 200)).toBe(true);
1335
- expect(codes[25]).toBe(429);
1336
- });
1337
-
1338
- it("a verification failure counts the request per IP, never unlimited", async () => {
1339
- verify.mockRejectedValue(new Error("db down: postgres://secret"));
1340
- app = signUpApp();
1341
- await app.ready();
1342
- const codes = await statuses(11, keyed());
1343
- expect(codes[10]).toBe(429);
1344
- const line = logLines.find(
1345
- (l) => l["event"] === "rate_limit_site_key_unverified",
1346
- );
1347
- expect(line).toBeDefined();
1348
- expect(JSON.stringify(logLines)).not.toContain("postgres://secret");
1349
- expect(JSON.stringify(logLines)).not.toContain(VALID);
1350
- });
1351
-
1352
- it("a lookup that outlasts its timeout counts the request per IP", async () => {
1353
- verify.mockImplementation(() => new Promise<string | null>(() => undefined));
1354
- app = signUpApp({ siteKeyOf: siteKeyReader(verify, 5) });
1355
- await app.ready();
1356
- const codes = await statuses(11, keyed());
1357
- expect(codes.slice(0, 10).every((code) => code === 200)).toBe(true);
1358
- expect(codes[10]).toBe(429);
1359
- expect(
1360
- logLines.some((l) => l["event"] === "rate_limit_site_key_unverified"),
1361
- ).toBe(true);
1362
- });
1363
-
1364
- it("ignores a key on any route but the sign-up evidence read", async () => {
1365
- app = signUpApp();
1366
- await app.ready();
1367
- const codes = await statuses(11, keyed(), "/v1/other");
1368
- expect(codes[10]).toBe(429);
1369
- expect(verify).not.toHaveBeenCalled();
1370
- });
1371
-
1372
- it("verifies the key once per request, however many limiters read it", async () => {
1373
- const reader = siteKeyReader(verify);
1374
- app = signUpApp({ siteKeyOf: reader });
1375
- // A second reader of the same request, as the server-wide limiter is.
1376
- app.addHook("onRequest", async (req) => {
1377
- await reader(req);
1378
- });
1379
- await app.ready();
1380
- await statuses(3, keyed());
1381
- expect(verify).toHaveBeenCalledTimes(3);
1382
- });
1383
-
1384
- it("reads AILK_RATE_LIMIT_SIGNUPEVIDENCE_PER_KEY_PER_MINUTE over the code value", async () => {
1385
- process.env.AILK_RATE_LIMIT_SIGNUPEVIDENCE_PER_KEY_PER_MINUTE = "12";
1386
- app = signUpApp();
1387
- await app.ready();
1388
- const codes = await statuses(13, keyed());
1389
- expect(codes.slice(0, 12).every((code) => code === 200)).toBe(true);
1390
- expect(codes[12]).toBe(429);
1391
- });
1392
-
1393
- it("logs a keyed 429 with bucket site and the spoke id, never the key", async () => {
1394
- app = signUpApp({ perKeyPerMinute: 1 });
1395
- await app.ready();
1396
- await statuses(2, keyed());
1397
- const line = logLines.find((l) => l["msg"] === "rate_limited");
1398
- expect(line).toMatchObject({
1399
- ip: `site,${SPOKE_ID}`,
1400
- bucket: "site",
1401
- });
1402
- expect(JSON.stringify(logLines)).not.toContain(VALID);
1403
- });
1404
-
1405
- it("rejects siteKeyOf without a scope", async () => {
1406
- app = signUpApp({ scope: undefined });
1407
- await expect(app.ready()).rejects.toThrow(/scope/);
1408
- });
1409
- });