create-ailk 0.17.0 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (193) hide show
  1. package/LICENSE +6 -5
  2. package/NOTICE +2 -0
  3. package/dist/add-module.js +4 -1
  4. package/dist/category-profile.d.ts +10 -0
  5. package/dist/category-profile.js +21 -0
  6. package/dist/derive-architecture.d.ts +5 -1
  7. package/dist/derive-architecture.js +8 -3
  8. package/dist/lib/env-catalog.js +5 -9
  9. package/dist/lib/license-key-files.d.ts +6 -3
  10. package/dist/lib/license-key-files.js +8 -2
  11. package/dist/lib/scaffold-render-sweep.d.ts +9 -0
  12. package/dist/lib/scaffold-render-sweep.js +24 -3
  13. package/dist/license-set.d.ts +1 -1
  14. package/dist/license-set.js +13 -8
  15. package/dist/module-architecture.js +119 -0
  16. package/dist/programmatic.js +3 -0
  17. package/dist/spoke-checkout.d.ts +11 -3
  18. package/dist/spoke-checkout.js +62 -12
  19. package/dist/starter-grid.d.ts +1 -1
  20. package/dist/surfaces.js +140 -1
  21. package/dist/template-manifest.d.ts +4 -3
  22. package/dist/topology.d.ts +15 -2
  23. package/dist/topology.js +83 -4
  24. package/package.json +5 -4
  25. package/templates/.env.example +3 -3
  26. package/templates/.github/workflows/ci.yml +5 -0
  27. package/templates/apps/api/CLAUDE.md +25 -7
  28. package/templates/apps/api/LICENSE +6 -5
  29. package/templates/apps/api/NOTICE +2 -0
  30. package/templates/apps/api/jest.config.cjs +4 -29
  31. package/templates/apps/api/package.json +1 -0
  32. package/templates/apps/api/src/lib/__mocks__/prisma.ts +9 -0
  33. package/templates/apps/api/src/lib/__tests__/deliverable-asset-store.test.ts +38 -0
  34. package/templates/apps/api/src/lib/deliverable-asset-store.ts +5 -4
  35. package/templates/apps/api/src/lib/stripe.ts +81 -0
  36. package/templates/apps/api/src/middleware/__tests__/auth.hub-session-path.test.ts +266 -39
  37. package/templates/apps/api/src/middleware/auth.ts +206 -46
  38. package/templates/apps/api/src/routes/leads/index.ts +4 -0
  39. package/templates/apps/api/src/server.ts +107 -0
  40. package/templates/apps/api/src/services/__tests__/lead-routing.test.ts +58 -0
  41. package/templates/apps/api/src/services/lead-routing.ts +30 -2
  42. package/templates/apps/api/vercel.json +2 -2
  43. package/templates/apps/mcp/.env.example +10 -0
  44. package/templates/apps/mcp/CLAUDE.md +58 -7
  45. package/templates/apps/mcp/LICENSE +6 -5
  46. package/templates/apps/mcp/NOTICE +2 -0
  47. package/templates/apps/mcp/__tests__/abuse/guard.test.ts +198 -0
  48. package/templates/apps/mcp/__tests__/app-entry.test.ts +325 -0
  49. package/templates/apps/mcp/__tests__/audit-single-page.test.ts +15 -3
  50. package/templates/apps/mcp/__tests__/boot.test.ts +280 -0
  51. package/templates/apps/mcp/__tests__/http-transport.test.ts +291 -2
  52. package/templates/apps/mcp/__tests__/index.test.ts +86 -47
  53. package/templates/apps/mcp/__tests__/lib/content-adapter.test.ts +5 -6
  54. package/templates/apps/mcp/__tests__/lib/content-root.test.ts +93 -0
  55. package/templates/apps/mcp/__tests__/request_callback.test.ts +69 -7
  56. package/templates/apps/mcp/__tests__/server.test.ts +63 -6
  57. package/templates/apps/mcp/__tests__/submit_lead.test.ts +69 -8
  58. package/templates/apps/mcp/__tests__/subscribe_newsletter.test.ts +69 -7
  59. package/templates/apps/mcp/jest.config.cjs +3 -44
  60. package/templates/apps/mcp/src/abuse/index.ts +117 -21
  61. package/templates/apps/mcp/src/app.ts +32 -0
  62. package/templates/apps/mcp/src/boot.ts +167 -0
  63. package/templates/apps/mcp/src/http-transport.ts +132 -88
  64. package/templates/apps/mcp/src/index.ts +19 -126
  65. package/templates/apps/mcp/src/lib/audit-single-page.ts +7 -6
  66. package/templates/apps/mcp/src/lib/content-adapter.ts +34 -5
  67. package/templates/apps/mcp/src/lib/topology.generated.ts +3 -0
  68. package/templates/apps/mcp/src/request-context.ts +52 -0
  69. package/templates/apps/mcp/src/server.ts +10 -2
  70. package/templates/apps/mcp/src/serverless-app.ts +88 -0
  71. package/templates/apps/mcp/src/tools/capture_lead.ts +9 -1
  72. package/templates/apps/mcp/src/tools/get_business_hours.ts +6 -5
  73. package/templates/apps/mcp/src/tools/get_faq.ts +6 -5
  74. package/templates/apps/mcp/src/tools/get_locations.ts +6 -5
  75. package/templates/apps/mcp/src/tools/get_offerings.ts +6 -5
  76. package/templates/apps/mcp/src/tools/get_pricing.ts +6 -5
  77. package/templates/apps/mcp/src/tools/get_site_info.ts +6 -5
  78. package/templates/apps/mcp/src/tools/list_pages.ts +8 -7
  79. package/templates/apps/mcp/src/tools/read_content.ts +7 -7
  80. package/templates/apps/mcp/src/tools/request_callback.ts +9 -1
  81. package/templates/apps/mcp/src/tools/search_content.ts +6 -5
  82. package/templates/apps/mcp/src/tools/subscribe_newsletter.ts +9 -1
  83. package/templates/apps/mcp/tsconfig.json +2 -0
  84. package/templates/apps/web/LICENSE +6 -5
  85. package/templates/apps/web/NOTICE +2 -0
  86. package/templates/apps/web/app/.well-known/ai-plugin.json/route.ts +3 -3
  87. package/templates/apps/web/app/.well-known/mcp.json/build-manifest.ts +16 -4
  88. package/templates/apps/web/app/.well-known/mcp.json/route.ts +3 -0
  89. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/billing.test.tsx +288 -0
  90. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/general.test.tsx +568 -0
  91. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/hub-mode.test.tsx +272 -42
  92. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/item.test.tsx +11 -13
  93. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/layout.test.tsx +115 -16
  94. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/new-menu.test.tsx +305 -0
  95. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/new-popups.test.tsx +82 -0
  96. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/notifications.test.tsx +126 -0
  97. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/page.test.tsx +163 -72
  98. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/popups.test.tsx +451 -0
  99. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/security.test.tsx +139 -0
  100. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/settings.test.tsx +20 -390
  101. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/support.test.tsx +16 -11
  102. package/templates/apps/web/app/[locale]/(authed)/account/account-data.ts +1 -1
  103. package/templates/apps/web/app/[locale]/(authed)/account/account-frame.tsx +114 -50
  104. package/templates/apps/web/app/[locale]/(authed)/account/actions.ts +25 -32
  105. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/[pieceId]/page.tsx +253 -0
  106. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/[pieceId]/review-form.tsx +145 -0
  107. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/[pieceId]/versions/[version]/file/route.ts +100 -0
  108. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/__tests__/file-route.test.ts +179 -0
  109. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/__tests__/page.test.tsx +514 -0
  110. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/__tests__/review.test.tsx +288 -0
  111. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/artifact-actions.ts +123 -0
  112. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/artifact-data.ts +82 -0
  113. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/page.tsx +177 -0
  114. package/templates/apps/web/app/[locale]/(authed)/account/billing/page.tsx +172 -0
  115. package/templates/apps/web/app/[locale]/(authed)/account/billing-source.ts +147 -0
  116. package/templates/apps/web/app/[locale]/(authed)/account/components/request-quote.tsx +229 -0
  117. package/templates/apps/web/app/[locale]/(authed)/account/components/schedule-service.tsx +276 -0
  118. package/templates/apps/web/app/[locale]/(authed)/account/components/send-message.tsx +128 -0
  119. package/templates/apps/web/app/[locale]/(authed)/account/general/billing-anchor.tsx +27 -0
  120. package/templates/apps/web/app/[locale]/(authed)/account/general/deletion-request.tsx +132 -0
  121. package/templates/apps/web/app/[locale]/(authed)/account/general/page.tsx +131 -0
  122. package/templates/apps/web/app/[locale]/(authed)/account/general/profile-form.tsx +104 -0
  123. package/templates/apps/web/app/[locale]/(authed)/account/general/profile-source.ts +73 -0
  124. package/templates/apps/web/app/[locale]/(authed)/account/inbox/message/[id]/file/__tests__/route.test.ts +18 -8
  125. package/templates/apps/web/app/[locale]/(authed)/account/inbox/message/[id]/file/route.ts +4 -6
  126. package/templates/apps/web/app/[locale]/(authed)/account/layout.tsx +4 -1
  127. package/templates/apps/web/app/[locale]/(authed)/account/new-actions.ts +219 -0
  128. package/templates/apps/web/app/[locale]/(authed)/account/new-menu.tsx +340 -0
  129. package/templates/apps/web/app/[locale]/(authed)/account/new-popups.tsx +107 -0
  130. package/templates/apps/web/app/[locale]/(authed)/account/notifications/page.tsx +57 -0
  131. package/templates/apps/web/app/[locale]/(authed)/account/page.tsx +85 -26
  132. package/templates/apps/web/app/[locale]/(authed)/account/profile-actions.ts +116 -0
  133. package/templates/apps/web/app/[locale]/(authed)/account/security/page.tsx +80 -0
  134. package/templates/apps/web/app/[locale]/(authed)/account/settings/page.tsx +13 -354
  135. package/templates/apps/web/app/[locale]/(authed)/account/settings-frame.tsx +108 -0
  136. package/templates/apps/web/app/[locale]/(authed)/account/sign-in-method.ts +37 -0
  137. package/templates/apps/web/app/[locale]/(authed)/account/support-actions.ts +9 -10
  138. package/templates/apps/web/app/[locale]/layout.tsx +23 -4
  139. package/templates/apps/web/app/api/auth/hub/__tests__/continuation.test.ts +143 -0
  140. package/templates/apps/web/app/api/auth/hub/authorize/__tests__/route.test.ts +62 -10
  141. package/templates/apps/web/app/api/auth/hub/authorize/route.ts +22 -7
  142. package/templates/apps/web/app/api/auth/hub/continuation.ts +73 -0
  143. package/templates/apps/web/app/api/auth/hub/continue/[ref]/__tests__/route.test.ts +188 -0
  144. package/templates/apps/web/app/api/auth/hub/continue/[ref]/route.ts +53 -0
  145. package/templates/apps/web/app/robots.txt/route.ts +10 -4
  146. package/templates/apps/web/auth.ts +5 -1
  147. package/templates/apps/web/lib/__tests__/account-config.test.ts +258 -46
  148. package/templates/apps/web/lib/__tests__/site-brand.test.ts +42 -0
  149. package/templates/apps/web/lib/account-config.ts +188 -52
  150. package/templates/apps/web/lib/hub-session/__tests__/hub-session.test.ts +143 -0
  151. package/templates/apps/web/lib/hub-session/index.ts +1 -0
  152. package/templates/apps/web/lib/hub-session/reseal.ts +90 -0
  153. package/templates/apps/web/lib/hub-session/seal.ts +13 -9
  154. package/templates/apps/web/lib/site-brand.tsx +22 -6
  155. package/templates/apps/web/lib/topology.generated.ts +27 -0
  156. package/templates/apps/web/messages/en.json +156 -35
  157. package/templates/database/CHANGELOG.md +21 -0
  158. package/templates/database/LICENSE +6 -5
  159. package/templates/database/NOTICE +2 -0
  160. package/templates/database/README.md +1 -1
  161. package/templates/database/__tests__/member-area.db.test.ts +15 -3
  162. package/templates/database/__tests__/member-contract-migration.test.ts +85 -0
  163. package/templates/database/__tests__/member-contract.db.test.ts +413 -0
  164. package/templates/database/__tests__/seed.test.ts +54 -2
  165. package/templates/database/inbox/schema.prisma +90 -15
  166. package/templates/database/migrations/20261012120000_member_contract/migration.sql +192 -0
  167. package/templates/database/migrations/20261013120000_lead_spoke_checkout/migration.sql +20 -0
  168. package/templates/database/package.json +3 -2
  169. package/templates/database/seed.ts +34 -2
  170. package/versions.json +36 -36
  171. package/templates/apps/api/src/__tests__/content-write-production-boot.test.ts +0 -104
  172. package/templates/apps/api/src/__tests__/cors.test.ts +0 -276
  173. package/templates/apps/api/src/__tests__/module-exclusion.test.ts +0 -279
  174. package/templates/apps/api/src/__tests__/openapi-keyless-hub.test.ts +0 -122
  175. package/templates/apps/api/src/__tests__/review-surface-registration.test.ts +0 -167
  176. package/templates/apps/api/src/__tests__/root-modules.test.ts +0 -175
  177. package/templates/apps/api/src/__tests__/schedule-forwarded-rate-limit.test.ts +0 -117
  178. package/templates/apps/api/src/__tests__/server.test.ts +0 -591
  179. package/templates/apps/api/src/__tests__/workspace-module-registration.test.ts +0 -175
  180. package/templates/apps/api/src/openapi/__tests__/surface-drift.test.ts +0 -293
  181. package/templates/apps/api/src/routes/leads/__tests__/index.test.ts +0 -1620
  182. package/templates/apps/api/src/routes/project-listings/__tests__/directory.test.ts +0 -528
  183. package/templates/apps/api/src/routes/workspaces/__tests__/inbox-wire-schemas.test.ts +0 -198
  184. package/templates/apps/api/src/services/__tests__/aeo-score.test.ts +0 -652
  185. package/templates/apps/api/src/services/__tests__/lead-promotion.test.ts +0 -408
  186. package/templates/apps/api/src/services/__tests__/leads-inbox.test.ts +0 -476
  187. package/templates/apps/mcp/__tests__/audit.test.ts +0 -346
  188. package/templates/apps/mcp/__tests__/parity.test.ts +0 -325
  189. package/templates/apps/mcp/__tests__/workspace-surface.test.ts +0 -364
  190. package/templates/apps/web/app/[locale]/(authed)/account/settings/color-mode.tsx +0 -68
  191. package/templates/apps/web/app/[locale]/(authed)/account/settings/deletion-request.tsx +0 -55
  192. package/templates/apps/web/app/[locale]/(authed)/account/settings/name-form.tsx +0 -118
  193. package/templates/database/__tests__/build.test.ts +0 -131
