create-ailk 0.23.0 → 0.25.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (604) hide show
  1. package/README.md +68 -33
  2. package/component-catalog.json +3 -3
  3. package/component-catalog.md +3 -3
  4. package/dist/add-module.js +10 -3
  5. package/dist/add-route.d.ts +12 -1
  6. package/dist/add-route.js +38 -4
  7. package/dist/cli.js +12 -7
  8. package/dist/derive-architecture.d.ts +3 -4
  9. package/dist/derive-architecture.js +75 -22
  10. package/dist/lib/design-checks.d.ts +9 -4
  11. package/dist/lib/design-checks.js +13 -7
  12. package/dist/lib/extract-module-bundle.js +29 -2
  13. package/dist/lib/fetch-template-snapshot.d.ts +1 -1
  14. package/dist/lib/fetch-template-snapshot.js +7 -3
  15. package/dist/lib/import-graph.d.ts +1 -1
  16. package/dist/lib/import-graph.js +4 -4
  17. package/dist/lib/module-license-gate.d.ts +12 -1
  18. package/dist/lib/module-license-gate.js +34 -12
  19. package/dist/lib/scaffold-render-sweep.d.ts +33 -0
  20. package/dist/lib/scaffold-render-sweep.js +45 -0
  21. package/dist/module-architecture.d.ts +20 -3
  22. package/dist/module-architecture.js +122 -538
  23. package/dist/paid-sections.d.ts +25 -1
  24. package/dist/paid-sections.js +88 -3
  25. package/dist/surfaces.js +10 -2
  26. package/dist/sync-routes.d.ts +30 -4
  27. package/dist/sync-routes.js +271 -18
  28. package/dist/template-record.d.ts +14 -4
  29. package/dist/template-record.js +23 -5
  30. package/dist/topology.d.ts +16 -3
  31. package/dist/topology.js +31 -19
  32. package/dist/update.d.ts +10 -1
  33. package/dist/update.js +540 -16
  34. package/package.json +3 -3
  35. package/release-scope.json +1 -1
  36. package/templates/.claude/cloudparity-repo-hooks.json +5 -0
  37. package/templates/.claude/hooks/template-guard.sh +137 -0
  38. package/templates/.claude/rules/extending.md +106 -0
  39. package/templates/.claude/rules/loop-contract.md +2 -2
  40. package/templates/.claude/settings.json +11 -0
  41. package/templates/.env.example +9 -5
  42. package/templates/.github/workflows/ci.yml +7 -4
  43. package/templates/CLAUDE.md +15 -3
  44. package/templates/CONVENTIONS.md +8 -10
  45. package/templates/README.md +14 -13
  46. package/templates/apps/api/.env.example +9 -2
  47. package/templates/apps/api/CLAUDE.md +122 -82
  48. package/templates/apps/api/jest.config.cjs +15 -5
  49. package/templates/apps/api/package.json +16 -20
  50. package/templates/apps/api/src/__tests__/trusted-origins.server.test.ts +2 -2
  51. package/templates/apps/api/src/__tests__/vercel-handler.test.ts +4 -4
  52. package/templates/apps/api/src/index.ts +1 -1
  53. package/templates/apps/api/src/lib/__mocks__/prisma.ts +7 -4
  54. package/templates/apps/api/src/modules/commerce.ts +10 -0
  55. package/templates/apps/api/src/modules/content-write.ts +10 -0
  56. package/templates/apps/api/src/modules/multi-tenant.ts +10 -0
  57. package/templates/apps/api/src/modules/scheduling.ts +10 -0
  58. package/templates/apps/api/src/modules/signal-collectors.ts +10 -0
  59. package/templates/apps/api/src/modules/workspace.ts +10 -0
  60. package/templates/apps/api/src/server.ts +117 -1857
  61. package/templates/apps/api/vercel.json +2 -2
  62. package/templates/apps/mcp/CLAUDE.md +77 -24
  63. package/templates/apps/mcp/__tests__/app-entry.test.ts +4 -254
  64. package/templates/apps/mcp/__tests__/boot-file.test.ts +92 -0
  65. package/templates/apps/mcp/jest.config.cjs +6 -1
  66. package/templates/apps/mcp/package.json +5 -12
  67. package/templates/apps/mcp/src/app.ts +8 -7
  68. package/templates/apps/mcp/src/index.ts +6 -34
  69. package/templates/apps/mcp/src/lib/paid-tools.generated.ts +10 -0
  70. package/templates/apps/mcp/src/lib/topology.generated.ts +2 -2
  71. package/templates/apps/mcp/src/site.ts +12 -0
  72. package/templates/apps/web/.env.example +1 -1
  73. package/templates/apps/web/CLAUDE.md +21 -5
  74. package/templates/apps/web/app/.well-known/mcp.json/route.ts +9 -3
  75. package/templates/apps/web/app/[locale]/contact/__tests__/ConversationalIntakeWrapper.test.tsx +1 -1
  76. package/templates/apps/web/app/[locale]/contact/contact.actions.ts +14 -4
  77. package/templates/apps/web/app/[locale]/contact/intake-analytics.ts +1 -1
  78. package/templates/apps/web/app/[locale]/contact/intake-script.ts +1 -1
  79. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/magnet-page.test.tsx +22 -1
  80. package/templates/apps/web/app/[locale]/flows/[slug]/magnet-page.tsx +28 -7
  81. package/templates/apps/web/app/[locale]/pricing/__tests__/unconnected.test.tsx +43 -0
  82. package/templates/apps/web/app/[locale]/pricing/page.tsx +7 -3
  83. package/templates/apps/web/app/api/offerings/checkout/[lookupKey]/__tests__/route.test.ts +222 -0
  84. package/templates/apps/web/app/api/offerings/checkout/[lookupKey]/route.ts +10 -3
  85. package/templates/apps/web/app/api/revalidate/route.ts +3 -3
  86. package/templates/apps/web/auth.ts +2 -2
  87. package/templates/apps/web/jest.config.cjs +1 -0
  88. package/templates/apps/web/lib/__tests__/magnet-routes.test.ts +7 -0
  89. package/templates/apps/web/lib/auth-email.ts +1 -1
  90. package/templates/apps/web/lib/magnet-routes.ts +3 -1
  91. package/templates/apps/web/lib/newsletter.actions.ts +9 -6
  92. package/templates/apps/web/lib/relay.ts +2 -2
  93. package/templates/apps/web/lib/release-scope.ts +47 -0
  94. package/templates/apps/web/lib/server-api.ts +1 -1
  95. package/templates/apps/web/src/lib/commerce-claim.ts +1 -1
  96. package/templates/customizations.yaml +37 -0
  97. package/templates/database/prisma.config.ts +10 -14
  98. package/templates/database/seed-test.ts +2 -2
  99. package/templates/database/seed.ts +32 -5
  100. package/templates/package.json +12 -6
  101. package/templates/pnpm-workspace.yaml +0 -1
  102. package/templates/project.yaml +16 -8
  103. package/templates/tools/jest/reporters.cjs +65 -0
  104. package/templates/tools/lint-architecture.ts +757 -7
  105. package/templates/tsconfig.json +1 -2
  106. package/versions.json +48 -35
  107. package/templates/apps/api/src/__tests__/commerce-claim-registration.test.ts +0 -409
  108. package/templates/apps/api/src/__tests__/factories/agent-caller.ts +0 -102
  109. package/templates/apps/api/src/__tests__/factories/content-fixture.ts +0 -138
  110. package/templates/apps/api/src/__tests__/factories/in-memory-prisma.ts +0 -441
  111. package/templates/apps/api/src/__tests__/factories/index.ts +0 -70
  112. package/templates/apps/api/src/__tests__/factories/lead-fixture.ts +0 -82
  113. package/templates/apps/api/src/__tests__/leads-forwarded-rate-limit.test.ts +0 -135
  114. package/templates/apps/api/src/__tests__/services/enrichment-shim.test.ts +0 -126
  115. package/templates/apps/api/src/__tests__/stripe-boot.test.ts +0 -132
  116. package/templates/apps/api/src/__tests__/support/hub-sign-in-fake-db.ts +0 -362
  117. package/templates/apps/api/src/bin/__tests__/rate-limit-probe.test.ts +0 -184
  118. package/templates/apps/api/src/bin/abandon-sweep.ts +0 -42
  119. package/templates/apps/api/src/bin/rate-limit-probe.ts +0 -53
  120. package/templates/apps/api/src/bin/spokes.ts +0 -198
  121. package/templates/apps/api/src/bin/stripe-connections-rekey.ts +0 -45
  122. package/templates/apps/api/src/config/__tests__/hub-require-spoke-key.test.ts +0 -196
  123. package/templates/apps/api/src/config/__tests__/index.test.ts +0 -233
  124. package/templates/apps/api/src/config/__tests__/modules.test.ts +0 -76
  125. package/templates/apps/api/src/config/__tests__/stripe-connection-key.test.ts +0 -185
  126. package/templates/apps/api/src/config/__tests__/trusted-origins.test.ts +0 -238
  127. package/templates/apps/api/src/config/index.ts +0 -596
  128. package/templates/apps/api/src/config/modules.ts +0 -83
  129. package/templates/apps/api/src/lib/__tests__/agent-store.test.ts +0 -581
  130. package/templates/apps/api/src/lib/__tests__/auth-email-budget.test.ts +0 -143
  131. package/templates/apps/api/src/lib/__tests__/consent-ledger-double.ts +0 -237
  132. package/templates/apps/api/src/lib/__tests__/consent-store.test.ts +0 -353
  133. package/templates/apps/api/src/lib/__tests__/content-adapter.test.ts +0 -201
  134. package/templates/apps/api/src/lib/__tests__/deliverable-asset-store.test.ts +0 -224
  135. package/templates/apps/api/src/lib/__tests__/error-serializer.test.ts +0 -120
  136. package/templates/apps/api/src/lib/__tests__/errors.test.ts +0 -94
  137. package/templates/apps/api/src/lib/__tests__/file-fallback.test.ts +0 -144
  138. package/templates/apps/api/src/lib/__tests__/fixtures/HomePage/home.mdx +0 -8
  139. package/templates/apps/api/src/lib/__tests__/flow-completion-store.test.ts +0 -149
  140. package/templates/apps/api/src/lib/__tests__/flow-rename-race.db.test.ts +0 -116
  141. package/templates/apps/api/src/lib/__tests__/hub-sign-in-store.test.ts +0 -209
  142. package/templates/apps/api/src/lib/__tests__/lead-capture-store.test.ts +0 -257
  143. package/templates/apps/api/src/lib/__tests__/lead-delivery.test.ts +0 -96
  144. package/templates/apps/api/src/lib/__tests__/outbound-http.test.ts +0 -125
  145. package/templates/apps/api/src/lib/__tests__/prisma.test.ts +0 -165
  146. package/templates/apps/api/src/lib/__tests__/require-commerce-claim.test.ts +0 -317
  147. package/templates/apps/api/src/lib/__tests__/require-paid-tier.test.ts +0 -129
  148. package/templates/apps/api/src/lib/__tests__/site.test.ts +0 -292
  149. package/templates/apps/api/src/lib/__tests__/slice-load.test.ts +0 -89
  150. package/templates/apps/api/src/lib/__tests__/spoke-store.test.ts +0 -202
  151. package/templates/apps/api/src/lib/__tests__/stripe-admission.test.ts +0 -217
  152. package/templates/apps/api/src/lib/__tests__/stripe.test.ts +0 -82
  153. package/templates/apps/api/src/lib/agent-store.ts +0 -613
  154. package/templates/apps/api/src/lib/auth-email-budget.ts +0 -161
  155. package/templates/apps/api/src/lib/consent-store.ts +0 -363
  156. package/templates/apps/api/src/lib/content-adapter.ts +0 -112
  157. package/templates/apps/api/src/lib/deliverable-asset-store.ts +0 -96
  158. package/templates/apps/api/src/lib/error-serializer.ts +0 -164
  159. package/templates/apps/api/src/lib/errors.ts +0 -95
  160. package/templates/apps/api/src/lib/file-fallback.ts +0 -87
  161. package/templates/apps/api/src/lib/flow-completion-store.ts +0 -136
  162. package/templates/apps/api/src/lib/hub-sign-in-store.ts +0 -455
  163. package/templates/apps/api/src/lib/lead-capture-store.ts +0 -122
  164. package/templates/apps/api/src/lib/lead-delivery.ts +0 -52
  165. package/templates/apps/api/src/lib/license-key-store.ts +0 -45
  166. package/templates/apps/api/src/lib/locales.ts +0 -201
  167. package/templates/apps/api/src/lib/outbound-http.ts +0 -127
  168. package/templates/apps/api/src/lib/prisma.ts +0 -21
  169. package/templates/apps/api/src/lib/proposal-paid-store.ts +0 -66
  170. package/templates/apps/api/src/lib/rate-limit-probe.ts +0 -165
  171. package/templates/apps/api/src/lib/rate-limit-store.ts +0 -142
  172. package/templates/apps/api/src/lib/require-commerce-claim.ts +0 -250
  173. package/templates/apps/api/src/lib/require-paid-tier.ts +0 -53
  174. package/templates/apps/api/src/lib/site.ts +0 -254
  175. package/templates/apps/api/src/lib/slice-load.ts +0 -90
  176. package/templates/apps/api/src/lib/spoke-store.ts +0 -180
  177. package/templates/apps/api/src/lib/stripe.ts +0 -318
  178. package/templates/apps/api/src/lib/webhook-idempotency.ts +0 -156
  179. package/templates/apps/api/src/middleware/__tests__/adversarial/bearer-token-format.test.ts +0 -111
  180. package/templates/apps/api/src/middleware/__tests__/adversarial/cookie-or-bearer-precedence.test.ts +0 -172
  181. package/templates/apps/api/src/middleware/__tests__/adversarial/csrf-bearer-skip.test.ts +0 -119
  182. package/templates/apps/api/src/middleware/__tests__/adversarial/csrf-cookie-path.test.ts +0 -138
  183. package/templates/apps/api/src/middleware/__tests__/adversarial/csrf-trusted-origins.test.ts +0 -142
  184. package/templates/apps/api/src/middleware/__tests__/adversarial/session-fixation.test.ts +0 -155
  185. package/templates/apps/api/src/middleware/__tests__/adversarial/session-timeout.test.ts +0 -139
  186. package/templates/apps/api/src/middleware/__tests__/auth.bearer-path.test.ts +0 -562
  187. package/templates/apps/api/src/middleware/__tests__/auth.both-present-precedence.test.ts +0 -76
  188. package/templates/apps/api/src/middleware/__tests__/auth.cookie-path.test.ts +0 -220
  189. package/templates/apps/api/src/middleware/__tests__/auth.database-not-configured.test.ts +0 -97
  190. package/templates/apps/api/src/middleware/__tests__/auth.hub-session-path.test.ts +0 -557
  191. package/templates/apps/api/src/middleware/__tests__/auth.neither-present.test.ts +0 -72
  192. package/templates/apps/api/src/middleware/__tests__/auth.optional-cookie.test.ts +0 -140
  193. package/templates/apps/api/src/middleware/__tests__/default-tenant.test.ts +0 -721
  194. package/templates/apps/api/src/middleware/__tests__/rate-limit-cross-isolate.db.test.ts +0 -220
  195. package/templates/apps/api/src/middleware/__tests__/rate-limit-store.test.ts +0 -430
  196. package/templates/apps/api/src/middleware/__tests__/rate-limit.test.ts +0 -1409
  197. package/templates/apps/api/src/middleware/__tests__/write-budget.test.ts +0 -174
  198. package/templates/apps/api/src/middleware/auth.ts +0 -864
  199. package/templates/apps/api/src/middleware/default-tenant.ts +0 -166
  200. package/templates/apps/api/src/middleware/rate-limit.ts +0 -983
  201. package/templates/apps/api/src/openapi/__tests__/openapi.test.ts +0 -264
  202. package/templates/apps/api/src/openapi/__tests__/spec-identity.test.ts +0 -182
  203. package/templates/apps/api/src/openapi/index.ts +0 -18
  204. package/templates/apps/api/src/openapi/spec.ts +0 -1815
  205. package/templates/apps/api/src/openapi/surface-drift.ts +0 -195
  206. package/templates/apps/api/src/routes/aeo/__tests__/index.test.ts +0 -175
  207. package/templates/apps/api/src/routes/aeo/index.ts +0 -107
  208. package/templates/apps/api/src/routes/auth/__tests__/auth-tokens.functional.test.ts +0 -196
  209. package/templates/apps/api/src/routes/auth/__tests__/auth-user.functional.test.ts +0 -249
  210. package/templates/apps/api/src/routes/auth/__tests__/hub-sign-in.test.ts +0 -532
  211. package/templates/apps/api/src/routes/auth/__tests__/tokens.test.ts +0 -313
  212. package/templates/apps/api/src/routes/auth/__tests__/transactional-email.test.ts +0 -413
  213. package/templates/apps/api/src/routes/auth/__tests__/user.test.ts +0 -609
  214. package/templates/apps/api/src/routes/auth/hub-sign-in.ts +0 -242
  215. package/templates/apps/api/src/routes/auth/tokens.ts +0 -211
  216. package/templates/apps/api/src/routes/auth/transactional-email.ts +0 -301
  217. package/templates/apps/api/src/routes/auth/user.ts +0 -305
  218. package/templates/apps/api/src/routes/billing/plan-checkout.ts +0 -325
  219. package/templates/apps/api/src/routes/checkout/__tests__/live-key.test.ts +0 -178
  220. package/templates/apps/api/src/routes/checkout/__tests__/offerings-authorization.test.ts +0 -1300
  221. package/templates/apps/api/src/routes/checkout/__tests__/session.test.ts +0 -448
  222. package/templates/apps/api/src/routes/checkout/__tests__/sessions.test.ts +0 -1742
  223. package/templates/apps/api/src/routes/checkout/index.ts +0 -34
  224. package/templates/apps/api/src/routes/checkout/session.ts +0 -171
  225. package/templates/apps/api/src/routes/checkout/sessions.ts +0 -540
  226. package/templates/apps/api/src/routes/consent/__tests__/account.test.ts +0 -386
  227. package/templates/apps/api/src/routes/consent/__tests__/sign-up-rate-limit.test.ts +0 -160
  228. package/templates/apps/api/src/routes/consent/account.ts +0 -268
  229. package/templates/apps/api/src/routes/consent/cookie.ts +0 -90
  230. package/templates/apps/api/src/routes/consent/index.ts +0 -26
  231. package/templates/apps/api/src/routes/consent/unsubscribe.ts +0 -127
  232. package/templates/apps/api/src/routes/content/__tests__/get-page.test.ts +0 -853
  233. package/templates/apps/api/src/routes/content/__tests__/list-pages.test.ts +0 -230
  234. package/templates/apps/api/src/routes/content/__tests__/list-types.test.ts +0 -44
  235. package/templates/apps/api/src/routes/content/__tests__/locale.test.ts +0 -118
  236. package/templates/apps/api/src/routes/content/__tests__/offerings.test.ts +0 -731
  237. package/templates/apps/api/src/routes/content/__tests__/pricing.test.ts +0 -753
  238. package/templates/apps/api/src/routes/content/__tests__/rate-limit.test.ts +0 -51
  239. package/templates/apps/api/src/routes/content/__tests__/search.test.ts +0 -450
  240. package/templates/apps/api/src/routes/content/__tests__/shown-offerings.test.ts +0 -762
  241. package/templates/apps/api/src/routes/content/get-page.ts +0 -268
  242. package/templates/apps/api/src/routes/content/index.ts +0 -49
  243. package/templates/apps/api/src/routes/content/list-pages.ts +0 -95
  244. package/templates/apps/api/src/routes/content/list-types.ts +0 -19
  245. package/templates/apps/api/src/routes/content/offerings.ts +0 -184
  246. package/templates/apps/api/src/routes/content/pricing.ts +0 -176
  247. package/templates/apps/api/src/routes/content/rate-limit.ts +0 -22
  248. package/templates/apps/api/src/routes/content/search.ts +0 -129
  249. package/templates/apps/api/src/routes/content/shown-offerings.ts +0 -229
  250. package/templates/apps/api/src/routes/content/slug.ts +0 -9
  251. package/templates/apps/api/src/routes/leads/__tests__/capture.test.ts +0 -88
  252. package/templates/apps/api/src/routes/leads/__tests__/list.test.ts +0 -171
  253. package/templates/apps/api/src/routes/leads/__tests__/magnet-completion.test.ts +0 -515
  254. package/templates/apps/api/src/routes/leads/__tests__/spoke.test.ts +0 -392
  255. package/templates/apps/api/src/routes/leads/__tests__/track.test.ts +0 -165
  256. package/templates/apps/api/src/routes/leads/index.ts +0 -573
  257. package/templates/apps/api/src/routes/leads/list.ts +0 -104
  258. package/templates/apps/api/src/routes/project-listings/__tests__/configured-application.test.ts +0 -626
  259. package/templates/apps/api/src/routes/project-listings/__tests__/drafts.test.ts +0 -1268
  260. package/templates/apps/api/src/routes/project-listings/__tests__/founder-identity.test.ts +0 -847
  261. package/templates/apps/api/src/routes/project-listings/__tests__/me.test.ts +0 -480
  262. package/templates/apps/api/src/routes/project-listings/__tests__/public.test.ts +0 -465
  263. package/templates/apps/api/src/routes/project-listings/__tests__/resume-email.test.ts +0 -872
  264. package/templates/apps/api/src/routes/project-listings/__tests__/site-answers.test.ts +0 -1022
  265. package/templates/apps/api/src/routes/project-listings/__tests__/site-key.test.ts +0 -484
  266. package/templates/apps/api/src/routes/project-listings/__tests__/structured-address.test.ts +0 -535
  267. package/templates/apps/api/src/routes/project-listings/index.ts +0 -164
  268. package/templates/apps/api/src/routes/project-listings/me.ts +0 -87
  269. package/templates/apps/api/src/routes/project-listings/patch-copy.ts +0 -224
  270. package/templates/apps/api/src/routes/project-listings/patch-draft.ts +0 -102
  271. package/templates/apps/api/src/routes/project-listings/public.ts +0 -98
  272. package/templates/apps/api/src/routes/project-listings/respond.ts +0 -48
  273. package/templates/apps/api/src/routes/project-listings/resume-token.ts +0 -27
  274. package/templates/apps/api/src/routes/project-listings/start.ts +0 -140
  275. package/templates/apps/api/src/routes/project-listings/submit.ts +0 -130
  276. package/templates/apps/api/src/routes/project-listings/verify-email.ts +0 -150
  277. package/templates/apps/api/src/routes/requests/__tests__/confirm.test.ts +0 -686
  278. package/templates/apps/api/src/routes/requests/confirm.ts +0 -601
  279. package/templates/apps/api/src/routes/requests/index.ts +0 -54
  280. package/templates/apps/api/src/routes/test/auth/__tests__/session.test.ts +0 -306
  281. package/templates/apps/api/src/routes/test/auth/session.ts +0 -143
  282. package/templates/apps/api/src/routes/webhooks/README.md +0 -398
  283. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-checkout-consent.test.ts +0 -649
  284. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-dunning.test.ts +0 -749
  285. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-flow-checkout.test.ts +0 -448
  286. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-idempotency.test.ts +0 -264
  287. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-livemode-live.test.ts +0 -159
  288. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-livemode.test.ts +0 -158
  289. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-offerings.test.ts +0 -814
  290. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-org-billing.test.ts +0 -301
  291. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-proposal-paid.test.ts +0 -369
  292. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-rate-limit.test.ts +0 -215
  293. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-request-paid.test.ts +0 -301
  294. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-site-filter.test.ts +0 -808
  295. package/templates/apps/api/src/routes/webhooks/__tests__/stripe.test.ts +0 -1155
  296. package/templates/apps/api/src/routes/webhooks/index.ts +0 -141
  297. package/templates/apps/api/src/routes/webhooks/stripe-offerings.ts +0 -384
  298. package/templates/apps/api/src/routes/webhooks/stripe.ts +0 -2026
  299. package/templates/apps/api/src/services/__tests__/abandon-email.test.ts +0 -528
  300. package/templates/apps/api/src/services/__tests__/answer-distributions.test.ts +0 -132
  301. package/templates/apps/api/src/services/__tests__/audit-log.test.ts +0 -1028
  302. package/templates/apps/api/src/services/__tests__/checkout-plan.test.ts +0 -313
  303. package/templates/apps/api/src/services/__tests__/consent-ledger.test.ts +0 -503
  304. package/templates/apps/api/src/services/__tests__/consent-migration.test.ts +0 -65
  305. package/templates/apps/api/src/services/__tests__/consent.test.ts +0 -299
  306. package/templates/apps/api/src/services/__tests__/default-tenant.test.ts +0 -147
  307. package/templates/apps/api/src/services/__tests__/deliverable-fulfillment.test.ts +0 -867
  308. package/templates/apps/api/src/services/__tests__/deliverable-resend.test.ts +0 -379
  309. package/templates/apps/api/src/services/__tests__/dunning-policy.test.ts +0 -368
  310. package/templates/apps/api/src/services/__tests__/entitlements.test.ts +0 -142
  311. package/templates/apps/api/src/services/__tests__/hub-sign-in.test.ts +0 -854
  312. package/templates/apps/api/src/services/__tests__/keyless-workspace-predicate.test.ts +0 -234
  313. package/templates/apps/api/src/services/__tests__/lead-accept-user.test.ts +0 -251
  314. package/templates/apps/api/src/services/__tests__/lead-routing.test.ts +0 -2660
  315. package/templates/apps/api/src/services/__tests__/listing-config.test.ts +0 -166
  316. package/templates/apps/api/src/services/__tests__/magnet-completion.test.ts +0 -389
  317. package/templates/apps/api/src/services/__tests__/person.test.ts +0 -1176
  318. package/templates/apps/api/src/services/__tests__/plan-offerings.test.ts +0 -444
  319. package/templates/apps/api/src/services/__tests__/project-listings.fence.test.ts +0 -154
  320. package/templates/apps/api/src/services/__tests__/public-site-resolver.test.ts +0 -137
  321. package/templates/apps/api/src/services/__tests__/request-confirm.test.ts +0 -531
  322. package/templates/apps/api/src/services/__tests__/revalidation.test.ts +0 -372
  323. package/templates/apps/api/src/services/__tests__/slack-notify.test.ts +0 -348
  324. package/templates/apps/api/src/services/__tests__/spoke-resolution.test.ts +0 -660
  325. package/templates/apps/api/src/services/__tests__/usage-aggregation.test.ts +0 -941
  326. package/templates/apps/api/src/services/__tests__/usage-credits.test.ts +0 -588
  327. package/templates/apps/api/src/services/__tests__/verified-email.test.ts +0 -78
  328. package/templates/apps/api/src/services/abandon-email.ts +0 -313
  329. package/templates/apps/api/src/services/aeo-score.ts +0 -325
  330. package/templates/apps/api/src/services/answer-distributions.ts +0 -138
  331. package/templates/apps/api/src/services/audit-log.ts +0 -961
  332. package/templates/apps/api/src/services/checkout-buyer.ts +0 -168
  333. package/templates/apps/api/src/services/consent.ts +0 -834
  334. package/templates/apps/api/src/services/default-tenant.ts +0 -416
  335. package/templates/apps/api/src/services/deliverable-fulfillment.ts +0 -755
  336. package/templates/apps/api/src/services/dunning-policy.ts +0 -294
  337. package/templates/apps/api/src/services/enrichment-shim.ts +0 -53
  338. package/templates/apps/api/src/services/entitlements.ts +0 -338
  339. package/templates/apps/api/src/services/hub-sign-in.ts +0 -472
  340. package/templates/apps/api/src/services/lead-accept-user.ts +0 -126
  341. package/templates/apps/api/src/services/lead-promotion.ts +0 -160
  342. package/templates/apps/api/src/services/lead-routing.ts +0 -1372
  343. package/templates/apps/api/src/services/leads-inbox.ts +0 -312
  344. package/templates/apps/api/src/services/listing-config.ts +0 -178
  345. package/templates/apps/api/src/services/magnet-completion.ts +0 -242
  346. package/templates/apps/api/src/services/offerings/__tests__/catalog.test.ts +0 -295
  347. package/templates/apps/api/src/services/offerings/__tests__/checkout-session-record.test.ts +0 -268
  348. package/templates/apps/api/src/services/offerings/__tests__/connection.test.ts +0 -868
  349. package/templates/apps/api/src/services/offerings/__tests__/fixtures.ts +0 -416
  350. package/templates/apps/api/src/services/offerings/__tests__/org-products.test.ts +0 -396
  351. package/templates/apps/api/src/services/offerings/__tests__/readers.test.ts +0 -681
  352. package/templates/apps/api/src/services/offerings/__tests__/source.test.ts +0 -231
  353. package/templates/apps/api/src/services/offerings/catalog.ts +0 -308
  354. package/templates/apps/api/src/services/offerings/checkout-authorization.ts +0 -385
  355. package/templates/apps/api/src/services/offerings/checkout-session-record.ts +0 -192
  356. package/templates/apps/api/src/services/offerings/connection.ts +0 -1003
  357. package/templates/apps/api/src/services/offerings/index.ts +0 -614
  358. package/templates/apps/api/src/services/offerings/source.ts +0 -140
  359. package/templates/apps/api/src/services/offerings/store.ts +0 -150
  360. package/templates/apps/api/src/services/owner-workspaces.ts +0 -132
  361. package/templates/apps/api/src/services/person.ts +0 -1188
  362. package/templates/apps/api/src/services/plan-offerings.ts +0 -125
  363. package/templates/apps/api/src/services/project-listing-resume-email.ts +0 -326
  364. package/templates/apps/api/src/services/project-listings.ts +0 -2073
  365. package/templates/apps/api/src/services/public-site-resolver.ts +0 -396
  366. package/templates/apps/api/src/services/request-confirm.ts +0 -698
  367. package/templates/apps/api/src/services/revalidation.ts +0 -235
  368. package/templates/apps/api/src/services/slack-notify.ts +0 -291
  369. package/templates/apps/api/src/services/usage-aggregation.ts +0 -516
  370. package/templates/apps/api/src/services/usage-credits.ts +0 -340
  371. package/templates/apps/api/src/services/verified-email.ts +0 -71
  372. package/templates/apps/mcp/__tests__/abuse/daily-cap.test.ts +0 -52
  373. package/templates/apps/mcp/__tests__/abuse/email-validator.test.ts +0 -46
  374. package/templates/apps/mcp/__tests__/abuse/guard.test.ts +0 -198
  375. package/templates/apps/mcp/__tests__/abuse/honeypot.test.ts +0 -36
  376. package/templates/apps/mcp/__tests__/abuse/user-agent-deny.test.ts +0 -54
  377. package/templates/apps/mcp/__tests__/aeo-cli-parity.test.ts +0 -116
  378. package/templates/apps/mcp/__tests__/audit-single-page.test.ts +0 -299
  379. package/templates/apps/mcp/__tests__/boot.test.ts +0 -280
  380. package/templates/apps/mcp/__tests__/catalog-drift.test.ts +0 -359
  381. package/templates/apps/mcp/__tests__/config/modules.test.ts +0 -78
  382. package/templates/apps/mcp/__tests__/get_business_hours.test.ts +0 -82
  383. package/templates/apps/mcp/__tests__/get_faq.test.ts +0 -80
  384. package/templates/apps/mcp/__tests__/get_locations.test.ts +0 -65
  385. package/templates/apps/mcp/__tests__/get_offerings.test.ts +0 -557
  386. package/templates/apps/mcp/__tests__/get_pricing.test.ts +0 -524
  387. package/templates/apps/mcp/__tests__/get_site_info.test.ts +0 -81
  388. package/templates/apps/mcp/__tests__/http-transport.test.ts +0 -1151
  389. package/templates/apps/mcp/__tests__/index.test.ts +0 -195
  390. package/templates/apps/mcp/__tests__/lib/audit-single-page-readiness-scan.test.ts +0 -191
  391. package/templates/apps/mcp/__tests__/lib/commerce-claim.test.ts +0 -531
  392. package/templates/apps/mcp/__tests__/lib/content-adapter-parity.test.ts +0 -65
  393. package/templates/apps/mcp/__tests__/lib/content-adapter.test.ts +0 -187
  394. package/templates/apps/mcp/__tests__/lib/content-root.test.ts +0 -93
  395. package/templates/apps/mcp/__tests__/lib/errors.test.ts +0 -75
  396. package/templates/apps/mcp/__tests__/lib/fail-closed-tools.test.ts +0 -165
  397. package/templates/apps/mcp/__tests__/lib/public-workspace.test.ts +0 -124
  398. package/templates/apps/mcp/__tests__/list_pages.test.ts +0 -228
  399. package/templates/apps/mcp/__tests__/locale.test.ts +0 -135
  400. package/templates/apps/mcp/__tests__/module-exclusion.test.ts +0 -175
  401. package/templates/apps/mcp/__tests__/purchase-disabled.test.ts +0 -101
  402. package/templates/apps/mcp/__tests__/read_content.test.ts +0 -474
  403. package/templates/apps/mcp/__tests__/request_callback.test.ts +0 -225
  404. package/templates/apps/mcp/__tests__/search_content.test.ts +0 -256
  405. package/templates/apps/mcp/__tests__/server.test.ts +0 -388
  406. package/templates/apps/mcp/__tests__/start_purchase.test.ts +0 -448
  407. package/templates/apps/mcp/__tests__/submit_lead.test.ts +0 -307
  408. package/templates/apps/mcp/__tests__/subscribe_newsletter.test.ts +0 -223
  409. package/templates/apps/mcp/__tests__/tools/create_project.test.ts +0 -243
  410. package/templates/apps/mcp/__tests__/tools/purchase.test.ts +0 -451
  411. package/templates/apps/mcp/src/abuse/daily-cap.ts +0 -47
  412. package/templates/apps/mcp/src/abuse/email-validator.ts +0 -25
  413. package/templates/apps/mcp/src/abuse/honeypot.ts +0 -21
  414. package/templates/apps/mcp/src/abuse/index.ts +0 -342
  415. package/templates/apps/mcp/src/abuse/user-agent-deny.ts +0 -58
  416. package/templates/apps/mcp/src/boot.ts +0 -167
  417. package/templates/apps/mcp/src/config/modules.ts +0 -43
  418. package/templates/apps/mcp/src/http-transport.ts +0 -526
  419. package/templates/apps/mcp/src/lib/audit-single-page.ts +0 -308
  420. package/templates/apps/mcp/src/lib/commerce-claim.ts +0 -263
  421. package/templates/apps/mcp/src/lib/content-adapter.ts +0 -142
  422. package/templates/apps/mcp/src/lib/empty-content-adapter.ts +0 -139
  423. package/templates/apps/mcp/src/lib/errors.ts +0 -61
  424. package/templates/apps/mcp/src/lib/license-key-store.ts +0 -45
  425. package/templates/apps/mcp/src/lib/locales.ts +0 -171
  426. package/templates/apps/mcp/src/lib/prisma.ts +0 -39
  427. package/templates/apps/mcp/src/lib/public-workspace.ts +0 -133
  428. package/templates/apps/mcp/src/lib/resolve-locale.ts +0 -30
  429. package/templates/apps/mcp/src/lib/shown-offerings.ts +0 -105
  430. package/templates/apps/mcp/src/lib/stripe-tax-signal.ts +0 -59
  431. package/templates/apps/mcp/src/request-context.ts +0 -52
  432. package/templates/apps/mcp/src/server.ts +0 -343
  433. package/templates/apps/mcp/src/serverless-app.ts +0 -88
  434. package/templates/apps/mcp/src/tools/audit.ts +0 -127
  435. package/templates/apps/mcp/src/tools/capture_lead.ts +0 -64
  436. package/templates/apps/mcp/src/tools/create_project.ts +0 -134
  437. package/templates/apps/mcp/src/tools/get_business_hours.ts +0 -68
  438. package/templates/apps/mcp/src/tools/get_faq.ts +0 -71
  439. package/templates/apps/mcp/src/tools/get_locations.ts +0 -88
  440. package/templates/apps/mcp/src/tools/get_offerings.ts +0 -96
  441. package/templates/apps/mcp/src/tools/get_pricing.ts +0 -94
  442. package/templates/apps/mcp/src/tools/get_site_info.ts +0 -86
  443. package/templates/apps/mcp/src/tools/index.ts +0 -137
  444. package/templates/apps/mcp/src/tools/list_pages.ts +0 -74
  445. package/templates/apps/mcp/src/tools/person_notes.ts +0 -25
  446. package/templates/apps/mcp/src/tools/proposals.ts +0 -27
  447. package/templates/apps/mcp/src/tools/purchase.ts +0 -205
  448. package/templates/apps/mcp/src/tools/read_content.ts +0 -75
  449. package/templates/apps/mcp/src/tools/request_callback.ts +0 -59
  450. package/templates/apps/mcp/src/tools/search_content.ts +0 -67
  451. package/templates/apps/mcp/src/tools/subscribe_newsletter.ts +0 -57
  452. package/templates/apps/mcp/src/workspace-server.ts +0 -224
  453. package/templates/database/CHANGELOG.md +0 -961
  454. package/templates/database/LICENSE +0 -202
  455. package/templates/database/NOTICE +0 -2
  456. package/templates/database/README.md +0 -243
  457. package/templates/database/__tests__/agents.db.test.ts +0 -320
  458. package/templates/database/__tests__/appointment.db.test.ts +0 -106
  459. package/templates/database/__tests__/artifact-content-store.db.test.ts +0 -316
  460. package/templates/database/__tests__/composite-fence.db.test.ts +0 -206
  461. package/templates/database/__tests__/consent-ledger.db.test.ts +0 -345
  462. package/templates/database/__tests__/consent-source-checkout-migration.test.ts +0 -79
  463. package/templates/database/__tests__/fence-fan-out.db.test.ts +0 -715
  464. package/templates/database/__tests__/fixtures/appointment-create-probe.ts +0 -79
  465. package/templates/database/__tests__/fixtures/person-backfill.json +0 -264
  466. package/templates/database/__tests__/fixtures/person-contact-backfill.json +0 -182
  467. package/templates/database/__tests__/fixtures/project-listing-consent-probe.ts +0 -100
  468. package/templates/database/__tests__/flow-completion-migration.test.ts +0 -115
  469. package/templates/database/__tests__/flow-completion.db.test.ts +0 -136
  470. package/templates/database/__tests__/flow-workspace-key.db.test.ts +0 -263
  471. package/templates/database/__tests__/flows-listing-diagnostic.test.ts +0 -392
  472. package/templates/database/__tests__/flows-presets.test.ts +0 -173
  473. package/templates/database/__tests__/in-page-magnets-migration.test.ts +0 -161
  474. package/templates/database/__tests__/lead-idempotency-key.db.test.ts +0 -92
  475. package/templates/database/__tests__/member-area.db.test.ts +0 -257
  476. package/templates/database/__tests__/member-contract-migration.test.ts +0 -85
  477. package/templates/database/__tests__/member-contract.db.test.ts +0 -413
  478. package/templates/database/__tests__/offerings-checkout-session.db.test.ts +0 -270
  479. package/templates/database/__tests__/offerings-migration.test.ts +0 -197
  480. package/templates/database/__tests__/offerings-shown-price-ids-migration.test.ts +0 -86
  481. package/templates/database/__tests__/offerings.db.test.ts +0 -303
  482. package/templates/database/__tests__/outbound-message-action.db.test.ts +0 -80
  483. package/templates/database/__tests__/person-contact.db.test.ts +0 -563
  484. package/templates/database/__tests__/person-notes.db.test.ts +0 -249
  485. package/templates/database/__tests__/person.db.test.ts +0 -586
  486. package/templates/database/__tests__/piece-kind-migration.test.ts +0 -67
  487. package/templates/database/__tests__/piece-kind.db.test.ts +0 -208
  488. package/templates/database/__tests__/prefixed-ids.db.test.ts +0 -222
  489. package/templates/database/__tests__/project-listing-consent-at.db.test.ts +0 -111
  490. package/templates/database/__tests__/seed.test.ts +0 -240
  491. package/templates/database/__tests__/spoke-registry.db.test.ts +0 -191
  492. package/templates/database/__tests__/tenancy.test.ts +0 -141
  493. package/templates/database/__tests__/user-cascade.test.ts +0 -140
  494. package/templates/database/_gitignore +0 -8
  495. package/templates/database/auth/.gitkeep +0 -0
  496. package/templates/database/auth/schema.prisma +0 -641
  497. package/templates/database/config/.gitkeep +0 -0
  498. package/templates/database/config/schema.prisma +0 -441
  499. package/templates/database/content/.gitkeep +0 -0
  500. package/templates/database/content/schema.prisma +0 -339
  501. package/templates/database/eslint.config.mjs +0 -69
  502. package/templates/database/flows/listing-diagnostic.ts +0 -182
  503. package/templates/database/flows/presets.ts +0 -315
  504. package/templates/database/inbox/.gitkeep +0 -0
  505. package/templates/database/inbox/README.md +0 -3
  506. package/templates/database/inbox/__tests__/schema.test.ts +0 -44
  507. package/templates/database/inbox/schema.prisma +0 -1447
  508. package/templates/database/jest.config.cjs +0 -36
  509. package/templates/database/migrations/20260508000000_add_inbox_namespace/migration.sql +0 -328
  510. package/templates/database/migrations/20260513000000_better_auth_migration/migration.sql +0 -100
  511. package/templates/database/migrations/20260515000000_add_user_billing_fields/migration.sql +0 -28
  512. package/templates/database/migrations/20260516000000_add_user_tier_care_plan_seat/migration.sql +0 -25
  513. package/templates/database/migrations/20260518000000_add_telemetry_records/migration.sql +0 -42
  514. package/templates/database/migrations/20260525000000_theme_wiring/migration.sql +0 -67
  515. package/templates/database/migrations/20260710000000_retire_commercial_tier/migration.sql +0 -21
  516. package/templates/database/migrations/20260712215647_add_multi_tenant_tenancy/migration.sql +0 -201
  517. package/templates/database/migrations/20260713143320_reanchor_site_config_to_workspace/migration.sql +0 -67
  518. package/templates/database/migrations/20260713174000_add_audit_logs/migration.sql +0 -46
  519. package/templates/database/migrations/20260713190000_drop_telemetry_records/migration.sql +0 -25
  520. package/templates/database/migrations/20260713192000_add_uuidv7_function/migration.sql +0 -49
  521. package/templates/database/migrations/20260713192429_prefixed_uuid_entity_ids/migration.sql +0 -197
  522. package/templates/database/migrations/20260713200000_add_org_billing/migration.sql +0 -32
  523. package/templates/database/migrations/20260714000000_add_lead_promotion_fields/migration.sql +0 -22
  524. package/templates/database/migrations/20260714010000_add_usage_billing_content_models/migration.sql +0 -151
  525. package/templates/database/migrations/20260714020000_add_usage_billing_auth_config_models/migration.sql +0 -223
  526. package/templates/database/migrations/20260714030000_credit_balance_non_negative/migration.sql +0 -22
  527. package/templates/database/migrations/20260714030000_widen_usage_billing_report_aggregates/migration.sql +0 -32
  528. package/templates/database/migrations/20260810233516_add_flow_engine_models/migration.sql +0 -40
  529. package/templates/database/migrations/20260811020000_add_flow_session_abandon_email_columns/migration.sql +0 -4
  530. package/templates/database/migrations/20260811030000_add_flow_session_abandon_email_index/migration.sql +0 -2
  531. package/templates/database/migrations/20260811040000_add_flow_session_segment/migration.sql +0 -2
  532. package/templates/database/migrations/20260811050000_add_deliverable_models/migration.sql +0 -29
  533. package/templates/database/migrations/20260812000000_add_deliverable_grant_send_columns/migration.sql +0 -6
  534. package/templates/database/migrations/20260902222948_add_waitlist_experiment_models/migration.sql +0 -39
  535. package/templates/database/migrations/20260902224500_add_waitlist_id_format_checks/migration.sql +0 -24
  536. package/templates/database/migrations/20260903004112_add_flow_session_flags_aeo_score/migration.sql +0 -3
  537. package/templates/database/migrations/20260903010000_add_playbook_instance/migration.sql +0 -33
  538. package/templates/database/migrations/20260904000000_add_waitlist_followup_send/migration.sql +0 -30
  539. package/templates/database/migrations/20260905230000_add_flow_checkout/migration.sql +0 -47
  540. package/templates/database/migrations/20260906000000_add_flow_checkout_idempotency/migration.sql +0 -16
  541. package/templates/database/migrations/20260907120000_add_project_listing/migration.sql +0 -47
  542. package/templates/database/migrations/20260907130000_add_project_listing_slack_columns/migration.sql +0 -10
  543. package/templates/database/migrations/20260907180000_add_listing_csv_send/migration.sql +0 -26
  544. package/templates/database/migrations/20260909120000_project_listings_platform/migration.sql +0 -90
  545. package/templates/database/migrations/20260909180000_listing_draft_and_fields/migration.sql +0 -174
  546. package/templates/database/migrations/20260910120000_listing_public_site_key/migration.sql +0 -14
  547. package/templates/database/migrations/20260911120000_listing_copy_edit_audit/migration.sql +0 -25
  548. package/templates/database/migrations/20260911140000_listing_structured_address/migration.sql +0 -32
  549. package/templates/database/migrations/20260911180000_consent_grants/migration.sql +0 -71
  550. package/templates/database/migrations/20260911200000_listing_site_answers/migration.sql +0 -30
  551. package/templates/database/migrations/20260912120000_listing_owner_link/migration.sql +0 -49
  552. package/templates/database/migrations/20260914120000_listing_founder_identity/migration.sql +0 -123
  553. package/templates/database/migrations/20260915120000_project_listing_solution/migration.sql +0 -15
  554. package/templates/database/migrations/20260916120000_artifact_content_store/migration.sql +0 -158
  555. package/templates/database/migrations/20260917120000_callback_request_confirm/migration.sql +0 -40
  556. package/templates/database/migrations/20260918120000_add_appointment/migration.sql +0 -67
  557. package/templates/database/migrations/20260918120000_asset_metadata_columns/migration.sql +0 -70
  558. package/templates/database/migrations/20260919120000_flow_workspace_key/migration.sql +0 -181
  559. package/templates/database/migrations/20260919130000_flow_definition_admin_columns/migration.sql +0 -172
  560. package/templates/database/migrations/20260919130000_workspace_meetings/migration.sql +0 -41
  561. package/templates/database/migrations/20260919140000_inbox_workspace_key/migration.sql +0 -185
  562. package/templates/database/migrations/20260920120000_lead_handled_at/migration.sql +0 -70
  563. package/templates/database/migrations/20260920130000_lead_workspace_source_index/migration.sql +0 -57
  564. package/templates/database/migrations/20260921120000_deliverable_grant_workspace_key/migration.sql +0 -68
  565. package/templates/database/migrations/20260922120000_tenancy_fence/migration.sql +0 -1067
  566. package/templates/database/migrations/20260923120000_listing_capturing_magnet/migration.sql +0 -210
  567. package/templates/database/migrations/20261003120000_spoke_registry/migration.sql +0 -80
  568. package/templates/database/migrations/20261003130000_scheduling_connection/migration.sql +0 -49
  569. package/templates/database/migrations/20261005120000_agents/migration.sql +0 -84
  570. package/templates/database/migrations/20261008120000_user_last_workspace/migration.sql +0 -35
  571. package/templates/database/migrations/20261008130000_lead_idempotency_key/migration.sql +0 -20
  572. package/templates/database/migrations/20261009120000_agent_grants/migration.sql +0 -33
  573. package/templates/database/migrations/20261010120000_person/migration.sql +0 -106
  574. package/templates/database/migrations/20261010121000_person_backfill/migration.sql +0 -132
  575. package/templates/database/migrations/20261010130000_agent_grants_people_read/migration.sql +0 -20
  576. package/templates/database/migrations/20261011120000_member_area/migration.sql +0 -158
  577. package/templates/database/migrations/20261011130000_agent_grants_member_pieces_manage/migration.sql +0 -21
  578. package/templates/database/migrations/20261012120000_member_contract/migration.sql +0 -192
  579. package/templates/database/migrations/20261013120000_lead_spoke_checkout/migration.sql +0 -20
  580. package/templates/database/migrations/20261014120000_consent_ledger/migration.sql +0 -122
  581. package/templates/database/migrations/20261014120000_person_contact/migration.sql +0 -231
  582. package/templates/database/migrations/20261015120000_person_notes/migration.sql +0 -77
  583. package/templates/database/migrations/20261015120000_rate_limit_counters/migration.sql +0 -43
  584. package/templates/database/migrations/20261016120000_piece_kind/migration.sql +0 -95
  585. package/templates/database/migrations/20261017120000_outbound_message_action/migration.sql +0 -30
  586. package/templates/database/migrations/20261018120000_flow_completion/migration.sql +0 -52
  587. package/templates/database/migrations/20261019120000_consent_source_checkout/migration.sql +0 -27
  588. package/templates/database/migrations/20261020120000_offerings_data_model/migration.sql +0 -146
  589. package/templates/database/migrations/20261021120000_offerings_checkout_session/migration.sql +0 -77
  590. package/templates/database/migrations/20261022120000_in_page_magnets/migration.sql +0 -45
  591. package/templates/database/migrations/20261023120000_offerings_shown_price_ids/migration.sql +0 -47
  592. package/templates/database/migrations/20261024120000_organization_plan_checkout_session/migration.sql +0 -16
  593. package/templates/database/migrations/migration_lock.toml +0 -3
  594. package/templates/database/ops/.gitkeep +0 -0
  595. package/templates/database/ops/schema.prisma +0 -43
  596. package/templates/database/package.json +0 -89
  597. package/templates/database/schema.prisma +0 -71
  598. package/templates/database/scripts/db-generate-locked.sh +0 -80
  599. package/templates/database/scripts/person-backfill.sql +0 -132
  600. package/templates/database/tenancy.ts +0 -183
  601. package/templates/database/tsconfig.build.json +0 -16
  602. package/templates/database/tsconfig.flows.json +0 -15
  603. package/templates/database/tsconfig.json +0 -16
  604. package/templates/database/tsconfig.tenancy.json +0 -14