@@ -7,17 +7,27 @@
7
7
  * 3. API 400 → { ok: false, error: { kind: 'api_error', status: 400 } }
8
8
  * 4. API 503 → { ok: false, error: { kind: 'api_error', status: 503 } }
9
9
  * 5. API 429 → { ok: false, error: { kind: 'api_error', status: 429 } }
10
+ * 6. #8073 — forwards the trusted caller address + AILK_VISITOR_FORWARD_KEY
11
+ * as the two visitor-forwarding headers only when both are present
10
12
  */
11
13
 
12
14
  import { ailkSubscribeNewsletter } from "../src/tools/subscribe_newsletter.js";
13
-
14
- jest.mock("@working-theory/api-client", () => ({
15
- apiClient: {
16
- leads: {
17
- subscribe: jest.fn(),
15
+ import { trustedCallerAddress } from "../src/request-context.js";
16
+
17
+ // Everything but `apiClient.leads.subscribe` stays the ACTUAL
18
+ // implementation — in particular `visitorForwardHeaders`, which
19
+ // `request-context.ts` (imported above, for `trustedCallerAddress`) reads
20
+ // for real.
21
+ jest.mock("@working-theory/api-client", () => {
22
+ const actual = jest.requireActual("@working-theory/api-client");
23
+ return {
24
+ ...actual,
25
+ apiClient: {
26
+ ...actual.apiClient,
27
+ leads: { ...actual.apiClient.leads, subscribe: jest.fn() },
18
28
  },
19
- },
20
- }));
29
+ };
30
+ });
21
31
 
22
32
 
23
33
  const { apiClient } = require("@working-theory/api-client") as {
@@ -159,3 +169,55 @@ describe("ailkSubscribeNewsletter — siteId override", () => {
159
169
  expect(call.siteId).toBe("site-abc");
160
170
  });
161
171
  });
172
+
173
+ describe("ailkSubscribeNewsletter — visitor-forwarding headers (#8073)", () => {
174
+ afterEach(() => {
175
+ delete process.env.AILK_VISITOR_FORWARD_KEY;
176
+ });
177
+
178
+ it("calls api-client with exactly one argument when there is no trusted address", async () => {
179
+ apiClient.leads.subscribe.mockResolvedValueOnce({
180
+ ok: true,
181
+ body: { id: "subscr_00000000-0000-7000-8000-0000000000e1", persisted: "db" },
182
+ });
183
+ process.env.AILK_VISITOR_FORWARD_KEY = "spoke-key";
184
+
185
+ await ailkSubscribeNewsletter(VALID_INPUT);
186
+
187
+ expect(apiClient.leads.subscribe.mock.calls[0]).toHaveLength(1);
188
+ });
189
+
190
+ it("forwards the trusted address and the forward key as the two visitor headers", async () => {
191
+ apiClient.leads.subscribe.mockResolvedValueOnce({
192
+ ok: true,
193
+ body: { id: "subscr_00000000-0000-7000-8000-0000000000e2", persisted: "db" },
194
+ });
195
+ process.env.AILK_VISITOR_FORWARD_KEY = "spoke-key";
196
+
197
+ await trustedCallerAddress.run("203.0.113.9", () =>
198
+ ailkSubscribeNewsletter(VALID_INPUT),
199
+ );
200
+
201
+ const init = apiClient.leads.subscribe.mock.calls[0][1] as
202
+ | { headers?: Record<string, string> }
203
+ | undefined;
204
+ expect(init?.headers).toEqual({
205
+ "x-ailk-visitor-ip": "203.0.113.9",
206
+ "x-ailk-visitor-forward-key": "spoke-key",
207
+ });
208
+ });
209
+
210
+ it("sends no headers when there is a trusted address but no forward key", async () => {
211
+ apiClient.leads.subscribe.mockResolvedValueOnce({
212
+ ok: true,
213
+ body: { id: "subscr_00000000-0000-7000-8000-0000000000e3", persisted: "db" },
214
+ });
215
+ delete process.env.AILK_VISITOR_FORWARD_KEY;
216
+
217
+ await trustedCallerAddress.run("203.0.113.9", () =>
218
+ ailkSubscribeNewsletter(VALID_INPUT),
219
+ );
220
+
221
+ expect(apiClient.leads.subscribe.mock.calls[0]).toHaveLength(1);
222
+ });
223
+ });
@@ -12,16 +12,8 @@ module.exports = {
12
12
  testMatch: ['**/__tests__/**/*.test.ts'],
13
13
  moduleFileExtensions: ['ts', 'js', 'json'],
14
14
  moduleNameMapper: {
15
- // Mock server-only in Jest environments — the package throws by design
16
- // outside Next.js. The real guard runs in production Next.js builds.
17
- '^server-only$': '<rootDir>/../../__mocks__/server-only.ts',
18
- // Map workspace packages to their TypeScript source so ts-jest compiles them
19
- // directly (the published dist is ESM, which Jest's CJS preset can't load).
20
- '^@working-theory/aeo$': '<rootDir>/../../packages/aeo/src/index.ts',
21
- '^@working-theory/common$': '<rootDir>/../../packages/common/src/index.ts',
22
- '^@working-theory/aeo/(.*)$': '<rootDir>/../../packages/aeo/src/$1',
23
- '^@working-theory/content-adapters$': '<rootDir>/../../packages/content-adapters/src/index.ts',
24
- '^@working-theory/content-adapters/(.*)$': '<rootDir>/../../packages/content-adapters/src/$1',
15
+ // @working-theory/* resolve from the installed packages; their ESM
16
+ // dist is converted by the transform below.
25
17
  // The constants + one-workspace predicate subpath only (#5876 spec D11) —
26
18
  // no @prisma/client import, so ts-jest compiles it directly like every
27
19
  // other workspace mapping below. The database/dist/ build is empty in a
@@ -29,23 +21,11 @@ module.exports = {
29
21
  // can't load. The CLIENT root (`@working-theory/database`) stays
30
22
  // deliberately UNMAPPED — see apps/mcp/src/lib/prisma.ts.
31
23
  '^@working-theory/database/tenancy$': '<rootDir>/../../database/tenancy.ts',
32
- // tenancy.ts's isSentinel import (above) is a VALUE import, so every
33
- // suite that loads the tenancy subpath transitively loads this one too
34
- // — mirrors apps/api/jest.config.cjs's identical mapping.
35
- '^@working-theory/ids$': '<rootDir>/../../packages/ids/src/index.ts',
36
- '^@working-theory/license$': '<rootDir>/../../packages/license/src/index.ts',
37
- '^@working-theory/metadata$': '<rootDir>/../../packages/metadata/src/index.ts',
38
- '^@working-theory/schema$': '<rootDir>/../../packages/schema/src/index.ts',
39
- '^@working-theory/schema/(.*)$': '<rootDir>/../../packages/schema/src/$1',
40
- '^@working-theory/schema-validator$': '<rootDir>/../../packages/schema-validator/src/index.ts',
41
- '^@working-theory/schema-pack-registry$': '<rootDir>/../../packages/schema-pack-registry/src/index.ts',
42
- '^@working-theory/validation$': '<rootDir>/../../packages/validation/src/index.ts',
43
- '^@working-theory/api-client$': '<rootDir>/../../packages/api-client/src/index.ts',
44
24
  '^(\\.{1,2}/.*)\\.js$': '$1',
45
25
  },
46
26
  collectCoverageFrom: ['src/**/*.ts', '!src/**/*.d.ts'],
47
27
  transformIgnorePatterns: [
48
- '/node_modules/(?!(\\.pnpm/)?jose@?[^/]*?(/|$))',
28
+ '/node_modules/(?!(\\.pnpm/)?(jose@?[^/]*?|cookie@?[^/]*?|@vercel(?:\\+analytics@[^/]*?|/analytics)|@working-theory(?:\\+[^/]*?@?[^/]*?|/[^/]+))(/|$))',
49
29
  ],
50
30
  transform: {
51
31
  '^.+\\.(tsx?|jsx?|mjs)$': [
@@ -61,27 +41,6 @@ module.exports = {
61
41
  skipLibCheck: true,
62
42
  ignoreDeprecations: '6.0',
63
43
  allowJs: true,
64
- // paths must mirror moduleNameMapper above so ts-jest's TypeScript
65
- // type-checker can resolve workspace package imports during compile.
66
- // Jest's moduleNameMapper handles runtime resolution; TS uses paths.
67
- baseUrl: '.',
68
- paths: {
69
- '@working-theory/aeo': ['../../packages/aeo/src/index.ts'],
70
- '@working-theory/common': ['../../packages/common/src/index.ts'],
71
- '@working-theory/aeo/*': ['../../packages/aeo/src/*'],
72
- '@working-theory/api-client': ['../../packages/api-client/src/index.ts'],
73
- '@working-theory/content-adapters': ['../../packages/content-adapters/src/index.ts'],
74
- '@working-theory/content-adapters/*': ['../../packages/content-adapters/src/*'],
75
- '@working-theory/database/tenancy': ['../../database/tenancy.ts'],
76
- '@working-theory/ids': ['../../packages/ids/src/index.ts'],
77
- '@working-theory/license': ['../../packages/license/src/index.ts'],
78
- '@working-theory/metadata': ['../../packages/metadata/src/index.ts'],
79
- '@working-theory/schema': ['../../packages/schema/src/index.ts'],
80
- '@working-theory/schema/*': ['../../packages/schema/src/*'],
81
- '@working-theory/schema-validator': ['../../packages/schema-validator/src/index.ts'],
82
- '@working-theory/schema-pack-registry': ['../../packages/schema-pack-registry/src/index.ts'],
83
- '@working-theory/validation': ['../../packages/validation/src/index.ts'],
84
- },
85
44
  },
86
45
  // Suppress "import.meta only allowed in ESM modules" — source is ESM,
87
46
  // but ts-jest compiles to CommonJS for Jest. The import.meta fallback
@@ -2,16 +2,18 @@
2
2
  * Abuse rule orchestrator for MCP write tools.
3
3
  *
4
4
  * Runs all in-process heuristics for the anonymous write tools:
5
- * capture_lead, subscribe_newsletter, request_callback, and — since #5971 —
6
- * start_purchase.
5
+ * capture_lead, subscribe_newsletter, request_callback, start_purchase
6
+ * (#5971), and — since #8071 — create_booking and submit_flow_step.
7
7
  *
8
8
  * Rules applied (in order):
9
9
  * 1. User-Agent deny list (applies to all write tools)
10
10
  * 2. Honeypot field check (applies to all write tools)
11
- * 3. Email format validation (capture_lead, subscribe_newsletter)
12
- * 4. Per-IP daily cap (capture_lead and start_purchase, each on its OWN
13
- * tracker — sharing one would let purchase attempts consume the lead
14
- * budget and vice versa, a silent cross-tool denial of service)
11
+ * 3. Email format validation (capture_lead, subscribe_newsletter, and
12
+ * create_booking's attendee.email)
13
+ * 4. Per-IP daily cap (capture_lead, start_purchase, create_booking and
14
+ * submit_flow_step, each on its OWN tracker — sharing one would let one
15
+ * tool's calls consume another's budget, a silent cross-tool denial of
16
+ * service)
15
17
  *
16
18
  * The paid layer (lead-routing.ts) extends with real abuse-protection
17
19
  * services. OSS gets basic heuristics that stop obvious bots.
@@ -24,11 +26,40 @@ import { isValidEmail } from "./email-validator.js";
24
26
  import { isHoneypotTripped } from "./honeypot.js";
25
27
  import { buildDenyList, isUserAgentBlocked } from "./user-agent-deny.js";
26
28
 
27
- /** Tools that require email format validation on their input. */
28
- const EMAIL_VALIDATED_TOOLS = new Set(["capture_lead", "subscribe_newsletter"]);
29
+ /**
30
+ * Tools that require email format validation on their input, each mapped to
31
+ * where the email sits in it: top level for the lead tools, `attendee.email`
32
+ * for create_booking (#8071 D3). submit_flow_step has no fixed email field —
33
+ * its `values` is a free record the hub's flow engine validates.
34
+ */
35
+ const EMAIL_VALIDATED_TOOLS = new Map<string, readonly string[]>([
36
+ ["capture_lead", ["email"]],
37
+ ["subscribe_newsletter", ["email"]],
38
+ ["create_booking", ["attendee", "email"]],
39
+ ]);
40
+
41
+ /**
42
+ * The value at `path` in `input`, or undefined when any step is not a plain
43
+ * object — a `null`, string or array `attendee` reads as a missing email, so a
44
+ * malformed body can never throw out of the guard (#8071 SEC-13).
45
+ */
46
+ function valueAt(input: unknown, path: readonly string[]): unknown {
47
+ let value = input;
48
+ for (const key of path) {
49
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
50
+ return undefined;
51
+ }
52
+ value = (value as Record<string, unknown>)[key];
53
+ }
54
+ return value;
55
+ }
29
56
 
30
57
  /** The per-tool daily-cap budgets, keyed by MCP tool name. */
31
- type DailyCapKey = "captureLead" | "startPurchase";
58
+ type DailyCapKey =
59
+ | "captureLead"
60
+ | "startPurchase"
61
+ | "createBooking"
62
+ | "submitFlowStep";
32
63
 
33
64
  /**
34
65
  * The typed reason codes an {@link AbuseResult} refusal can carry.
@@ -56,8 +87,9 @@ export type AbuseReasonCode =
56
87
  /**
57
88
  * Tools that apply a per-IP daily cap, each mapped to the tracker that budgets
58
89
  * it and the refusal reason it answers with. One tracker per entry — never
59
- * shared across tools, since a shared budget would let purchase attempts
60
- * consume the lead allowance and vice versa.
90
+ * shared across tools, since a shared budget would let one tool's calls
91
+ * consume another's allowance (purchase attempts the lead budget, flow steps
92
+ * the lead budget they could otherwise mint Leads past).
61
93
  *
62
94
  * The reason strings here are prose for the caller and nothing more: every
63
95
  * entry refuses with {@link AbuseReasonCode.DAILY_CAP_REACHED}, and that code
@@ -81,6 +113,20 @@ const DAILY_CAPPED_TOOLS = new Map<
81
113
  reason: "daily cap reached for start_purchase from this IP",
82
114
  },
83
115
  ],
116
+ [
117
+ "create_booking",
118
+ {
119
+ tracker: "createBooking",
120
+ reason: "daily cap reached for create_booking from this IP",
121
+ },
122
+ ],
123
+ [
124
+ "submit_flow_step",
125
+ {
126
+ tracker: "submitFlowStep",
127
+ reason: "daily cap reached for submit_flow_step from this IP",
128
+ },
129
+ ],
84
130
  ]);
85
131
 
86
132
  export interface AbuseConfig {
@@ -93,6 +139,18 @@ export interface AbuseConfig {
93
139
  * keep compiling; omitted falls back to the default.
94
140
  */
95
141
  startPurchaseDailyCapPerIp?: number;
142
+ /**
143
+ * Per-IP daily cap for create_booking (#8071). Default 20, as for
144
+ * start_purchase: each call creates a real calendar event and emails the
145
+ * attendee an invite. Optional; omitted falls back to the default.
146
+ */
147
+ createBookingDailyCapPerIp?: number;
148
+ /**
149
+ * Per-IP daily cap for submit_flow_step (#8071). Default 50, equal to
150
+ * capture_lead's and no higher: a one-step flow creates a Lead in one call.
151
+ * Optional; omitted falls back to the default.
152
+ */
153
+ submitFlowStepDailyCapPerIp?: number;
96
154
  /** Comma-separated extra UA substrings to block. */
97
155
  blockedUserAgents: string;
98
156
  }
@@ -103,6 +161,12 @@ export const DEFAULT_START_PURCHASE_DAILY_CAP = 20;
103
161
  /** Default per-IP daily cap for capture_lead when none is configured. */
104
162
  export const DEFAULT_CAPTURE_LEAD_DAILY_CAP = 50;
105
163
 
164
+ /** Default per-IP daily cap for create_booking when none is configured. */
165
+ export const DEFAULT_CREATE_BOOKING_DAILY_CAP = 20;
166
+
167
+ /** Default per-IP daily cap for submit_flow_step when none is configured. */
168
+ export const DEFAULT_SUBMIT_FLOW_STEP_DAILY_CAP = 50;
169
+
106
170
  /**
107
171
  * Reads a positive-integer env var, falling back to `fallback` for anything
108
172
  * that is not one.
@@ -162,6 +226,18 @@ export class AbuseGuard {
162
226
  DEFAULT_START_PURCHASE_DAILY_CAP,
163
227
  ),
164
228
  ),
229
+ createBooking: new DailyCapTracker(
230
+ usableCap(
231
+ config.createBookingDailyCapPerIp,
232
+ DEFAULT_CREATE_BOOKING_DAILY_CAP,
233
+ ),
234
+ ),
235
+ submitFlowStep: new DailyCapTracker(
236
+ usableCap(
237
+ config.submitFlowStepDailyCapPerIp,
238
+ DEFAULT_SUBMIT_FLOW_STEP_DAILY_CAP,
239
+ ),
240
+ ),
165
241
  };
166
242
  }
167
243
 
@@ -198,10 +274,12 @@ export class AbuseGuard {
198
274
  };
199
275
  }
200
276
 
201
- // Rule 3: Email format validation
202
- if (EMAIL_VALIDATED_TOOLS.has(toolName)) {
203
- const rec = input as Record<string, unknown>;
204
- const email = rec["email"];
277
+ // Rule 3: Email format validation, at the tool's own email path. A
278
+ // missing or non-string email passes — the handler's Zod schema is the
279
+ // authority on required fields.
280
+ const emailPath = EMAIL_VALIDATED_TOOLS.get(toolName);
281
+ if (emailPath !== undefined) {
282
+ const email = valueAt(input, emailPath);
205
283
  if (typeof email === "string" && !isValidEmail(email)) {
206
284
  return {
207
285
  allowed: false,
@@ -227,12 +305,16 @@ export class AbuseGuard {
227
305
  }
228
306
 
229
307
  /**
230
- * Convenience function for constructing an AbuseGuard from env vars.
231
- * Reads MCP_ABUSE_CAPTURE_LEAD_DAILY_CAP,
232
- * MCP_ABUSE_START_PURCHASE_DAILY_CAP and MCP_ABUSE_BLOCKED_USER_AGENTS.
308
+ * The abuse configuration, read from the environment. The one reader of the
309
+ * MCP_ABUSE_* variables: both entries reach it through
310
+ * `httpTransportConfigFromEnv()` (`src/boot.ts`), and
311
+ * {@link createAbuseGuardFromEnv} wraps it, so a new cap is added here once.
312
+ *
313
+ * Every cap goes through {@link readPositiveIntEnv}: a blank, zero or
314
+ * non-numeric value yields its default, never an unlimited cap.
233
315
  */
234
- export function createAbuseGuardFromEnv(): AbuseGuard {
235
- return new AbuseGuard({
316
+ export function abuseConfigFromEnv(): Required<AbuseConfig> {
317
+ return {
236
318
  captureLeadDailyCapPerIp: readPositiveIntEnv(
237
319
  "MCP_ABUSE_CAPTURE_LEAD_DAILY_CAP",
238
320
  DEFAULT_CAPTURE_LEAD_DAILY_CAP,
@@ -241,6 +323,20 @@ export function createAbuseGuardFromEnv(): AbuseGuard {
241
323
  "MCP_ABUSE_START_PURCHASE_DAILY_CAP",
242
324
  DEFAULT_START_PURCHASE_DAILY_CAP,
243
325
  ),
326
+ createBookingDailyCapPerIp: readPositiveIntEnv(
327
+ "MCP_ABUSE_CREATE_BOOKING_DAILY_CAP",
328
+ DEFAULT_CREATE_BOOKING_DAILY_CAP,
329
+ ),
330
+ submitFlowStepDailyCapPerIp: readPositiveIntEnv(
331
+ "MCP_ABUSE_SUBMIT_FLOW_STEP_DAILY_CAP",
332
+ DEFAULT_SUBMIT_FLOW_STEP_DAILY_CAP,
333
+ ),
334
+ // A literal read, so create-ailk's declared-env scan finds it (#7874).
244
335
  blockedUserAgents: process.env["MCP_ABUSE_BLOCKED_USER_AGENTS"] ?? "",
245
- });
336
+ };
337
+ }
338
+
339
+ /** An AbuseGuard built from {@link abuseConfigFromEnv}. */
340
+ export function createAbuseGuardFromEnv(): AbuseGuard {
341
+ return new AbuseGuard(abuseConfigFromEnv());
246
342
  }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * @working-theory/mcp — the Vercel entry (#8070 D2).
3
+ *
4
+ * A Vercel project whose root directory is `apps/mcp` detects this file
5
+ * (`src/app` precedes `src/index` in its Node-backend search, and the chosen
6
+ * file must import the framework), builds it, and calls the default export —
7
+ * the `serverlessHandler(app)` request function, which Vercel's Node runtime
8
+ * accepts where a bare Fastify instance is not a shape it runs.
9
+ * It never listens; the module-level `await` runs once per instance, so a
10
+ * warm instance reuses the booted app.
11
+ *
12
+ * Run locally, use `src/index.ts` (stdio, or HTTP on MCP_HTTP_PORT) instead.
13
+ * Everything testable lives in `serverless-app.ts`.
14
+ */
15
+
16
+ import Fastify from "fastify";
17
+
18
+ import { bootMcp } from "./boot.js";
19
+ import {
20
+ configureServerlessApp,
21
+ SERVERLESS_FASTIFY_OPTIONS,
22
+ serverlessHandler,
23
+ } from "./serverless-app.js";
24
+
25
+ /** Read statically by Vercel's Node builder; caps one request (S8070-03). */
26
+ export const config = { maxDuration: 30 };
27
+
28
+ await bootMcp();
29
+ const app = Fastify(SERVERLESS_FASTIFY_OPTIONS);
30
+ await configureServerlessApp(app);
31
+ await app.ready();
32
+ export default serverlessHandler(app);
@@ -0,0 +1,167 @@
1
+ /**
2
+ * The boot sequence and the HTTP env→config reader both entrypoints share
3
+ * (#8070 D1, D2).
4
+ *
5
+ * `src/index.ts` (stdio, or HTTP on `MCP_HTTP_PORT`) and `src/app.ts` (the
6
+ * Vercel entry) each call {@link bootMcp} before they build a transport, and
7
+ * read the HTTP configuration through {@link httpTransportConfigFromEnv} and
8
+ * {@link readStatelessEnv}. One copy of each, so the two entries cannot drift.
9
+ *
10
+ * Nothing here loads Fastify: the HTTP transport's config type is imported as
11
+ * a type only, so the stdio entry still never loads the HTTP stack.
12
+ */
13
+
14
+ import { abuseConfigFromEnv, readPositiveIntEnv } from "./abuse/index.js";
15
+ import type { HttpTransportConfig } from "./http-transport.js";
16
+ import {
17
+ initMcpCommerceClaim,
18
+ startMcpClaimRefresh,
19
+ } from "./lib/commerce-claim.js";
20
+ import {
21
+ initPublicWorkspace,
22
+ registerLicenseKeyStore,
23
+ } from "./lib/topology.generated.js";
24
+
25
+ /**
26
+ * Runs the boot sequence, in order: the workspace resolution, the licence-key
27
+ * store, the commerce claim, the claim re-read loop and the one-release
28
+ * licence warning. Each step that can fail is guarded so one failure never
29
+ * takes the other tools down.
30
+ */
31
+ export async function bootMcp(): Promise<void> {
32
+ // Resolves the MCP server's own workspace ONCE, before any transport is
33
+ // built — a no-op unless CONTENT_ADAPTER=database (#5876 spec D4/D6).
34
+ // This is the one `await` that covers every transport:
35
+ // `getMcpContentAdapter()` (content-adapter.ts) stays synchronous and reads
36
+ // the memoised result.
37
+ //
38
+ // A REJECTION here (a transient DB error — unreachable at boot, a migration
39
+ // in progress, a bad DATABASE_URL) is caught rather than left to crash the
40
+ // process: every OTHER tool (lead capture, scheduling, …) has nothing to do
41
+ // with the content adapter and must keep serving. The module's un-resolved
42
+ // `{ kind: "not-required" }` state is left in place on a caught failure —
43
+ // the SAME fail-closed shape an ambiguous workspace count already produces
44
+ // (D5) — so content tools serve their empty/not-found shape rather than the
45
+ // whole server going dark over one adapter's connectivity.
46
+ try {
47
+ await initPublicWorkspace();
48
+ } catch (err) {
49
+ console.error(
50
+ "[mcp] initPublicWorkspace() failed — content tools will serve their " +
51
+ "fail-closed empty shape under CONTENT_ADAPTER=database until this " +
52
+ "resolves; every other tool is unaffected:",
53
+ err,
54
+ );
55
+ }
56
+
57
+ // Registers the renewed licence key's durable home (#6677 DD-6) BEFORE the
58
+ // commerce claim below memoises the licence: with a database, the key a
59
+ // sibling app renewed lives in one SiteSetting row, and the claim must read
60
+ // it. Never throws; without DATABASE_URL the file store stays in place.
61
+ await registerLicenseKeyStore();
62
+
63
+ // Resolves the deployment's `commerce` add-on claim at boot, before any
64
+ // transport is built — the sibling of the workspace resolution above and
65
+ // the same #5876 idiom (#5971 spec D2). Without this await the memoised
66
+ // claim is never resolved and `start_purchase` is invisible on a KEYED
67
+ // site too. The same single licence read now also resolves the licence
68
+ // features the deployment holds, which gate the five `feature`-tagged
69
+ // tools (#7136). The re-read loop below runs every `MCP_CLAIM_REFRESH_MS`
70
+ // thereafter (#7156), so the server's origin agrees with the manifest
71
+ // route's origin response within that bound; the route answers
72
+ // `cache-control: public, max-age=86400`, so a downstream cache may serve
73
+ // an older manifest for up to 24 hours.
74
+ //
75
+ // A REJECTION is caught for the same reason: a licence read that fails
76
+ // must not take the other 19 tools down. `initMcpCommerceClaim()` already
77
+ // resolves to the fail-closed "unclaimed" internally, so this catch is
78
+ // belt-and-braces for anything thrown outside its own try.
79
+ try {
80
+ await initMcpCommerceClaim();
81
+ } catch (err) {
82
+ console.error(
83
+ "[mcp] initMcpCommerceClaim() failed — start_purchase stays unregistered " +
84
+ "(fail-closed) until this resolves; every other tool is unaffected:",
85
+ err,
86
+ );
87
+ }
88
+
89
+ // Starts the bounded re-read (#7156 spec D1), after the boot read resolves
90
+ // so the first re-read never races it. Never throws; the timer is unref'd.
91
+ startMcpClaimRefresh();
92
+
93
+ // The one-release warning cycle (#7136): once per process, whichever
94
+ // transport follows, one stderr line per tool served without its licence
95
+ // feature. After the claim resolves, or it would warn for every tool.
96
+ //
97
+ // A throw here must not stop the server (#7156 spec D2, L1) — only the call
98
+ // is guarded, not the import: if `./server.js` fails to load, every
99
+ // transport loads it again and the server could not start anyway.
100
+ const { reportUnlicensedProTools } = await import("./server.js");
101
+ try {
102
+ reportUnlicensedProTools();
103
+ } catch (err) {
104
+ console.error(
105
+ "[mcp] reportUnlicensedProTools() failed — the licence boot warning was " +
106
+ "not written; every tool is served as registered:",
107
+ err,
108
+ );
109
+ }
110
+ }
111
+
112
+ /**
113
+ * Whether the HTTP transport runs stateless, from `MCP_HTTP_STATELESS`
114
+ * (#8070 D1). Trimmed and case-insensitive: `true`/`1` → on, `false`/`0` →
115
+ * off, unset or empty → `defaultValue`. Anything else throws, so a typo fails
116
+ * the boot rather than silently picking a mode.
117
+ *
118
+ * Each entry passes its own default: `src/index.ts` passes `false` (today's
119
+ * stateful server, unchanged); the Vercel entry passes `true`, because a
120
+ * stateful transport keeps its sessions in one instance's memory and cannot
121
+ * work across the instances a serverless host runs.
122
+ */
123
+ export function readStatelessEnv(defaultValue: boolean): boolean {
124
+ // A literal read, so create-ailk's declared-env scan finds it (#7874).
125
+ const raw = process.env["MCP_HTTP_STATELESS"];
126
+ const value = (raw ?? "").trim().toLowerCase();
127
+ if (value === "") return defaultValue;
128
+ if (value === "true" || value === "1") return true;
129
+ if (value === "false" || value === "0") return false;
130
+ throw new Error(
131
+ `MCP_HTTP_STATELESS must be one of true, false, 1 or 0 (got "${raw}")`,
132
+ );
133
+ }
134
+
135
+ /**
136
+ * The HTTP transport's configuration, read from the environment as
137
+ * `src/index.ts` has always read it — with one change: the two per-minute
138
+ * rates go through {@link readPositiveIntEnv}, as the daily caps already do,
139
+ * so a blank or non-numeric value falls back to its default instead of
140
+ * yielding `NaN` and silently disabling the limit (#8070 S8070-06).
141
+ *
142
+ * Every variable is optional; the defaults are shown in
143
+ * `apps/mcp/.env.example`. Stateless mode is not read here: each entry reads
144
+ * it through {@link readStatelessEnv} with its own default.
145
+ */
146
+ export function httpTransportConfigFromEnv(): HttpTransportConfig & {
147
+ port: number;
148
+ } {
149
+ const port = parseInt(process.env["MCP_HTTP_PORT"] ?? "8080", 10);
150
+ const path = process.env["MCP_HTTP_PATH"] ?? "/mcp";
151
+ const readPerMin = readPositiveIntEnv("MCP_RATE_LIMIT_READ_PER_MIN", 60);
152
+ const writePerMin = readPositiveIntEnv("MCP_RATE_LIMIT_WRITE_PER_MIN", 10);
153
+ const writeOriginsRaw = process.env["MCP_CORS_WRITE_ALLOWED_ORIGINS"] ?? "";
154
+ const writeAllowedOrigins = writeOriginsRaw
155
+ ? writeOriginsRaw.split(",").map((o) => o.trim())
156
+ : [];
157
+ return {
158
+ port,
159
+ path,
160
+ rateLimits: { readPerMin, writePerMin },
161
+ cors: { writeAllowedOrigins },
162
+ // The MCP_ABUSE_* variables have one reader, shared with
163
+ // createAbuseGuardFromEnv (#8071); every cap falls back to its default
164
+ // on a blank or non-numeric value, never to unlimited (#5971).
165
+ abuse: abuseConfigFromEnv(),
166
+ };
167
+ }