@@ -1,961 +0,0 @@
1
- /**
2
- * @file audit-log.ts
3
- * @description The audit writer (#6040, REL-017 row 5 / FEAT-084 SUB-096;
4
- * reshaped by #3591 D8) — `recordAuditAction`, the one production write site
5
- * for `ops.AuditLog`. Writes exactly one row per audited action: tenant,
6
- * actor, action, and outcome, with personal data redacted before it can
7
- * reach the stored row.
8
- *
9
- * ## WHO ACTED
10
- *
11
- * The caller names the actor: a person (`actorType: "user"`, `actorId` their
12
- * user id), or an agent acting on behalf of a person (`actorType: "agent"`,
13
- * `actorId` the agent's id, `metadata.onBehalfOf` the person's user id). The
14
- * `action` column is `<domain>.<tool>` — `inbox.accept_message`,
15
- * `magnets.magnet.create` — and never says who acted; that is the
16
- * `actorType` column's job.
17
- *
18
- * ## AUDIT FAILURE DOES NOT BLOCK THE AUDITED ACTION
19
- *
20
- * A failed write is reported to the caller and logged at `error`; it never
21
- * throws and never aborts the caller's action. At MVP the audited action is
22
- * frequently already irreversible by the time this writer runs — a Stripe
23
- * refund has been issued, a price has changed — so aborting the caller's
24
- * request after the money moved would make the site lie to its operator
25
- * about what happened. The compensating control is that the failure is
26
- * loud: a typed `{ ok: false }` the caller can branch on, plus a
27
- * `logger.error` line. Nothing in TypeScript FORCES a caller to read the
28
- * result — `await recordAuditAction(input)` as a bare statement compiles
29
- * and lints clean — so the caller issue (#6041 or SUB-097) owns branching on
30
- * `ok` and raising its own alert; a lint/metric enforcing that belongs to
31
- * whichever issue adds the first caller.
32
- *
33
- * ## WHY THIS FILE CARRIES NO `architecture.yaml` EXCEPTION
34
- *
35
- * `architecture.yaml`'s tenant-scope `forbidden_pattern` protects against ONE
36
- * failure mode: an UN-SCOPED read of a listed tenancy/domain model — this
37
- * one included — that could enumerate or leak another tenant's rows. This
38
- * file does not have that failure mode, by construction rather than by
39
- * convention: its write delegate (`AuditWriteClient`, below) declares only
40
- * `create` — no `find*`/`update`/`delete`/`count` — so a read of this model
41
- * is a COMPILE ERROR here, not a review catch. Every write goes through that
42
- * delegate (`db.auditLog.create`), never the raw singleton directly, which
43
- * is WHY it also satisfies the rule MECHANICALLY (the pattern is a raw-text
44
- * scan over the whole file, comments included — so this paragraph is
45
- * deliberately worded to describe the shape without ever writing the literal
46
- * banned call adjacency itself) — the mechanical pass is a consequence of
47
- * meeting the rule's intent, not a way around it. No `paths_excluded` entry
48
- * was added for it (a draft of this design proposed one; it was withdrawn):
49
- * that list is a capability allow-list under the `security_settings` hard
50
- * floor, and this file does not need to widen it. If a later change ever
51
- * inlines a direct singleton call for this model, the lint goes red on this
52
- * file and a human looks — which is the intended outcome, since that change
53
- * would be the first one actually capable of the failure mode the rule
54
- * guards against.
55
- *
56
- * ## THE WRITER CANNOT VERIFY TENANT OWNERSHIP
57
- *
58
- * `tenant` is the full `TenantContext` (never a `Pick`) so a caller must at
59
- * least have *constructed* a resolved-context-shaped value, and
60
- * `workspaceId` is format-validated against `zWorkspaceId` at runtime. But
61
- * an `Id<E>`'s brand is compile-time only — at runtime an id is a plain
62
- * string — so this writer cannot and does not verify that the actor
63
- * genuinely belongs to the workspace it is told. `tenant` MUST come from
64
- * `resolveActiveTenant` (multi-tenant) or `resolveDefaultTenant` /
65
- * `resolveDefaultTenantForOperator` (base) — never assembled from request
66
- * input. That is a caller obligation this file cannot enforce.
67
- *
68
- * ## NOT GATED ON THE `commerce` LICENSE CLAIM
69
- *
70
- * An audit writer a license read can switch off is not an audit writer:
71
- * there is no state in which the right answer to "should this write
72
- * happen?" is "no." Gating stays upstream, at the caller's own
73
- * `require-commerce-claim.ts` check.
74
- *
75
- * External dependency boundaries: `@working-theory/observability` (logger +
76
- * `redactHighEntropy`); `@working-theory/ids` (id format validation +
77
- * the entity registry); `node:crypto` (the id digest); `../lib/prisma.js`
78
- * (the default write delegate, structurally satisfied via `AuditWriteClient`
79
- * — a caller may inject its own, e.g. an interactive `$transaction` client).
80
- */
81
-
82
- import { createHash, randomUUID } from "node:crypto";
83
-
84
- import type { Prisma } from "@working-theory/database";
85
- import {
86
- ENTITIES,
87
- idRegex,
88
- zAuditLogId,
89
- zWorkspaceId,
90
- type Entity,
91
- type Id,
92
- } from "@working-theory/ids";
93
- import { logger, redactHighEntropy } from "@working-theory/observability";
94
-
95
- import { prisma } from "../lib/prisma.js";
96
-
97
- import { isUniqueViolation, type TenantContext } from "./default-tenant.js";
98
-
99
- // ─── Types ──────────────────────────────────────────────────────────────────
100
-
101
- /** The full actor-kind vocabulary the model comments (not a DB CHECK). This
102
- * file writes `"user"` and `"agent"` (#3591 D8), and `"system"` for Stripe's
103
- * payment outcome (#8516 D14, `recordWorkspaceAuditAction`). */
104
- export type AuditActorType = "user" | "agent" | "system";
105
-
106
- /**
107
- * Who acted (#3591 D8) — the same shape as `request.actor`
108
- * (`middleware/auth.ts`'s `RequestActor`), so a route passes it through.
109
- */
110
- export type AuditActor =
111
- | { type: "user"; userId: Id<"user"> }
112
- | { type: "agent"; agentId: Id<"agent">; onBehalfOfUserId: Id<"user"> };
113
-
114
- export type AuditActionOutcome =
115
- "succeeded" | "failed" | "refused" | "awaiting_approval";
116
-
117
- /** One row as this writer assembles it — never re-exported; a caller sees
118
- * only the input/output shapes below. */
119
- /** `metadata`'s closed, versioned shape (D9) — declared with concrete scalar
120
- * value types (never `Record<string, unknown>`) so it structurally satisfies
121
- * Prisma's `InputJsonValue` under `exactOptionalPropertyTypes` — an
122
- * `unknown`-valued record does not. */
123
- interface AuditLogMetadata {
124
- v: 2;
125
- outcome: AuditActionOutcome;
126
- tool: string;
127
- idempotencyKey: string;
128
- /** The person an agent acted for (#3591 D8) — present only on an agent row. */
129
- onBehalfOf?: string;
130
- summary?: string;
131
- failureReason?: string;
132
- }
133
-
134
- interface AuditLogRow {
135
- id: string;
136
- workspaceId: string;
137
- actorId: string;
138
- actorType: AuditActorType;
139
- action: string;
140
- targetType?: string;
141
- targetId?: string;
142
- /** `AuditLogMetadata`'s shape, cast at the call site — Prisma's generated
143
- * `InputJsonObject` requires a `[key: string]: InputJsonValue` index
144
- * signature a named interface does not structurally carry. */
145
- metadata: Prisma.InputJsonValue;
146
- }
147
-
148
- /**
149
- * The one delegate this module writes through — deliberately narrower than
150
- * `PrismaClient["auditLog"]`: it declares ONLY `create`, so a read (which
151
- * would defeat the "cannot leak one tenant's rows to another" property) is a
152
- * compile error, not a review catch. The real `prisma` singleton satisfies
153
- * this structurally (checked by `pnpm type-check`); a caller running inside
154
- * an interactive `$transaction` may pass its `tx` client instead, so the
155
- * audit row can land in the SAME transaction as the action it records.
156
- */
157
- export interface AuditWriteClient {
158
- auditLog: {
159
- create(args: { data: AuditLogRow }): Promise<{ id: string }>;
160
- };
161
- }
162
-
163
- /**
164
- * Every string member is charset- and length-constrained. A value outside
165
- * its constraint is an `invalid_input` refusal, never a truncation or a
166
- * silent coercion — a coerced audit row is a wrong audit row.
167
- */
168
- export interface RecordAuditActionInput {
169
- /** MUST come from `resolveActiveTenant` / `resolveDefaultTenant` — never
170
- * assembled from request input. See the file docblock. */
171
- tenant: TenantContext;
172
- /** Who acted — `request.actor`. Each id it carries is <=128 chars,
173
- * `/^[A-Za-z0-9_:.-]+$/`, then personal-data-scanned unless it is a
174
- * registry-minted `user_` or `agent_` id. */
175
- actor: AuditActor;
176
- /** <=32 chars, `/^[a-z][a-z0-9_]*$/` — the area the action belongs to
177
- * (`"inbox"`, `"magnets"`, `"scheduling"`), the first segment of
178
- * `action`. */
179
- domain: string;
180
- /** <=64 chars, `/^[a-z0-9_.-]+$/` — an identifier, so `action` cannot
181
- * carry prose. */
182
- tool: string;
183
- outcome: AuditActionOutcome;
184
- /** <=256 chars, `/^[A-Za-z0-9_:.-]+$/`, then personal-data-scanned.
185
- * REQUIRED — an optional key would silently degrade to "no dedup" for a
186
- * caller who forgets it. Stable across a replay of the same logical
187
- * action (the MCP request/tool-call id, or the provider event id).
188
- *
189
- * MUST be process-INDEPENDENT (#6231): a value unique to one logical
190
- * action across every instance, such as a client-supplied idempotency
191
- * header, a provider event id, or a fresh `crypto.randomUUID()`. Never
192
- * Fastify's default `request.id` — `req-<base36>` is a per-process
193
- * counter that restarts at `req-1` on every fresh serverless instance,
194
- * so two genuine actions on two instances can share a key. Since
195
- * `deriveAuditRowId` digests every field the row carries and a caller's
196
- * other digest inputs are typically constant, a shared key makes the
197
- * SECOND genuine action collide on the primary key and be reported
198
- * `duplicate` — a real action left unaudited. */
199
- idempotencyKey: string;
200
- /** <=2000 chars, NFKC-normalised, entropy- and personal-data-scanned. */
201
- summary?: string;
202
- /** <=2000 chars, same treatment. Provider error text lands here — hence
203
- * the entropy scan (a live secret is more likely to arrive here than in
204
- * `summary`). */
205
- failureReason?: string;
206
- /** <=32 chars, `/^[a-z][a-z0-9_]*$/`. */
207
- targetType?: string;
208
- /** <=128 chars; `zId`-validated against the entity registry when
209
- * `targetType` names a known entity, else a generic identifier charset. */
210
- targetId?: string;
211
- }
212
-
213
- /** Every member of a row's input but who and where — shared by both writers. */
214
- type AuditRowInput = Omit<RecordAuditActionInput, "tenant" | "actor">;
215
-
216
- /** Every actor a row can name: a tenant caller's, or a tenant-less one's (D14). */
217
- type WriterActor = AuditActor | { type: "system"; systemId: "stripe" };
218
-
219
- export type RecordAuditActionResult =
220
- | { ok: true; outcome: "recorded" | "duplicate"; id: Id<"auditLog"> }
221
- | {
222
- ok: false;
223
- error: {
224
- kind: "invalid_input" | "write_failed";
225
- message: string;
226
- /** ALWAYS false — one insert, no transaction, nothing partial to
227
- * leave behind. */
228
- persisted: false;
229
- };
230
- };
231
-
232
- /**
233
- * The fields `deriveAuditRowId` digests, in the ONE fixed order used by
234
- * every caller — every field the row will carry, so pre-empting a row
235
- * requires writing a byte-identical one (D8). `summary` / `failureReason`
236
- * here are the POST-REDACTION values (what will actually be stored);
237
- * `idempotencyKey` is the RAW caller-supplied value, so a replay under the
238
- * same key always digests identically regardless of any future redaction
239
- * change.
240
- */
241
- export interface AuditRowDigestInput {
242
- workspaceId: string;
243
- actorId: string;
244
- actorType: AuditActorType;
245
- onBehalfOf: string | undefined;
246
- action: string;
247
- targetType: string | undefined;
248
- targetId: string | undefined;
249
- outcome: AuditActionOutcome;
250
- summary: string | undefined;
251
- failureReason: string | undefined;
252
- idempotencyKey: string;
253
- }
254
-
255
- // ─── Constants ──────────────────────────────────────────────────────────────
256
-
257
- /** The free-text cap (`summary` / `failureReason`) — bounds both the stored
258
- * row and the redaction scan's regex work. Rejected above it, not
259
- * truncated. */
260
- const MAX_TEXT = 2_000;
261
-
262
- /** An MCP tool name is an identifier — this charset cannot express an `@`,
263
- * and it bounds the `action` column (`domain + "." + tool`). */
264
- const TOOL_RE = /^[a-z0-9_.-]{1,64}$/;
265
-
266
- /** The action's first segment — `"inbox"`, `"magnets"`, `"scheduling"`. */
267
- const DOMAIN_RE = /^[a-z][a-z0-9_]{0,31}$/;
268
-
269
- /** The schema's own examples are `"workspace"`, `"lead"`, `"user"`. */
270
- const TARGET_TYPE_RE = /^[a-z][a-z0-9_]{0,31}$/;
271
-
272
- /** An actor id's shape is open (Q2) — any identifier, registry-minted or not. */
273
- const ACTOR_ID_RE = /^[A-Za-z0-9_:.-]{1,128}$/;
274
-
275
- /** `targetId` when `targetType` does not name a known registry entity. */
276
- const TARGET_ID_FALLBACK_RE = /^[A-Za-z0-9_:-]{1,128}$/;
277
-
278
- /** The MCP request/tool-call id or provider event id — an identifier, not
279
- * prose. */
280
- const IDEMPOTENCY_KEY_RE = /^[A-Za-z0-9_:.-]{1,256}$/;
281
-
282
- /** NUL and the rest of the C0 control range. Postgres `text` cannot store
283
- * U+0000 — an unvalidated NUL anywhere in a free-text member is a
284
- * repeatable audit-disable switch under the fail-open policy above. */
285
- // eslint-disable-next-line no-control-regex -- the control-character range is exactly what F9 must detect and refuse (a NUL in `text` fails every Postgres insert).
286
- const C0_CONTROL_RE = /[\x00-\x1f]/;
287
-
288
- /**
289
- * Email — RFC-ish local + domain, no nested quantifier. The domain segment
290
- * is a negated class (`[^\s@]`, not `[A-Za-z0-9.-]`) so an
291
- * internationalised/homoglyph domain is still bounded and redacted rather
292
- * than silently admitted past the pattern.
293
- */
294
- const EMAIL_RE = /[^\s@]{1,64}@[^\s@]{1,255}\.[A-Za-z]{2,24}/g;
295
-
296
- /**
297
- * International phone — an optional leading `+`, then 7-15 digits with
298
- * optional space/dot/dash separators between them. No separator is also
299
- * accepted (a bare digit run), which is deliberate belt-and-braces: it also
300
- * catches a phone number typed with no separators at all.
301
- */
302
- const PHONE_RE = /\+?\d(?:[ .-]?\d){6,14}/g;
303
-
304
- /** Long digit runs (9+) — account- and card-shaped numbers not already
305
- * caught by the phone pattern (its separators are optional, so most digit
306
- * runs are already consumed above; this is the residual). */
307
- const LONG_DIGIT_RUN_RE = /\d{9,}/g;
308
-
309
- /**
310
- * Where free text splits into tokens for the registry-id exemption below:
311
- * whitespace and `=` (so `responsibleUserId=<id>` holds the id as a token).
312
- */
313
- const FREE_TEXT_TOKEN_SEPARATOR_RE = /(\s+|=)/;
314
-
315
- /**
316
- * Whether a free-text token is EXACTLY a registry-minted `user_` or `agent_`
317
- * id (#3591 D8) — the same anchored pattern `actorIdRefusal` exempts. Such an
318
- * id's hex can hold a digit run the phone pattern flags (about one id in
319
- * three), which would turn a `summary` that names a person by id — the agent
320
- * lifecycle rows' "for whom" — into `[REDACTED:phone]`. A token that merely
321
- * contains one, or only looks like one, is scanned like any other text.
322
- */
323
- function isRegistryActorId(token: string): boolean {
324
- return idRegex("user").test(token) || idRegex("agent").test(token);
325
- }
326
-
327
- const EMAIL_MARKER = "[REDACTED:email]";
328
- const PHONE_MARKER = "[REDACTED:phone]";
329
- const NUMBER_MARKER = "[REDACTED:number]";
330
-
331
- // ─── Pure helpers (D1 — directly unit-testable, no database) ───────────────
332
-
333
- /** True when `value` names a registered `packages/ids` entity — the branch
334
- * that lets `targetId` be validated against the entity's own id grammar
335
- * rather than the generic fallback. */
336
- function isKnownEntity(value: string): value is Entity {
337
- return (ENTITIES as readonly string[]).includes(value);
338
- }
339
-
340
- /**
341
- * Redacts personal data from a free-text value: caps (the CALLER enforces
342
- * the cap as a rejection — this function assumes an already-capped input),
343
- * NFKC-normalises (so a full-width or other compatibility form does not
344
- * walk past a pattern that would catch its canonical twin), runs
345
- * `redactHighEntropy` first (catches a live secret pasted into
346
- * `failureReason` — the natural home for provider error text), then applies
347
- * the three anchored, bounded personal-data patterns. Exported — directly
348
- * unit-testable, and reused (as a detection predicate) for the actor's ids
349
- * and `idempotencyKey` below.
350
- *
351
- * What this does NOT catch, stated rather than implied: a postal address or
352
- * a personal name in free text (no achievable regex exists across locales),
353
- * an obfuscated address ("jane dot doe at example dot com"), a date of
354
- * birth, or a national identifier. The allow-list (this file's input type
355
- * has no member whose purpose is a buyer's identity) and the charset
356
- * constraints below are the guarantee; this scan is defence-in-depth over
357
- * the two members that must stay free text.
358
- */
359
- export function redactPersonalData(text: string): string {
360
- let out = text.normalize("NFKC");
361
- out = redactHighEntropy(out);
362
- out = out.replace(EMAIL_RE, EMAIL_MARKER);
363
- // Long-digit-run BEFORE phone, deliberately: its unbounded `{9,}` consumes
364
- // an arbitrarily-long unseparated digit run (a card/account number) in ONE
365
- // match, whereas the phone pattern's bounded `{6,14}` would otherwise eat
366
- // only the first 15 digits of a longer run and leave a ragged remainder.
367
- // A phone number written WITH separators (spaces/dots/dashes) has no
368
- // contiguous 9+ digit substring, so this pass never touches it.
369
- out = out.replace(LONG_DIGIT_RUN_RE, NUMBER_MARKER);
370
- out = out.replace(PHONE_RE, PHONE_MARKER);
371
- return out;
372
- }
373
-
374
- /**
375
- * `summary` / `failureReason`'s redaction: `redactPersonalData`, except that a
376
- * token which is exactly a registry `user_` / `agent_` id is kept whole (see
377
- * `isRegistryActorId`). The text between such tokens is scanned as ONE run,
378
- * separators included, so a phone number written with spaces is still caught.
379
- * Identifier fields are not routed here — an actor id has its own exemption,
380
- * and `idempotencyKey` stays scanned.
381
- */
382
- function redactFreeText(text: string): string {
383
- let out = "";
384
- let run = "";
385
- for (const part of text.normalize("NFKC").split(FREE_TEXT_TOKEN_SEPARATOR_RE)) {
386
- if (isRegistryActorId(part)) {
387
- out += redactPersonalData(run) + part;
388
- run = "";
389
- } else {
390
- run += part;
391
- }
392
- }
393
- return out + redactPersonalData(run);
394
- }
395
-
396
- /** True when `redactPersonalData` would change `text` — used to REFUSE
397
- * (never silently rewrite) an identifier-shaped field that happens to
398
- * contain a personal-data-shaped substring (an actor id, `idempotencyKey`). */
399
- function personalDataDetected(text: string): boolean {
400
- // Checked by MARKER PRESENCE, not by inequality against the input — an
401
- // inequality check is a call-order-dependent accident: NFKC alone can
402
- // change a string with no personal data present (a full-width form
403
- // folding to its ASCII twin) with nothing to redact, and that must never
404
- // read as "detected" regardless of what charset check a future caller
405
- // does or doesn't run first (code review, #6040).
406
- const redacted = redactPersonalData(text);
407
- return (
408
- redacted.includes(EMAIL_MARKER) ||
409
- redacted.includes(PHONE_MARKER) ||
410
- redacted.includes(NUMBER_MARKER)
411
- );
412
- }
413
-
414
- /**
415
- * Derives the row's primary key deterministically from every field the row
416
- * will carry (D8) — the mechanism that makes AC-4 (replay produces no
417
- * duplicate) hold on a table whose only unique constraint is its primary
418
- * key. Each field is encoded as a 1-byte presence flag, then (when present)
419
- * a 4-byte big-endian UTF-8 byte length, then the UTF-8 bytes themselves —
420
- * length-PREFIXED, not separator-delimited, so no component boundary is
421
- * expressible inside a component (a `tool`/`idempotencyKey` pair that
422
- * shifts content across the two fields' boundary digests differently,
423
- * because the length prefixes differ).
424
- *
425
- * The sha256 digest's first 16 bytes become a uuid with the version nibble
426
- * forced to `7` and the variant nibble forced to `8`, satisfying the
427
- * `audit_logs_id_format` DB CHECK constraint
428
- * (`database/migrations/20260713192429_prefixed_uuid_entity_ids/migration.sql:158`)
429
- * and `zAuditLogId`. `createdAt` is deliberately NOT a digest input (nor an
430
- * insert column — the database clock supplies it) — including it would make
431
- * every call mint a fresh id and destroy replay detection entirely.
432
- *
433
- * Widening the digest to the WHOLE row (rather than a caller-controlled
434
- * subset) is what defeats an agent pre-writing a harmless decoy to suppress
435
- * its real action's record: pre-empting a row now requires writing one with
436
- * byte-identical content, which means the correct record already exists.
437
- */
438
- export function deriveAuditRowId(input: AuditRowDigestInput): string {
439
- const parts: Array<string | undefined> = [
440
- input.workspaceId,
441
- input.actorId,
442
- input.actorType,
443
- input.onBehalfOf,
444
- input.action,
445
- input.targetType,
446
- input.targetId,
447
- input.outcome,
448
- input.summary,
449
- input.failureReason,
450
- input.idempotencyKey,
451
- ];
452
- const encoded = Buffer.concat(parts.map(encodeDigestField));
453
- const digest = createHash("sha256").update(encoded).digest();
454
- const bytes = Buffer.from(digest.subarray(0, 16));
455
- bytes[6] = ((bytes[6] ?? 0) & 0x0f) | 0x70; // version 7
456
- bytes[8] = ((bytes[8] ?? 0) & 0x0f) | 0x80; // variant 8 (satisfies the [89ab] CHECK)
457
- const hex = bytes.toString("hex");
458
- const uuid = `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
459
- return `audit_${uuid}`;
460
- }
461
-
462
- /** One digest component: a 1-byte presence flag, then (when present) a
463
- * fixed-width 4-byte length prefix plus the UTF-8 bytes. `undefined` is
464
- * encoded distinctly from an empty string. */
465
- function encodeDigestField(value: string | undefined): Buffer {
466
- if (value === undefined) {
467
- return Buffer.from([0]);
468
- }
469
- const bytes = Buffer.from(value, "utf8");
470
- const length = Buffer.alloc(4);
471
- length.writeUInt32BE(bytes.length, 0);
472
- return Buffer.concat([Buffer.from([1]), length, bytes]);
473
- }
474
-
475
- /** `error.code` / `error.constructor.name` only — never the message, which
476
- * on this writer embeds the audit row itself (`summary`, `actorId`,
477
- * `targetId`, `idempotencyKey`) via Prisma's validation-error `data`
478
- * argument (N7, D10). */
479
- function classifyError(error: unknown): { code: string; name: string } {
480
- const code =
481
- typeof error === "object" &&
482
- error !== null &&
483
- "code" in error &&
484
- typeof (error as { code?: unknown }).code === "string"
485
- ? (error as { code: string }).code
486
- : "unknown";
487
- const name = error instanceof Error ? error.constructor.name : typeof error;
488
- return { code, name };
489
- }
490
-
491
- // ─── Input validation ───────────────────────────────────────────────────────
492
-
493
- interface ValidatedFields {
494
- workspaceId: string;
495
- actorId: string;
496
- actorType: AuditActorType;
497
- onBehalfOf: string | undefined;
498
- tool: string;
499
- targetType: string | undefined;
500
- targetId: string | undefined;
501
- redactedSummary: string | undefined;
502
- redactedFailureReason: string | undefined;
503
- }
504
-
505
- type ValidationResult =
506
- { ok: true; value: ValidatedFields } | { ok: false; message: string };
507
-
508
- /** Caps first (rejected, not truncated), then rejects a NUL or other C0
509
- * control character (F9 — Postgres `text` cannot store U+0000), then
510
- * redacts. Absent input passes through as `undefined`. */
511
- function validateFreeText(
512
- text: string | undefined,
513
- ): { ok: true; value: string | undefined } | { ok: false; message: string } {
514
- if (text === undefined) {
515
- return { ok: true, value: undefined };
516
- }
517
- if (text.length > MAX_TEXT) {
518
- return { ok: false, message: `exceeds the ${MAX_TEXT}-character cap` };
519
- }
520
- if (C0_CONTROL_RE.test(text)) {
521
- return {
522
- ok: false,
523
- message: "contains a NUL or other C0 control character",
524
- };
525
- }
526
- return { ok: true, value: redactFreeText(text) };
527
- }
528
-
529
- /**
530
- * An actor's id: the identifier grammar, then the personal-data scan — except
531
- * for a registry-minted `user_` or `agent_` id, which is an identifier, not
532
- * personal data. Its hex can still hold a digit run the phone pattern flags
533
- * (about one id in three), which silently dropped real actors' rows (#7636
534
- * D7, security review finding 1; #3591 D8). Every other id is still scanned.
535
- * Returns the refusal message, or `undefined` when the id is admitted.
536
- */
537
- function actorIdRefusal(id: string, field: string): string | undefined {
538
- if (!ACTOR_ID_RE.test(id)) {
539
- return `${field} does not match the required identifier grammar`;
540
- }
541
- const registryId = idRegex("user").test(id) || idRegex("agent").test(id);
542
- if (!registryId && personalDataDetected(id)) {
543
- return `${field} appears to carry personal data`;
544
- }
545
- return undefined;
546
- }
547
-
548
- /**
549
- * Validates every string member before it is digested or written (F9).
550
- * Identifier-shaped members are REFUSED on a constraint violation, never
551
- * coerced — a coerced audit row is a wrong audit row (D5). The actor's ids
552
- * and `idempotencyKey` additionally fail the personal-data scan as a REFUSAL
553
- * (never a silent rewrite of an identifier field) rather than as a
554
- * redaction, unlike `summary` / `failureReason`.
555
- */
556
- function validateInput(
557
- workspaceId: string,
558
- workspaceField: string,
559
- actor: WriterActor,
560
- input: AuditRowInput,
561
- ): ValidationResult {
562
- if (!zWorkspaceId.safeParse(workspaceId).success) {
563
- return {
564
- ok: false,
565
- message: `${workspaceField} is not a valid workspace id`,
566
- };
567
- }
568
- const actorId =
569
- actor.type === "agent"
570
- ? actor.agentId
571
- : actor.type === "system"
572
- ? actor.systemId
573
- : actor.userId;
574
- const actorRefusal = actorIdRefusal(actorId, "actorId");
575
- if (actorRefusal !== undefined) {
576
- return { ok: false, message: actorRefusal };
577
- }
578
- const onBehalfOf = actor.type === "agent" ? actor.onBehalfOfUserId : undefined;
579
- if (onBehalfOf !== undefined) {
580
- const onBehalfOfRefusal = actorIdRefusal(onBehalfOf, "onBehalfOf");
581
- if (onBehalfOfRefusal !== undefined) {
582
- return { ok: false, message: onBehalfOfRefusal };
583
- }
584
- }
585
- if (!DOMAIN_RE.test(input.domain)) {
586
- return {
587
- ok: false,
588
- message: "domain does not match the required identifier grammar",
589
- };
590
- }
591
- if (!TOOL_RE.test(input.tool)) {
592
- return {
593
- ok: false,
594
- message: "tool does not match the required identifier grammar",
595
- };
596
- }
597
- if (!IDEMPOTENCY_KEY_RE.test(input.idempotencyKey)) {
598
- return {
599
- ok: false,
600
- message: "idempotencyKey does not match the required identifier grammar",
601
- };
602
- }
603
- if (personalDataDetected(input.idempotencyKey)) {
604
- return {
605
- ok: false,
606
- message: "idempotencyKey appears to carry personal data",
607
- };
608
- }
609
- if (
610
- input.targetType !== undefined &&
611
- !TARGET_TYPE_RE.test(input.targetType)
612
- ) {
613
- return {
614
- ok: false,
615
- message: "targetType does not match the required identifier grammar",
616
- };
617
- }
618
- if (input.targetId !== undefined) {
619
- const targetIdRe =
620
- input.targetType !== undefined && isKnownEntity(input.targetType)
621
- ? idRegex(input.targetType)
622
- : TARGET_ID_FALLBACK_RE;
623
- if (!targetIdRe.test(input.targetId)) {
624
- return {
625
- ok: false,
626
- message:
627
- "targetId does not match the required grammar for its targetType",
628
- };
629
- }
630
- }
631
- const summaryCheck = validateFreeText(input.summary);
632
- if (!summaryCheck.ok) {
633
- return { ok: false, message: `summary ${summaryCheck.message}` };
634
- }
635
- const failureReasonCheck = validateFreeText(input.failureReason);
636
- if (!failureReasonCheck.ok) {
637
- return {
638
- ok: false,
639
- message: `failureReason ${failureReasonCheck.message}`,
640
- };
641
- }
642
-
643
- return {
644
- ok: true,
645
- value: {
646
- workspaceId,
647
- actorId,
648
- actorType: actor.type,
649
- onBehalfOf,
650
- tool: input.tool,
651
- targetType: input.targetType,
652
- targetId: input.targetId,
653
- redactedSummary: summaryCheck.value,
654
- redactedFailureReason: failureReasonCheck.value,
655
- },
656
- };
657
- }
658
-
659
- /**
660
- * One fresh, process-independent audit idempotency key (#6231; moved here
661
- * from `routes/magnets/index.ts` so every route writer shares it, #7636): a
662
- * `crypto.randomUUID()` with its dashes removed and its 32 hex characters
663
- * regrouped into runs of six joined by `_` (e.g.
664
- * `e4a940_bf8d33_4c2281_4b1b27_4461cd_19`).
665
- *
666
- * The regrouping is load-bearing, not cosmetic. `recordAuditAction` REFUSES
667
- * an `idempotencyKey` its personal-data scan flags — a refusal writes no row
668
- * at all — and that scan's phone pattern treats `-` as a digit separator,
669
- * so a raw dashed uuid whose hex happens to be digit-heavy reads as a phone
670
- * number: measured over 200k uuids, 37% are refused. `_` is not one of that
671
- * pattern's separators (and is inside the key's allowed charset), so
672
- * grouping caps every digit run at six — under the phone pattern's 7-digit
673
- * floor and the long-digit-run pattern's 9 — and no generated key can be
674
- * refused. Entropy is untouched: the same 128 bits, re-spelled.
675
- */
676
- export function freshAuditIdempotencyKey(): string {
677
- return randomUUID().replace(/-/g, "").replace(/(.{6})(?=.)/g, "$1_");
678
- }
679
-
680
- // ─── The writer ─────────────────────────────────────────────────────────────
681
-
682
- /**
683
- * Writes exactly one `audit_logs` row for one audited action. Never throws;
684
- * never blocks the caller's action (see the file docblock heading). Not
685
- * gated on the `commerce` license claim (see the file docblock) — gating
686
- * stays upstream, at the caller's own claim check.
687
- */
688
- export async function recordAuditAction(
689
- input: RecordAuditActionInput,
690
- db: AuditWriteClient = prisma,
691
- ): Promise<RecordAuditActionResult> {
692
- const { tenant, actor, ...row } = input;
693
- return writeAuditRow(tenant.workspaceId, "tenant.workspaceId", actor, row, db);
694
- }
695
-
696
- /**
697
- * Who acted on a tenant-less row (#8516 D14): a client — a signed-in person
698
- * with no membership — or Stripe itself, reporting a payment outcome.
699
- */
700
- export type WorkspaceAuditActor =
701
- | { type: "user"; userId: Id<"user"> }
702
- | { type: "system"; systemId: "stripe" };
703
-
704
- /** `recordWorkspaceAuditAction`'s input: a workspace id in place of a tenant. */
705
- export type RecordWorkspaceAuditActionInput = AuditRowInput & {
706
- workspaceId: string;
707
- actor: WorkspaceAuditActor;
708
- };
709
-
710
- /**
711
- * One `audit_logs` row for a caller that holds no `TenantContext` (#8516
712
- * D14): a client acting in the member area, or a Stripe webhook. Writes the
713
- * row `recordAuditAction` would for the same workspace and user actor; the
714
- * system actor stores `actor_type` `system` and `actor_id` `stripe`. Never
715
- * throws; never blocks the caller's action.
716
- *
717
- * CALLER OBLIGATION — `workspaceId` MUST come from `resolveMember`'s
718
- * resolved workspace, or from a Stripe-signed event's server-written
719
- * metadata matched to a stored row — NEVER from request input. A client
720
- * actor's row says so in its `tool` and summary (`by: "client"`), so it is
721
- * never read as a staff member's action.
722
- */
723
- export async function recordWorkspaceAuditAction(
724
- input: RecordWorkspaceAuditActionInput,
725
- db: AuditWriteClient = prisma,
726
- ): Promise<RecordAuditActionResult> {
727
- const { workspaceId, actor, ...row } = input;
728
- return writeAuditRow(workspaceId, "workspaceId", actor, row, db);
729
- }
730
-
731
- /** The body of both writers: one validated, digested, idempotent insert. */
732
- async function writeAuditRow(
733
- workspaceIdInput: string,
734
- workspaceField: string,
735
- actor: WriterActor,
736
- input: AuditRowInput,
737
- db: AuditWriteClient,
738
- ): Promise<RecordAuditActionResult> {
739
- const validated = validateInput(workspaceIdInput, workspaceField, actor, input);
740
- if (!validated.ok) {
741
- return {
742
- ok: false,
743
- error: {
744
- kind: "invalid_input",
745
- message: validated.message,
746
- persisted: false,
747
- },
748
- };
749
- }
750
-
751
- const {
752
- workspaceId,
753
- actorId,
754
- actorType,
755
- onBehalfOf,
756
- tool,
757
- targetType,
758
- targetId,
759
- redactedSummary,
760
- redactedFailureReason,
761
- } = validated.value;
762
- const action = `${input.domain}.${tool}`;
763
-
764
- const id = deriveAuditRowId({
765
- workspaceId,
766
- actorId,
767
- actorType,
768
- onBehalfOf,
769
- action,
770
- targetType,
771
- targetId,
772
- outcome: input.outcome,
773
- summary: redactedSummary,
774
- failureReason: redactedFailureReason,
775
- idempotencyKey: input.idempotencyKey,
776
- });
777
-
778
- if (!zAuditLogId.safeParse(id).success) {
779
- // Structurally unreachable given the derivation above (sha256 digest,
780
- // version/variant nibbles forced) — a defensive guard, never observed
781
- // to fire, kept because the format authority stays in `packages/ids`
782
- // even though the derivation lives here (D8).
783
- logger.error(
784
- { workspaceId, action, actorType },
785
- "[audit-log] derived id failed format validation",
786
- );
787
- return {
788
- ok: false,
789
- error: {
790
- kind: "write_failed",
791
- message: "audit row write failed",
792
- persisted: false,
793
- },
794
- };
795
- }
796
-
797
- const metadata: AuditLogMetadata = {
798
- v: 2,
799
- outcome: input.outcome,
800
- tool,
801
- idempotencyKey: input.idempotencyKey,
802
- ...(onBehalfOf !== undefined && { onBehalfOf }),
803
- ...(redactedSummary !== undefined && { summary: redactedSummary }),
804
- ...(redactedFailureReason !== undefined && {
805
- failureReason: redactedFailureReason,
806
- }),
807
- };
808
-
809
- const row: AuditLogRow = {
810
- id,
811
- workspaceId,
812
- actorId,
813
- actorType,
814
- action,
815
- ...(targetType !== undefined && { targetType }),
816
- ...(targetId !== undefined && { targetId }),
817
-
818
- metadata: metadata as unknown as Prisma.InputJsonValue,
819
- };
820
-
821
- try {
822
- // The delegate's resolved `{ id }` is discarded deliberately — the row's
823
- // id is `id` above (the digest this writer derived), never a value the
824
- // database could have generated differently (code review, #6040).
825
- await db.auditLog.create({ data: row });
826
- return { ok: true, outcome: "recorded", id: id as Id<"auditLog"> };
827
- } catch (error) {
828
- if (isUniqueViolation(error)) {
829
- // F10 — a replay is reported, not silent. The colliding id IS the
830
- // stored row's id (that is the whole point of a deterministic PK), so
831
- // no read is needed to report it.
832
- logger.warn(
833
- { workspaceId, action, actorType, auditLogId: id },
834
- "[audit-log] duplicate audit row suppressed by primary key",
835
- );
836
- return { ok: true, outcome: "duplicate", id: id as Id<"auditLog"> };
837
- }
838
- const { code, name } = classifyError(error);
839
- // Never `error.message` — on this writer the Prisma validation `data`
840
- // argument IS the audit row (N7, D10).
841
- logger.error(
842
- { workspaceId, action, actorType, errorCode: code, errorName: name },
843
- "[audit-log] audit row write failed",
844
- );
845
- return {
846
- ok: false,
847
- error: {
848
- kind: "write_failed",
849
- message: "audit row write failed",
850
- persisted: false,
851
- },
852
- };
853
- }
854
- }
855
-
856
- // ─── Route helpers (#3591 D8) ───────────────────────────────────────────────
857
-
858
- /**
859
- * The actor a route records: `request.actor`, which the auth preHandler sets
860
- * on every authenticated request. A route reached without it (a harness that
861
- * seats `request.tenant` directly) is filed as the tenant's own person, with a
862
- * `warn` — an auth path that forgot to bind the actor must not pass silently.
863
- */
864
- export function auditActorFor(
865
- actor: AuditActor | undefined,
866
- tenant: TenantContext,
867
- ): AuditActor {
868
- if (actor) return actor;
869
- logger.warn(
870
- { workspaceId: tenant.workspaceId },
871
- "[audit-log] no request actor; filing the tenant's person",
872
- );
873
- return { type: "user", userId: tenant.userId };
874
- }
875
-
876
- /** A service call's result, as far as the audit row needs it. */
877
- export type AuditedResult = { ok: true } | { ok: false; error: { kind: string } };
878
-
879
- /**
880
- * Who a route says acted, as far as `recordAgentWrite` reads it: the request
881
- * itself (`request.actor`, and `request.agent` on the agent path), or — the
882
- * older call shape — `request.actor` alone.
883
- */
884
- export type AgentWriteCaller =
885
- | AuditActor
886
- | undefined
887
- | { actor?: AuditActor; agent?: { agentId: Id<"agent"> } };
888
-
889
- /**
890
- * #3591 D8 — one row for an agent's inbox write, recorded after the write
891
- * returns: `succeeded` when it did, else `failed` with the service's error
892
- * kind. A person's write records nothing (spec § 2.3: a person's inbox
893
- * actions are not audited). A failed audit write is logged at `error` once —
894
- * by the writer for a failed insert, here for a refused row — and returns
895
- * normally, so it never changes the caller's response.
896
- *
897
- * Pass the request, not `request.actor` alone, so an agent write cannot go
898
- * unrecorded in silence: a request with `request.agent` but no
899
- * `request.actor` (an auth path that forgot to bind the actor) is logged at
900
- * `error` and still recorded, from `request.agent`. Its person is
901
- * `tenant.userId`: on the agent path the tenant guard grants the workspace
902
- * through the agent's responsible membership, so the tenant's person IS the
903
- * person the agent acts for — read from the grant, not guessed.
904
- */
905
- export async function recordAgentWrite(
906
- caller: AgentWriteCaller,
907
- input: Omit<
908
- RecordAuditActionInput,
909
- "actor" | "outcome" | "failureReason" | "idempotencyKey"
910
- >,
911
- result: AuditedResult,
912
- db: AuditWriteClient = prisma,
913
- ): Promise<void> {
914
- const actor = agentWriteActor(caller, input);
915
- if (actor?.type !== "agent") return;
916
- const audit = await recordAuditAction(
917
- {
918
- ...input,
919
- actor,
920
- idempotencyKey: freshAuditIdempotencyKey(),
921
- ...(result.ok
922
- ? { outcome: "succeeded" as const }
923
- : { outcome: "failed" as const, failureReason: result.error.kind }),
924
- },
925
- db,
926
- );
927
- if (!audit.ok && audit.error.kind === "invalid_input") {
928
- logger.error(
929
- {
930
- workspaceId: input.tenant.workspaceId,
931
- action: `${input.domain}.${input.tool}`,
932
- actorId: actor.agentId,
933
- error: audit.error,
934
- },
935
- "[audit-log] agent write audit refused",
936
- );
937
- }
938
- }
939
-
940
- /** The actor `recordAgentWrite` files — see its docblock for the fallback. */
941
- function agentWriteActor(
942
- caller: AgentWriteCaller,
943
- input: { tenant: TenantContext; domain: string; tool: string },
944
- ): AuditActor | undefined {
945
- if (caller === undefined || "type" in caller) return caller;
946
- if (caller.actor) return caller.actor;
947
- if (!caller.agent) return undefined;
948
- logger.error(
949
- {
950
- workspaceId: input.tenant.workspaceId,
951
- action: `${input.domain}.${input.tool}`,
952
- actorId: caller.agent.agentId,
953
- },
954
- "[audit-log] agent write without request.actor; recording from request.agent",
955
- );
956
- return {
957
- type: "agent",
958
- agentId: caller.agent.agentId,
959
- onBehalfOfUserId: input.tenant.userId,
960
- };
961
- }