create-ailk 0.22.0 → 0.23.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 (238) hide show
  1. package/component-catalog.json +149 -5
  2. package/component-catalog.md +7 -6
  3. package/dist/add-module.js +11 -9
  4. package/dist/add-route.d.ts +55 -1
  5. package/dist/add-route.js +294 -12
  6. package/dist/cli.js +27 -10
  7. package/dist/derive-architecture.d.ts +7 -5
  8. package/dist/derive-architecture.js +9 -32
  9. package/dist/lib/design-checks.js +4 -2
  10. package/dist/lib/env-catalog.js +0 -4
  11. package/dist/lib/npm-auth.d.ts +9 -0
  12. package/dist/lib/npm-auth.js +48 -0
  13. package/dist/lib/scaffold-render-sweep.d.ts +3 -2
  14. package/dist/lib/scaffold-render-sweep.js +5 -8
  15. package/dist/module-architecture.js +98 -10
  16. package/dist/paid-sections.d.ts +21 -2
  17. package/dist/paid-sections.js +69 -7
  18. package/dist/seed-flows.d.ts +4 -1
  19. package/dist/seed-flows.js +50 -4
  20. package/dist/spoke-checkout.d.ts +38 -35
  21. package/dist/spoke-checkout.js +66 -229
  22. package/dist/starter-grid.d.ts +0 -3
  23. package/dist/starter-grid.js +24 -14
  24. package/dist/surfaces.js +33 -12
  25. package/dist/sync-routes.d.ts +38 -1
  26. package/dist/sync-routes.js +184 -11
  27. package/dist/template-record.d.ts +1 -1
  28. package/dist/template-record.js +3 -2
  29. package/dist/update.js +10 -0
  30. package/package.json +3 -3
  31. package/site-templates/_base/content/en/NewsletterSignup/newsletter.mdx +4 -49
  32. package/site-templates/_base/content/en/Pricing/pricing.mdx +3 -21
  33. package/site-templates/marketing-site/TEMPLATE-MANIFEST.json +23 -20
  34. package/site-templates/marketing-site/TEMPLATE-MANIFEST.md +28 -14
  35. package/site-templates/marketing-site-free/TEMPLATE-MANIFEST.json +15 -39
  36. package/site-templates/marketing-site-free/TEMPLATE-MANIFEST.md +38 -34
  37. package/site-templates/marketing-site-free/content/en/NewsletterSignup/newsletter.mdx +6 -43
  38. package/site-templates/shapes/local-business-service/TEMPLATE-MANIFEST.json +14 -31
  39. package/site-templates/shapes/local-business-service/TEMPLATE-MANIFEST.md +26 -25
  40. package/site-templates/shapes/local-business-service/content/en/NewsletterSignup/newsletter.mdx +6 -43
  41. package/site-templates/shapes/organization-service/TEMPLATE-MANIFEST.json +14 -31
  42. package/site-templates/shapes/organization-service/TEMPLATE-MANIFEST.md +26 -25
  43. package/site-templates/shapes/organization-service/content/en/NewsletterSignup/newsletter.mdx +6 -43
  44. package/site-templates/shapes/person-service/TEMPLATE-MANIFEST.json +14 -31
  45. package/site-templates/shapes/person-service/TEMPLATE-MANIFEST.md +26 -25
  46. package/site-templates/shapes/person-service/content/en/NewsletterSignup/newsletter.mdx +6 -43
  47. package/templates/.env.example +9 -7
  48. package/templates/.github/workflows/ci.yml +13 -0
  49. package/templates/README.md +1 -0
  50. package/templates/_gitignore +4 -0
  51. package/templates/apps/api/.env.example +27 -0
  52. package/templates/apps/api/CLAUDE.md +77 -16
  53. package/templates/apps/api/package.json +1 -0
  54. package/templates/apps/api/src/__tests__/factories/in-memory-prisma.ts +2 -0
  55. package/templates/apps/api/src/bin/stripe-connections-rekey.ts +45 -0
  56. package/templates/apps/api/src/config/__tests__/stripe-connection-key.test.ts +185 -0
  57. package/templates/apps/api/src/config/index.ts +109 -0
  58. package/templates/apps/api/src/lib/__mocks__/prisma.ts +3 -0
  59. package/templates/apps/api/src/lib/__tests__/flow-rename-race.db.test.ts +116 -0
  60. package/templates/apps/api/src/lib/error-serializer.ts +74 -7
  61. package/templates/apps/api/src/lib/stripe.ts +74 -4
  62. package/templates/apps/api/src/lib/webhook-idempotency.ts +66 -2
  63. package/templates/apps/api/src/middleware/__tests__/rate-limit.test.ts +218 -0
  64. package/templates/apps/api/src/middleware/__tests__/write-budget.test.ts +174 -0
  65. package/templates/apps/api/src/middleware/rate-limit.ts +226 -4
  66. package/templates/apps/api/src/openapi/spec.ts +10 -7
  67. package/templates/apps/api/src/routes/billing/plan-checkout.ts +325 -0
  68. package/templates/apps/api/src/routes/checkout/__tests__/live-key.test.ts +11 -0
  69. package/templates/apps/api/src/routes/checkout/__tests__/offerings-authorization.test.ts +1300 -0
  70. package/templates/apps/api/src/routes/checkout/__tests__/session.test.ts +11 -0
  71. package/templates/apps/api/src/routes/checkout/__tests__/sessions.test.ts +49 -0
  72. package/templates/apps/api/src/routes/checkout/session.ts +57 -25
  73. package/templates/apps/api/src/routes/checkout/sessions.ts +232 -82
  74. package/templates/apps/api/src/routes/consent/__tests__/account.test.ts +5 -5
  75. package/templates/apps/api/src/routes/consent/__tests__/sign-up-rate-limit.test.ts +160 -0
  76. package/templates/apps/api/src/routes/consent/account.ts +4 -2
  77. package/templates/apps/api/src/routes/content/__tests__/get-page.test.ts +2 -2
  78. package/templates/apps/api/src/routes/content/__tests__/offerings.test.ts +731 -0
  79. package/templates/apps/api/src/routes/content/__tests__/pricing.test.ts +753 -0
  80. package/templates/apps/api/src/routes/content/__tests__/shown-offerings.test.ts +762 -0
  81. package/templates/apps/api/src/routes/content/index.ts +16 -2
  82. package/templates/apps/api/src/routes/content/offerings.ts +184 -0
  83. package/templates/apps/api/src/routes/content/pricing.ts +176 -0
  84. package/templates/apps/api/src/routes/content/shown-offerings.ts +229 -0
  85. package/templates/apps/api/src/routes/leads/index.ts +17 -14
  86. package/templates/apps/api/src/routes/webhooks/README.md +66 -0
  87. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-offerings.test.ts +814 -0
  88. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-org-billing.test.ts +80 -68
  89. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-site-filter.test.ts +5 -5
  90. package/templates/apps/api/src/routes/webhooks/__tests__/stripe.test.ts +8 -2
  91. package/templates/apps/api/src/routes/webhooks/index.ts +23 -0
  92. package/templates/apps/api/src/routes/webhooks/stripe-offerings.ts +384 -0
  93. package/templates/apps/api/src/routes/webhooks/stripe.ts +91 -17
  94. package/templates/apps/api/src/server.ts +140 -51
  95. package/templates/apps/api/src/services/__tests__/checkout-plan.test.ts +313 -0
  96. package/templates/apps/api/src/services/__tests__/deliverable-fulfillment.test.ts +51 -2
  97. package/templates/apps/api/src/services/__tests__/keyless-workspace-predicate.test.ts +234 -0
  98. package/templates/apps/api/src/services/__tests__/lead-routing.test.ts +374 -44
  99. package/templates/apps/api/src/services/__tests__/person.test.ts +232 -1
  100. package/templates/apps/api/src/services/__tests__/plan-offerings.test.ts +444 -0
  101. package/templates/apps/api/src/services/deliverable-fulfillment.ts +13 -5
  102. package/templates/apps/api/src/services/entitlements.ts +157 -1
  103. package/templates/apps/api/src/services/lead-routing.ts +113 -58
  104. package/templates/apps/api/src/services/offerings/__tests__/catalog.test.ts +295 -0
  105. package/templates/apps/api/src/services/offerings/__tests__/checkout-session-record.test.ts +268 -0
  106. package/templates/apps/api/src/services/offerings/__tests__/connection.test.ts +868 -0
  107. package/templates/apps/api/src/services/offerings/__tests__/fixtures.ts +416 -0
  108. package/templates/apps/api/src/services/offerings/__tests__/org-products.test.ts +396 -0
  109. package/templates/apps/api/src/services/offerings/__tests__/readers.test.ts +681 -0
  110. package/templates/apps/api/src/services/offerings/__tests__/source.test.ts +231 -0
  111. package/templates/apps/api/src/services/offerings/catalog.ts +308 -0
  112. package/templates/apps/api/src/services/offerings/checkout-authorization.ts +385 -0
  113. package/templates/apps/api/src/services/offerings/checkout-session-record.ts +192 -0
  114. package/templates/apps/api/src/services/offerings/connection.ts +1003 -0
  115. package/templates/apps/api/src/services/offerings/index.ts +614 -0
  116. package/templates/apps/api/src/services/offerings/source.ts +140 -0
  117. package/templates/apps/api/src/services/offerings/store.ts +150 -0
  118. package/templates/apps/api/src/services/person.ts +124 -9
  119. package/templates/apps/api/src/services/plan-offerings.ts +96 -30
  120. package/templates/apps/api/src/services/public-site-resolver.ts +19 -14
  121. package/templates/apps/mcp/CLAUDE.md +22 -14
  122. package/templates/apps/mcp/__tests__/catalog-drift.test.ts +9 -4
  123. package/templates/apps/mcp/__tests__/get_offerings.test.ts +358 -0
  124. package/templates/apps/mcp/__tests__/get_pricing.test.ts +364 -0
  125. package/templates/apps/mcp/__tests__/http-transport.test.ts +4 -4
  126. package/templates/apps/mcp/__tests__/module-exclusion.test.ts +2 -2
  127. package/templates/apps/mcp/__tests__/server.test.ts +13 -11
  128. package/templates/apps/mcp/__tests__/start_purchase.test.ts +208 -12
  129. package/templates/apps/mcp/__tests__/tools/purchase.test.ts +11 -11
  130. package/templates/apps/mcp/src/lib/shown-offerings.ts +105 -0
  131. package/templates/apps/mcp/src/server.ts +5 -0
  132. package/templates/apps/mcp/src/tools/get_offerings.ts +47 -30
  133. package/templates/apps/mcp/src/tools/get_pricing.ts +40 -40
  134. package/templates/apps/mcp/src/tools/purchase.ts +30 -2
  135. package/templates/apps/mcp/src/workspace-server.ts +15 -0
  136. package/templates/apps/web/.env.example +10 -31
  137. package/templates/apps/web/CLAUDE.md +315 -42
  138. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/agreements-prompt.test.tsx +3 -3
  139. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/layout.test.tsx +3 -3
  140. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/privacy.test.tsx +3 -3
  141. package/templates/apps/web/app/[locale]/careers/[slug]/[action]/page.tsx +189 -0
  142. package/templates/apps/web/app/[locale]/careers/[slug]/apply.actions.ts +4 -2
  143. package/templates/apps/web/app/[locale]/careers/[slug]/job-application-form.ts +8 -3
  144. package/templates/apps/web/app/[locale]/careers/[slug]/page.tsx +22 -144
  145. package/templates/apps/web/app/[locale]/careers/__tests__/apply.actions.test.ts +9 -0
  146. package/templates/apps/web/app/[locale]/careers/__tests__/careers-hub.test.tsx +172 -0
  147. package/templates/apps/web/app/[locale]/careers/__tests__/careers-set.test.tsx +149 -0
  148. package/templates/apps/web/app/[locale]/careers/__tests__/job-application-form.test.ts +22 -24
  149. package/templates/apps/web/app/[locale]/careers/__tests__/job-apply-page.test.tsx +140 -66
  150. package/templates/apps/web/app/[locale]/careers/__tests__/page-renderer-migration.test.tsx +57 -22
  151. package/templates/apps/web/app/[locale]/careers/page.tsx +129 -5
  152. package/templates/apps/web/app/[locale]/contact/__tests__/contact-magnet-page.test.tsx +119 -11
  153. package/templates/apps/web/app/[locale]/contact/__tests__/contact.actions.test.ts +28 -5
  154. package/templates/apps/web/app/[locale]/contact/contact.actions.ts +6 -2
  155. package/templates/apps/web/app/[locale]/contact/page.tsx +99 -92
  156. package/templates/apps/web/app/[locale]/flows/[slug]/FlowStepperClient.tsx +237 -5
  157. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/FlowStepperClient.count.test.tsx +43 -0
  158. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/FlowStepperClient.deliverable.test.tsx +200 -0
  159. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/FlowStepperClient.ending.test.tsx +197 -0
  160. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/magnet-page.test.tsx +430 -0
  161. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/two-route-tool.test.tsx +21 -9
  162. package/templates/apps/web/app/[locale]/flows/[slug]/magnet-page.tsx +352 -0
  163. package/templates/apps/web/app/[locale]/flows/[slug]/page.tsx +12 -73
  164. package/templates/apps/web/app/[locale]/flows/[slug]/start/page.tsx +10 -31
  165. package/templates/apps/web/app/[locale]/layout.tsx +55 -4
  166. package/templates/apps/web/app/[locale]/newsletter/__tests__/page.test.tsx +174 -104
  167. package/templates/apps/web/app/[locale]/newsletter/page.tsx +95 -58
  168. package/templates/apps/web/app/[locale]/pricing/__tests__/__snapshots__/unconnected.test.tsx.snap +7 -0
  169. package/templates/apps/web/app/[locale]/pricing/__tests__/offerings.test.tsx +599 -0
  170. package/templates/apps/web/app/[locale]/pricing/__tests__/page.test.tsx +216 -0
  171. package/templates/apps/web/app/[locale]/pricing/__tests__/unconnected.test.tsx +236 -0
  172. package/templates/apps/web/app/[locale]/pricing/page.tsx +367 -6
  173. package/templates/apps/web/app/[locale]/team/__tests__/team-routes.test.tsx +4 -1
  174. package/templates/apps/web/app/[locale]/unsubscribe/__tests__/unsubscribe-rsc-boundary.test.tsx +17 -0
  175. package/templates/apps/web/app/[locale]/unsubscribe/__tests__/unsubscribe.test.tsx +62 -3
  176. package/templates/apps/web/app/[locale]/unsubscribe/page.tsx +70 -18
  177. package/templates/apps/web/app/[locale]/unsubscribe/unsubscribe-button.tsx +30 -9
  178. package/templates/apps/web/app/api/offerings/checkout/[lookupKey]/route.ts +316 -0
  179. package/templates/apps/web/app/api/offerings/checkout/__tests__/route.test.ts +810 -0
  180. package/templates/apps/web/lib/__tests__/auth-routes.test.ts +27 -1
  181. package/templates/apps/web/lib/__tests__/deck-page.test.ts +2 -1
  182. package/templates/apps/web/lib/__tests__/in-page-magnet.test.ts +265 -0
  183. package/templates/apps/web/lib/__tests__/magnet-routes.test.ts +57 -0
  184. package/templates/apps/web/lib/__tests__/newsletter.actions.test.ts +293 -0
  185. package/templates/apps/web/lib/__tests__/offerings-pricing.test.ts +601 -0
  186. package/templates/apps/web/lib/__tests__/structured-data.test.tsx +67 -8
  187. package/templates/apps/web/lib/auth-routes.ts +36 -2
  188. package/templates/apps/web/lib/checkout-config.ts +9 -20
  189. package/templates/apps/web/lib/deck-page.ts +1 -0
  190. package/templates/apps/web/lib/deliverable-grant.ts +18 -0
  191. package/templates/apps/web/lib/in-page-magnet.ts +416 -0
  192. package/templates/apps/web/lib/magnet-routes.ts +42 -0
  193. package/templates/apps/web/lib/modules.generated.ts +9 -0
  194. package/templates/apps/web/lib/newsletter.actions.ts +202 -0
  195. package/templates/apps/web/lib/offerings-pricing.ts +326 -0
  196. package/templates/apps/web/lib/posting-title.ts +17 -0
  197. package/templates/apps/web/lib/sign-up-agreements.ts +4 -2
  198. package/templates/apps/web/messages/en.json +49 -15
  199. package/templates/apps/web/middleware.ts +12 -2
  200. package/templates/apps/web/security-headers.config.ts +17 -0
  201. package/templates/content/en/BlogList/blog.mdx +4 -71
  202. package/templates/content/en/BookCall/book-a-call.mdx +1 -41
  203. package/templates/content/en/BookCall/onsite-estimate.mdx +1 -17
  204. package/templates/content/en/BookCall/onsite-service.mdx +1 -17
  205. package/templates/content/en/BookCall/start-project.mdx +1 -17
  206. package/templates/content/en/ContactPage/contact.mdx +6 -63
  207. package/templates/content/en/HomePage/home.mdx +3 -21
  208. package/templates/database/CHANGELOG.md +31 -0
  209. package/templates/database/__tests__/in-page-magnets-migration.test.ts +161 -0
  210. package/templates/database/__tests__/offerings-checkout-session.db.test.ts +270 -0
  211. package/templates/database/__tests__/offerings-migration.test.ts +197 -0
  212. package/templates/database/__tests__/offerings-shown-price-ids-migration.test.ts +86 -0
  213. package/templates/database/__tests__/offerings.db.test.ts +303 -0
  214. package/templates/database/__tests__/seed.test.ts +31 -1
  215. package/templates/database/auth/schema.prisma +4 -0
  216. package/templates/database/config/schema.prisma +91 -0
  217. package/templates/database/migrations/20261020120000_offerings_data_model/migration.sql +146 -0
  218. package/templates/database/migrations/20261021120000_offerings_checkout_session/migration.sql +77 -0
  219. package/templates/database/migrations/20261022120000_in_page_magnets/migration.sql +45 -0
  220. package/templates/database/migrations/20261023120000_offerings_shown_price_ids/migration.sql +47 -0
  221. package/templates/database/migrations/20261024120000_organization_plan_checkout_session/migration.sql +16 -0
  222. package/templates/database/package.json +1 -1
  223. package/templates/database/seed.ts +30 -2
  224. package/versions.json +35 -35
  225. package/site-templates/marketing-site-free/content/en/Pricing/pricing.mdx +0 -199
  226. package/templates/apps/web/app/[locale]/downloads/__tests__/page-renderer-migration.test.tsx +0 -93
  227. package/templates/apps/web/app/[locale]/downloads/page.tsx +0 -37
  228. package/templates/apps/web/app/[locale]/newsletter/__tests__/newsletter.actions.test.ts +0 -139
  229. package/templates/apps/web/app/[locale]/newsletter/newsletter.actions.ts +0 -93
  230. package/templates/apps/web/app/api/checkout/[offering]/route.ts +0 -48
  231. package/templates/apps/web/app/api/checkout/__tests__/route.test.ts +0 -120
  232. package/templates/apps/web/app/api/checkout/__tests__/success-path.test.ts +0 -86
  233. package/templates/apps/web/app/api/webhooks/stripe/__tests__/route.test.ts +0 -92
  234. package/templates/apps/web/app/api/webhooks/stripe/route.ts +0 -31
  235. package/templates/apps/web/lib/__tests__/checkout.test.ts +0 -243
  236. package/templates/apps/web/lib/__tests__/meeting-slugs.test.ts +0 -120
  237. package/templates/apps/web/lib/checkout.ts +0 -93
  238. package/templates/apps/web/lib/meeting-slugs.ts +0 -63
@@ -0,0 +1,1300 @@
1
+ /**
2
+ * The Offerings checkout (#8931; spec
3
+ * docs/specs/8931-offerings-checkout-authorization-server-side-spec.md AC-1 …
4
+ * AC-6 and AC-3's composed A9 and A13 cases; contract A-T1, A-T2, A-T3).
5
+ *
6
+ * The harness drives `checkoutRoutes` through `app.inject()` on a Fastify
7
+ * instance configured as `server.ts` configures its own (`trustProxy`, the
8
+ * `req` serializer), with a logger whose stream captures every line.
9
+ * Mocked: the resolver, `store.js`, `connection.js`, the session record store
10
+ * and `chargeWriteBudget`. Real: `getSellableProductIds`, `normalizeCatalog`,
11
+ * `parseLookupKey` and the `stripe-client` calls, run against a fake client
12
+ * object. `STRIPE_SECRET_KEY` is unset, so any env-path answer is
13
+ * `500 stripe-not-configured`, distinguishable from every Offerings answer.
14
+ * The A9 cases set a composed `sk_test_` key and mock the `stripe` SDK, so the
15
+ * real `createCheckoutSession` runs the real `isOfferingsProduct`; the #9126
16
+ * cases set one too, so the env path they keep is a sale, not a 500.
17
+ */
18
+ import { Writable } from "node:stream";
19
+
20
+ import { logger } from "@working-theory/observability";
21
+ import Fastify, { type FastifyInstance } from "fastify";
22
+
23
+ jest.mock("@working-theory/analytics/server", () => ({
24
+ track: jest.fn().mockResolvedValue(undefined),
25
+ }));
26
+ // `server.ts` (for `requestLogSerializer`) reaches the email package, whose
27
+ // React Email dependency is ESM-only.
28
+ jest.mock("@working-theory/email", () => ({
29
+ sendLeadNotification: jest.fn().mockResolvedValue({ ok: true }),
30
+ }));
31
+
32
+ const mockEnvPricesList = jest.fn();
33
+ const mockEnvSessionsCreate = jest.fn();
34
+ const mockEnvSessionsRetrieve = jest.fn();
35
+ const mockEnvCustomersCreate = jest.fn();
36
+ jest.mock("stripe", () =>
37
+ jest.fn().mockImplementation(() => ({
38
+ prices: { list: mockEnvPricesList },
39
+ customers: { create: mockEnvCustomersCreate },
40
+ checkout: {
41
+ sessions: {
42
+ create: mockEnvSessionsCreate,
43
+ retrieve: mockEnvSessionsRetrieve,
44
+ },
45
+ },
46
+ })),
47
+ );
48
+
49
+ // eslint-disable-next-line no-restricted-syntax -- jest mock factory must be hoisted; the DB boundary, mirrors sessions.test.ts
50
+ jest.mock("../../../lib/prisma.js", () => ({
51
+ prisma: {
52
+ session: { findUnique: jest.fn() },
53
+ user: { findUnique: jest.fn() },
54
+ apiToken: { findUnique: jest.fn(), update: jest.fn() },
55
+ },
56
+ }));
57
+
58
+ const mockResolvePublicWorkspace = jest.fn();
59
+ // eslint-disable-next-line no-restricted-syntax -- the resolver reads the spoke registry and the workspace table; the spec's harness (§5) stubs its answers.
60
+ jest.mock("../../../services/public-site-resolver.js", () => ({
61
+ ...jest.requireActual("../../../services/public-site-resolver.js"),
62
+ resolvePublicWorkspace: (...args: unknown[]) =>
63
+ mockResolvePublicWorkspace(...args),
64
+ }));
65
+
66
+ const mockOrganizationIdOfWorkspace = jest.fn();
67
+ const mockReadWorkspaceSelection = jest.fn();
68
+ const mockReadEnabledProductIds = jest.fn();
69
+ const mockReadWorkspaceSnapshot = jest.fn();
70
+ // eslint-disable-next-line no-restricted-syntax -- store.js is the Offerings rows' one database file (#8876); the rows are stubbed here, the readers above them run as themselves.
71
+ jest.mock("../../../services/offerings/store.js", () => ({
72
+ ...jest.requireActual("../../../services/offerings/store.js"),
73
+ organizationIdOfWorkspace: (...args: unknown[]) =>
74
+ mockOrganizationIdOfWorkspace(...args),
75
+ readWorkspaceSelection: (...args: unknown[]) =>
76
+ mockReadWorkspaceSelection(...args),
77
+ readEnabledProductIds: (...args: unknown[]) =>
78
+ mockReadEnabledProductIds(...args),
79
+ readWorkspaceSnapshot: (...args: unknown[]) =>
80
+ mockReadWorkspaceSnapshot(...args),
81
+ }));
82
+
83
+ const mockConnectionSummary = jest.fn();
84
+ const mockClientForOrganization = jest.fn();
85
+ // eslint-disable-next-line no-restricted-syntax -- the connection custody wraps the database and the AES-GCM key (#8907); the spec's harness stubs its two answers.
86
+ jest.mock("../../../services/offerings/connection.js", () => ({
87
+ getStripeConnectionSummary: (...args: unknown[]) =>
88
+ mockConnectionSummary(...args),
89
+ stripeClientForOrganization: (...args: unknown[]) =>
90
+ mockClientForOrganization(...args),
91
+ }));
92
+
93
+ const mockRecordCheckoutSession = jest.fn();
94
+ const mockReadCheckoutSessionRecord = jest.fn();
95
+ // eslint-disable-next-line no-restricted-syntax -- the session record wraps the database (#8930); its write and read are stubbed.
96
+ jest.mock("../../../services/offerings/checkout-session-record.js", () => ({
97
+ ...jest.requireActual(
98
+ "../../../services/offerings/checkout-session-record.js",
99
+ ),
100
+ recordCheckoutSession: (...args: unknown[]) =>
101
+ mockRecordCheckoutSession(...args),
102
+ readCheckoutSessionRecord: (...args: unknown[]) =>
103
+ mockReadCheckoutSessionRecord(...args),
104
+ }));
105
+
106
+ const mockChargeWriteBudget = jest.fn();
107
+ // eslint-disable-next-line no-restricted-syntax -- chargeWriteBudget runs on the database store (#8907); the bucket's answers are stubbed, the rest of the module is real.
108
+ jest.mock("../../../middleware/rate-limit.js", () => ({
109
+ ...jest.requireActual("../../../middleware/rate-limit.js"),
110
+ chargeWriteBudget: (...args: unknown[]) => mockChargeWriteBudget(...args),
111
+ }));
112
+
113
+ import { config } from "../../../config/index.js";
114
+ import { prisma } from "../../../lib/prisma.js";
115
+ import { requestLogSerializer } from "../../../server.js";
116
+ import { CheckoutSessionRecordError } from "../../../services/offerings/checkout-session-record.js";
117
+ import { checkoutRoutes } from "../index";
118
+
119
+ config.FRONTEND_URL = "https://example.com";
120
+ config.TRUSTED_ORIGINS = ["https://example.com"];
121
+
122
+ /** The mocked SDK constructor: a call to it is the env client being built. */
123
+ const envStripeConstructor = () => jest.requireMock("stripe") as jest.Mock;
124
+
125
+ // ── Fixture ──────────────────────────────────────────────────────────────────
126
+
127
+ const WS = "wksp_00000000-0000-7000-8000-000000008931";
128
+ const ORG = "org_00000000-0000-7000-8000-000000008931";
129
+ const SESSION_ID = "cs_test_a1B2c3D4e5F6g7H8offerings8931";
130
+ const SESSION_URL = `https://checkout.stripe.com/c/pay/${SESSION_ID}`;
131
+ const SUMMARY = {
132
+ mode: "test",
133
+ last4: "4242",
134
+ connectedAt: "2026-10-18T00:00:00.000Z",
135
+ liveAt: null,
136
+ updatedAt: "2026-10-18T00:00:00.000Z",
137
+ };
138
+
139
+ function product(id: string, overrides: Record<string, unknown> = {}) {
140
+ return {
141
+ id,
142
+ object: "product",
143
+ active: true,
144
+ name: `Product ${id.slice(5)}`,
145
+ metadata: { ailk_group: "plan" },
146
+ ...overrides,
147
+ };
148
+ }
149
+
150
+ function recurringPrice(id: string, lookupKey: string, prod: unknown) {
151
+ return {
152
+ id,
153
+ object: "price",
154
+ active: true,
155
+ product: prod,
156
+ lookup_key: lookupKey,
157
+ type: "recurring",
158
+ recurring: { interval: "month", interval_count: 1, usage_type: "licensed" },
159
+ billing_scheme: "per_unit",
160
+ unit_amount: 2900,
161
+ currency: "usd",
162
+ };
163
+ }
164
+
165
+ function oneTimePrice(id: string, lookupKey: string, prod: unknown) {
166
+ return {
167
+ id,
168
+ object: "price",
169
+ active: true,
170
+ product: prod,
171
+ lookup_key: lookupKey,
172
+ type: "one_time",
173
+ recurring: null,
174
+ billing_scheme: "per_unit",
175
+ unit_amount: 9900,
176
+ currency: "usd",
177
+ };
178
+ }
179
+
180
+ const PROD_A = product("prod_A8931");
181
+ const PROD_B = product("prod_B8931");
182
+ const PROD_C = product("prod_C8931");
183
+ const PROD_D = product("prod_D8931");
184
+ const PROD_X = product("prod_X8931");
185
+ const PRICE_A = recurringPrice("price_A8931growth", "growth_monthly", PROD_A);
186
+ const PRICE_B = recurringPrice("price_B8931scale", "scale_monthly", PROD_B);
187
+ const PRICE_C = recurringPrice("price_C8931team", "team_monthly", PROD_C);
188
+ const PRICE_D = oneTimePrice("price_D8931basic", "basic_once", PROD_D);
189
+ /** PROD_A's yearly Price, for the per-Price shown set (#9070 D5). */
190
+ const PRICE_A_YEARLY = {
191
+ ...recurringPrice("price_A8931growthyear", "growth_yearly", PROD_A),
192
+ recurring: { interval: "year", interval_count: 1, usage_type: "licensed" },
193
+ unit_amount: 29000,
194
+ };
195
+ const PRICE_MOVED = recurringPrice(
196
+ "price_X8931moved",
197
+ "growth_monthly",
198
+ PROD_X,
199
+ );
200
+
201
+ /** Every id, key and URL that must never reach a log line or a refusal body (AC-6). */
202
+ const SECRETS = [
203
+ "growth_monthly",
204
+ "growth_yearly",
205
+ "scale_monthly",
206
+ "team_monthly",
207
+ "basic_once",
208
+ "enterprise_monthly",
209
+ "Growth_Monthly",
210
+ "growth_pro_monthly",
211
+ "wendi_retainer",
212
+ PROD_A.id,
213
+ PROD_B.id,
214
+ PROD_C.id,
215
+ PROD_D.id,
216
+ PROD_X.id,
217
+ PRICE_A.id,
218
+ PRICE_A_YEARLY.id,
219
+ PRICE_B.id,
220
+ PRICE_C.id,
221
+ PRICE_D.id,
222
+ PRICE_MOVED.id,
223
+ SESSION_ID,
224
+ SESSION_URL,
225
+ ];
226
+
227
+ const BODY = {
228
+ productCode: "growth_monthly",
229
+ successUrl: "https://example.com/thanks",
230
+ cancelUrl: "https://example.com/pricing",
231
+ };
232
+
233
+ type Fake = ReturnType<typeof fakeClient>;
234
+
235
+ /** The Organization's own client: `prices.list` answers from `catalog` by key. */
236
+ function fakeClient(
237
+ catalog: Record<string, unknown[]> = { growth_monthly: [PRICE_A] },
238
+ ) {
239
+ return {
240
+ prices: {
241
+ list: jest.fn(async (params: { lookup_keys: string[] }) => ({
242
+ data: catalog[params.lookup_keys[0]!] ?? [],
243
+ })),
244
+ },
245
+ checkout: {
246
+ sessions: {
247
+ create: jest
248
+ .fn()
249
+ .mockResolvedValue({ id: SESSION_ID, url: SESSION_URL }),
250
+ expire: jest.fn().mockResolvedValue({}),
251
+ retrieve: jest.fn(),
252
+ },
253
+ },
254
+ };
255
+ }
256
+
257
+ // ── The log capture (AC-6) ──────────────────────────────────────────────────
258
+
259
+ const logged: string[] = [];
260
+ const bodies: Array<{ status: number; body: string }> = [];
261
+
262
+ function captureStream(): Writable {
263
+ return new Writable({
264
+ write(chunk, _enc, done) {
265
+ logged.push(chunk.toString());
266
+ done();
267
+ },
268
+ });
269
+ }
270
+
271
+ function buildApp(): FastifyInstance {
272
+ const app = Fastify({
273
+ logger: {
274
+ level: "info",
275
+ stream: captureStream(),
276
+ serializers: { req: requestLogSerializer },
277
+ },
278
+ trustProxy: true,
279
+ });
280
+ app.register(checkoutRoutes);
281
+ return app;
282
+ }
283
+
284
+ let app: FastifyInstance;
285
+ let client: Fake;
286
+ const savedKey = process.env.STRIPE_SECRET_KEY;
287
+ const savedDatabaseUrl = process.env.DATABASE_URL;
288
+
289
+ async function post(
290
+ body: Record<string, unknown> = BODY,
291
+ headers: Record<string, string> = {},
292
+ ) {
293
+ const res = await app.inject({
294
+ method: "POST",
295
+ url: "/v1/checkout/sessions",
296
+ payload: body,
297
+ headers,
298
+ });
299
+ bodies.push({ status: res.statusCode, body: res.body });
300
+ return res;
301
+ }
302
+
303
+ async function get(id = SESSION_ID) {
304
+ const res = await app.inject({
305
+ method: "GET",
306
+ url: `/v1/checkout/sessions/${id}`,
307
+ });
308
+ bodies.push({ status: res.statusCode, body: res.body });
309
+ return res;
310
+ }
311
+
312
+ function givenRows(enabled: string[], shown: string[], shownPrices: string[] = []) {
313
+ mockReadEnabledProductIds.mockResolvedValue(enabled);
314
+ mockReadWorkspaceSelection.mockResolvedValue({
315
+ shownProductIds: shown,
316
+ shownPriceIds: shownPrices,
317
+ recommendedPlanProductId: null,
318
+ recommendedAddonProductId: null,
319
+ });
320
+ }
321
+
322
+ beforeAll(() => {
323
+ for (const level of ["info", "warn", "error", "debug"] as const) {
324
+ jest.spyOn(logger, level).mockImplementation(((...args: unknown[]) => {
325
+ logged.push(JSON.stringify(args));
326
+ }) as never);
327
+ }
328
+ });
329
+
330
+ beforeEach(async () => {
331
+ jest.clearAllMocks();
332
+ delete process.env.STRIPE_SECRET_KEY;
333
+ process.env.DATABASE_URL = savedDatabaseUrl;
334
+ client = fakeClient();
335
+ mockResolvePublicWorkspace.mockResolvedValue({
336
+ kind: "resolved",
337
+ workspaceId: WS,
338
+ });
339
+ mockOrganizationIdOfWorkspace.mockResolvedValue(ORG);
340
+ mockConnectionSummary.mockResolvedValue(SUMMARY);
341
+ mockClientForOrganization.mockImplementation(async () => ({
342
+ kind: "ok",
343
+ client,
344
+ mode: "test",
345
+ }));
346
+ givenRows([PROD_A.id, PROD_B.id], [PROD_A.id, PROD_C.id]);
347
+ mockReadWorkspaceSnapshot.mockResolvedValue(null);
348
+ mockRecordCheckoutSession.mockResolvedValue(undefined);
349
+ mockReadCheckoutSessionRecord.mockResolvedValue(null);
350
+ mockChargeWriteBudget.mockResolvedValue({ ok: true });
351
+ app = buildApp();
352
+ await app.ready();
353
+ });
354
+
355
+ afterEach(async () => {
356
+ await app.close();
357
+ });
358
+
359
+ afterAll(() => {
360
+ process.env.STRIPE_SECRET_KEY = savedKey;
361
+ process.env.DATABASE_URL = savedDatabaseUrl;
362
+ });
363
+
364
+ // ── AC-1: one identical 404 for every miss (A3, A4, A5, A-T1, A-T2) ─────────
365
+
366
+ describe("AC-1 — every miss is one 404 that never echoes the key", () => {
367
+ const NOT_FOUND = JSON.stringify({ error: "unknown-product-code" });
368
+
369
+ function expectMiss(res: { statusCode: number; body: string }, key: string) {
370
+ expect(res.statusCode).toBe(404);
371
+ expect(res.body).toBe(NOT_FOUND);
372
+ expect(res.body).not.toContain(key);
373
+ expect(client.checkout.sessions.create).not.toHaveBeenCalled();
374
+ expect(mockRecordCheckoutSession).not.toHaveBeenCalled();
375
+ }
376
+
377
+ it.each<[string, string, Record<string, unknown[]>]>([
378
+ ["enabled but not shown", "scale_monthly", { scale_monthly: [PRICE_B] }],
379
+ ["shown but not enabled", "team_monthly", { team_monthly: [PRICE_C] }],
380
+ [
381
+ "moved to another Product",
382
+ "growth_monthly",
383
+ { growth_monthly: [PRICE_MOVED] },
384
+ ],
385
+ ["nonexistent", "enterprise_monthly", {}],
386
+ ])("a key %s answers the 404", async (_label, key, catalog) => {
387
+ client = fakeClient(catalog);
388
+ const res = await post({ ...BODY, productCode: key });
389
+ expectMiss(res, key);
390
+ expect(client.prices.list).toHaveBeenCalledTimes(1);
391
+ });
392
+
393
+ it.each(["Growth_Monthly", "growth_pro_monthly", "wendi_retainer"])(
394
+ "the ungrammatical %s answers the 404 with no Stripe or database call",
395
+ async (key) => {
396
+ const res = await post({ ...BODY, productCode: key });
397
+ expectMiss(res, key);
398
+ expect(client.prices.list).not.toHaveBeenCalled();
399
+ expect(mockClientForOrganization).not.toHaveBeenCalled();
400
+ expect(mockReadWorkspaceSelection).not.toHaveBeenCalled();
401
+ },
402
+ );
403
+
404
+ it("a key in the shown set's snapshot but not the live read answers 404 with no session (A-T2)", async () => {
405
+ mockReadWorkspaceSnapshot.mockResolvedValue({
406
+ snapshot: {
407
+ offerings: [
408
+ { productId: PROD_A.id, prices: [{ lookupKey: "growth_monthly" }] },
409
+ ],
410
+ },
411
+ snapshotAt: new Date(),
412
+ });
413
+ client = fakeClient({});
414
+ const res = await post();
415
+ expectMiss(res, "growth_monthly");
416
+ expect(mockReadWorkspaceSnapshot).not.toHaveBeenCalled();
417
+ });
418
+
419
+ it("the same fixtures sell growth_monthly (so each 404 above is the check, not the fixture)", async () => {
420
+ const res = await post();
421
+ expect(res.statusCode).toBe(201);
422
+ });
423
+
424
+ it("a workspace that sells nothing answers the 404 with no Stripe call", async () => {
425
+ givenRows([PROD_A.id], [PROD_C.id]);
426
+ const res = await post();
427
+ expectMiss(res, "growth_monthly");
428
+ expect(client.prices.list).not.toHaveBeenCalled();
429
+ });
430
+
431
+ it("a Price whose period disagrees with its key answers the 404", async () => {
432
+ const yearly = {
433
+ ...PRICE_A,
434
+ recurring: {
435
+ interval: "year",
436
+ interval_count: 1,
437
+ usage_type: "licensed",
438
+ },
439
+ };
440
+ client = fakeClient({ growth_monthly: [yearly] });
441
+ expectMiss(await post(), "growth_monthly");
442
+ });
443
+
444
+ it("a Product the normalizer holds (no ailk_group) answers the 404", async () => {
445
+ const unmarked = recurringPrice(PRICE_A.id, "growth_monthly", {
446
+ ...PROD_A,
447
+ metadata: {},
448
+ });
449
+ client = fakeClient({ growth_monthly: [unmarked] });
450
+ expectMiss(await post(), "growth_monthly");
451
+ });
452
+ });
453
+
454
+ // ── AC-2: the stamped, anonymous, recorded session (A6, A7, A11) ────────────
455
+
456
+ describe("#9070 D5 (AC-5) — a workspace saved per Price sells only its shown Prices", () => {
457
+ const catalog = { growth_monthly: [PRICE_A], growth_yearly: [PRICE_A_YEARLY] };
458
+
459
+ it("sells the shown yearly Price and refuses its switched-off monthly sibling as the one 404", async () => {
460
+ client = fakeClient(catalog);
461
+ givenRows([PROD_A.id], [PROD_A.id], [PRICE_A_YEARLY.id]);
462
+
463
+ const yearly = await post({ ...BODY, productCode: "growth_yearly" });
464
+ expect(yearly.statusCode).toBe(201);
465
+ expect(client.checkout.sessions.create).toHaveBeenCalledTimes(1);
466
+ expect(client.checkout.sessions.create.mock.calls[0][0].line_items).toEqual([
467
+ { price: PRICE_A_YEARLY.id, quantity: 1 },
468
+ ]);
469
+
470
+ jest.clearAllMocks();
471
+ const monthly = await post();
472
+ expect(monthly.statusCode).toBe(404);
473
+ expect(monthly.json()).toEqual({ error: "unknown-product-code" });
474
+ expect(monthly.body).not.toContain("growth_monthly");
475
+ expect(client.checkout.sessions.create).not.toHaveBeenCalled();
476
+ expect(mockRecordCheckoutSession).not.toHaveBeenCalled();
477
+ });
478
+
479
+ it("with no stored Prices both Prices of a shown Product sell", async () => {
480
+ client = fakeClient(catalog);
481
+ givenRows([PROD_A.id], [PROD_A.id]);
482
+
483
+ expect((await post({ ...BODY, productCode: "growth_yearly" })).statusCode).toBe(201);
484
+ expect((await post()).statusCode).toBe(201);
485
+ expect(client.checkout.sessions.create).toHaveBeenCalledTimes(2);
486
+ });
487
+ });
488
+
489
+ describe("AC-2 — an authorized key sells its Price in a stamped hosted session", () => {
490
+ it("answers 201 { sessionId, url } from a session created for the authorized Price", async () => {
491
+ const res = await post();
492
+
493
+ expect(res.statusCode).toBe(201);
494
+ expect(res.json()).toEqual({ sessionId: SESSION_ID, url: SESSION_URL });
495
+ expect(client.prices.list).toHaveBeenCalledTimes(1);
496
+ expect(client.prices.list).toHaveBeenCalledWith({
497
+ lookup_keys: ["growth_monthly"],
498
+ active: true,
499
+ limit: 1,
500
+ expand: ["data.product"],
501
+ });
502
+ expect(client.checkout.sessions.create).toHaveBeenCalledTimes(1);
503
+ const params = client.checkout.sessions.create.mock.calls[0][0];
504
+ expect(params.line_items).toEqual([{ price: PRICE_A.id, quantity: 1 }]);
505
+ expect(params.mode).toBe("subscription");
506
+ expect(params.allow_promotion_codes).toBe(true);
507
+ expect(Object.keys(params.metadata).sort()).toEqual([
508
+ "ailk_offering",
509
+ "ailk_terms",
510
+ "site",
511
+ ]);
512
+ expect(params.metadata.site).toBe(WS);
513
+ expect(params.metadata.ailk_offering).toBe("growth_monthly");
514
+ expect(params.subscription_data).toEqual({
515
+ metadata: { site: WS, ailk_offering: "growth_monthly" },
516
+ });
517
+ expect(params).not.toHaveProperty("customer");
518
+ expect(params).not.toHaveProperty("customer_creation");
519
+ // The env client is never built.
520
+ expect(envStripeConstructor()).not.toHaveBeenCalled();
521
+ });
522
+
523
+ it("allows promotion codes even when the body says false (C3)", async () => {
524
+ await post({ ...BODY, allowPromotionCodes: false });
525
+ expect(
526
+ client.checkout.sessions.create.mock.calls[0][0].allow_promotion_codes,
527
+ ).toBe(true);
528
+ });
529
+
530
+ it("a one-time Price opens a payment session that creates a customer, with no subscription_data", async () => {
531
+ givenRows([PROD_D.id], [PROD_D.id]);
532
+ client = fakeClient({ basic_once: [PRICE_D] });
533
+
534
+ const res = await post({ ...BODY, productCode: "basic_once" });
535
+
536
+ expect(res.statusCode).toBe(201);
537
+ const params = client.checkout.sessions.create.mock.calls[0][0];
538
+ expect(params.mode).toBe("payment");
539
+ expect(params.customer_creation).toBe("always");
540
+ expect(params).not.toHaveProperty("subscription_data");
541
+ expect(params).not.toHaveProperty("customer");
542
+ });
543
+
544
+ it("a signed-in cookie is never read and no param carries ailk_user_id (C4)", async () => {
545
+ (prisma.session.findUnique as jest.Mock).mockResolvedValue({
546
+ id: "ses_1",
547
+ userId: "usr_buyer",
548
+ expiresAt: new Date(Date.now() + 60_000),
549
+ activeOrganizationId: null,
550
+ activeWorkspaceId: null,
551
+ });
552
+ (prisma.user.findUnique as jest.Mock).mockResolvedValue({
553
+ id: "usr_buyer",
554
+ email: "buyer@example.com",
555
+ emailVerified: true,
556
+ billingProvider: null,
557
+ billingCustomerId: null,
558
+ });
559
+
560
+ const res = await post(BODY, {
561
+ cookie: "better-auth.session_token=sess_tok_buyer.signature",
562
+ origin: "https://example.com",
563
+ });
564
+
565
+ expect(res.statusCode).toBe(201);
566
+ expect(prisma.session.findUnique).not.toHaveBeenCalled();
567
+ expect(
568
+ JSON.stringify(client.checkout.sessions.create.mock.calls),
569
+ ).not.toContain("ailk_user_id");
570
+ });
571
+
572
+ it("records the session through the keystone store, after the create", async () => {
573
+ await post();
574
+
575
+ expect(mockRecordCheckoutSession).toHaveBeenCalledTimes(1);
576
+ expect(mockRecordCheckoutSession).toHaveBeenCalledWith({
577
+ sessionId: SESSION_ID,
578
+ workspaceId: WS,
579
+ organizationId: ORG,
580
+ priceId: PRICE_A.id,
581
+ lookupKey: "growth_monthly",
582
+ mode: "test",
583
+ });
584
+ expect(
585
+ mockRecordCheckoutSession.mock.invocationCallOrder[0],
586
+ ).toBeGreaterThan(
587
+ client.checkout.sessions.create.mock.invocationCallOrder[0]!,
588
+ );
589
+ });
590
+
591
+ it("does not answer while the record is pending", async () => {
592
+ let release!: () => void;
593
+ mockRecordCheckoutSession.mockReturnValue(
594
+ new Promise<void>((resolve) => {
595
+ release = resolve;
596
+ }),
597
+ );
598
+ let answered = false;
599
+ const pending = post().then((res) => {
600
+ answered = true;
601
+ return res;
602
+ });
603
+ for (
604
+ let i = 0;
605
+ i < 20 && mockRecordCheckoutSession.mock.calls.length === 0;
606
+ i++
607
+ ) {
608
+ await new Promise((resolve) => setImmediate(resolve));
609
+ }
610
+ expect(mockRecordCheckoutSession).toHaveBeenCalledTimes(1);
611
+ await new Promise((resolve) => setImmediate(resolve));
612
+ expect(answered).toBe(false);
613
+
614
+ release();
615
+ const res = await pending;
616
+ expect(res.statusCode).toBe(201);
617
+ });
618
+
619
+ it.each([
620
+ "invalid",
621
+ "workspace_mismatch",
622
+ "conflict",
623
+ "write_failed",
624
+ ] as const)(
625
+ "a record that rejects %s expires the session and answers 502",
626
+ async (reason) => {
627
+ mockRecordCheckoutSession.mockRejectedValue(
628
+ new CheckoutSessionRecordError(reason),
629
+ );
630
+
631
+ const res = await post();
632
+
633
+ expect(res.statusCode).toBe(502);
634
+ expect(res.json()).toEqual({ error: "checkout-unavailable" });
635
+ expect(client.checkout.sessions.expire).toHaveBeenCalledWith(SESSION_ID);
636
+ },
637
+ );
638
+
639
+ it("a budget store that throws answers 502 with no Stripe call (code review #9032)", async () => {
640
+ mockChargeWriteBudget.mockRejectedValueOnce(new Error("store down"));
641
+
642
+ const res = await post();
643
+
644
+ expect(res.statusCode).toBe(502);
645
+ expect(res.json()).toEqual({ error: "checkout-unavailable" });
646
+ expect(client.checkout.sessions.create).not.toHaveBeenCalled();
647
+ });
648
+
649
+ it("a failed record whose expire also fails still answers 502", async () => {
650
+ mockRecordCheckoutSession.mockRejectedValue(
651
+ new CheckoutSessionRecordError("write_failed"),
652
+ );
653
+ client.checkout.sessions.expire.mockRejectedValue(new Error("stripe down"));
654
+
655
+ const res = await post();
656
+
657
+ expect(res.statusCode).toBe(502);
658
+ expect(res.json()).toEqual({ error: "checkout-unavailable" });
659
+ expect(client.checkout.sessions.expire).toHaveBeenCalledWith(SESSION_ID);
660
+ });
661
+ });
662
+
663
+ // ── AC-3: the env path refuses an Offerings product (A9) ────────────────────
664
+
665
+ describe("AC-3 (A9) — the env path, composed with the real stripe-client and marker", () => {
666
+ beforeEach(() => {
667
+ mockResolvePublicWorkspace.mockResolvedValue({ kind: "not-required" });
668
+ process.env.STRIPE_SECRET_KEY =
669
+ ["sk", "test", ""].join("_") + "OfferingsEnv8931";
670
+ mockEnvSessionsCreate.mockResolvedValue({
671
+ id: "cs_test_env8931",
672
+ url: "https://checkout.stripe.com/c/pay/cs_test_env8931",
673
+ });
674
+ });
675
+
676
+ it.each<[string, unknown]>([
677
+ [
678
+ "a Product carrying metadata.ailk_group",
679
+ { id: "prod_Env1", metadata: { ailk_group: "plan" } },
680
+ ],
681
+ ["a bare product id the expand did not turn into an object", "prod_Env2"],
682
+ ])("%s answers the 404 with no session", async (_label, prod) => {
683
+ mockEnvPricesList.mockResolvedValue({
684
+ data: [{ id: "price_Env", type: "recurring", product: prod }],
685
+ });
686
+
687
+ const res = await post({ ...BODY, productCode: "ailk-pro" });
688
+
689
+ expect(res.statusCode).toBe(404);
690
+ expect(res.json()).toEqual({ error: "unknown-product-code" });
691
+ expect(mockEnvPricesList).toHaveBeenCalledWith({
692
+ lookup_keys: ["ailk-pro"],
693
+ active: true,
694
+ limit: 1,
695
+ expand: ["data.product"],
696
+ });
697
+ expect(mockEnvSessionsCreate).not.toHaveBeenCalled();
698
+ expect(mockChargeWriteBudget).not.toHaveBeenCalled();
699
+ });
700
+
701
+ it("a Product with no ailk_group still sells on the env path", async () => {
702
+ mockEnvPricesList.mockResolvedValue({
703
+ data: [
704
+ {
705
+ id: "price_Env",
706
+ type: "recurring",
707
+ product: { id: "prod_Env3", metadata: {} },
708
+ },
709
+ ],
710
+ });
711
+
712
+ const res = await post({ ...BODY, productCode: "ailk-pro" });
713
+
714
+ expect(res.statusCode).toBe(201);
715
+ expect(mockEnvSessionsCreate).toHaveBeenCalledTimes(1);
716
+ expect(mockEnvSessionsCreate.mock.calls[0][0].metadata).toHaveProperty(
717
+ "site",
718
+ );
719
+ });
720
+ });
721
+
722
+ // ── AC-3: the session read uses the record's own connection (A13) ───────────
723
+
724
+ describe("AC-3 (A13) — GET /v1/checkout/sessions/:id for a recorded session", () => {
725
+ const RECORD = {
726
+ sessionId: SESSION_ID,
727
+ workspaceId: WS,
728
+ organizationId: ORG,
729
+ priceId: PRICE_A.id,
730
+ lookupKey: "growth_monthly",
731
+ mode: "test" as const,
732
+ createdAt: new Date("2026-10-18T00:00:00Z"),
733
+ };
734
+ const LONG_NAME = "Growth‮ plan" + "x".repeat(300);
735
+
736
+ function stripeSession() {
737
+ return {
738
+ id: SESSION_ID,
739
+ status: "complete",
740
+ payment_status: "paid",
741
+ currency: "usd",
742
+ amount_total: 2900,
743
+ line_items: {
744
+ data: [
745
+ {
746
+ description: LONG_NAME,
747
+ quantity: 1,
748
+ amount_total: 2900,
749
+ currency: "usd",
750
+ },
751
+ ],
752
+ },
753
+ };
754
+ }
755
+
756
+ beforeEach(() => {
757
+ mockReadCheckoutSessionRecord.mockResolvedValue(RECORD);
758
+ client.checkout.sessions.retrieve.mockResolvedValue(stripeSession());
759
+ });
760
+
761
+ it("reads on the record's connection and serves today's 200 body and headers", async () => {
762
+ const res = await get();
763
+
764
+ expect(res.statusCode).toBe(200);
765
+ expect(mockClientForOrganization).toHaveBeenCalledWith(ORG);
766
+ expect(client.checkout.sessions.retrieve).toHaveBeenCalledWith(SESSION_ID, {
767
+ expand: ["line_items"],
768
+ });
769
+ expect(envStripeConstructor()).not.toHaveBeenCalled();
770
+ expect(res.headers["cache-control"]).toBe("no-store");
771
+ expect(res.headers["x-robots-tag"]).toBe("noindex, nofollow");
772
+ expect(res.headers["referrer-policy"]).toBe("no-referrer");
773
+ const body = res.json();
774
+ expect(Object.keys(body).sort()).toEqual(
775
+ [
776
+ "amountTotal",
777
+ "currency",
778
+ "id",
779
+ "lineItems",
780
+ "paymentStatus",
781
+ "status",
782
+ ].sort(),
783
+ );
784
+ expect(body).toMatchObject({
785
+ id: SESSION_ID,
786
+ status: "complete",
787
+ paymentStatus: "paid",
788
+ currency: "usd",
789
+ amountTotal: 2900,
790
+ });
791
+ const description: string = body.lineItems[0].description;
792
+ expect(description).not.toContain("‮");
793
+ expect([...description].length).toBeLessThanOrEqual(200);
794
+ expect(description.startsWith("Growth plan")).toBe(true);
795
+ });
796
+
797
+ it.each<[string, () => void]>([
798
+ [
799
+ "a connection in another mode",
800
+ () =>
801
+ mockClientForOrganization.mockResolvedValue({
802
+ kind: "ok",
803
+ client,
804
+ mode: "live",
805
+ }),
806
+ ],
807
+ [
808
+ "no connection",
809
+ () => mockClientForOrganization.mockResolvedValue({ kind: "none" }),
810
+ ],
811
+ [
812
+ "an unusable connection",
813
+ () => mockClientForOrganization.mockResolvedValue({ kind: "unusable" }),
814
+ ],
815
+ [
816
+ "an unreadable record",
817
+ () => mockReadCheckoutSessionRecord.mockResolvedValue("unreadable"),
818
+ ],
819
+ [
820
+ "a rejected record read",
821
+ () =>
822
+ mockReadCheckoutSessionRecord.mockRejectedValue(
823
+ new CheckoutSessionRecordError("read_failed"),
824
+ ),
825
+ ],
826
+ [
827
+ "a rejected connection read",
828
+ () =>
829
+ mockClientForOrganization.mockRejectedValue(new Error("store down")),
830
+ ],
831
+ ])(
832
+ "%s answers 502 with no retrieve on any client",
833
+ async (_label, arrange) => {
834
+ arrange();
835
+
836
+ const res = await get();
837
+
838
+ expect(res.statusCode).toBe(502);
839
+ expect(res.json()).toEqual({ error: "checkout-unavailable" });
840
+ expect(client.checkout.sessions.retrieve).not.toHaveBeenCalled();
841
+ expect(mockEnvSessionsRetrieve).not.toHaveBeenCalled();
842
+ },
843
+ );
844
+
845
+ it("a recorded session Stripe does not know answers 404 unknown-session", async () => {
846
+ client.checkout.sessions.retrieve.mockRejectedValue(
847
+ Object.assign(new Error("No such checkout.session"), {
848
+ code: "resource_missing",
849
+ }),
850
+ );
851
+ const res = await get();
852
+ expect(res.statusCode).toBe(404);
853
+ expect(res.json()).toEqual({ error: "unknown-session" });
854
+ });
855
+
856
+ it("no record answers as the env path does", async () => {
857
+ mockReadCheckoutSessionRecord.mockResolvedValue(null);
858
+ const res = await get();
859
+ expect(res.statusCode).toBe(500);
860
+ expect(res.json()).toEqual({ error: "stripe-not-configured" });
861
+ expect(client.checkout.sessions.retrieve).not.toHaveBeenCalled();
862
+ });
863
+
864
+ it("with no database the record store is never called", async () => {
865
+ delete process.env.DATABASE_URL;
866
+ const res = await get();
867
+ expect(mockReadCheckoutSessionRecord).not.toHaveBeenCalled();
868
+ expect(res.statusCode).toBe(500);
869
+ expect(res.json()).toEqual({ error: "stripe-not-configured" });
870
+ });
871
+ });
872
+
873
+ // ── AC-4: the path decision (A1, A2, A-T3) ──────────────────────────────────
874
+
875
+ describe("AC-4 — the workspace is the server's, and a refused spoke key is 503", () => {
876
+ it("a refused spoke key answers 503 tenant_unresolved with no Stripe, budget or Organization call", async () => {
877
+ mockResolvePublicWorkspace.mockResolvedValue({
878
+ kind: "unresolved",
879
+ reason: "spoke-refused",
880
+ });
881
+
882
+ const res = await post(BODY, { "x-ailk-spoke-key": "revoked-key" });
883
+
884
+ expect(res.statusCode).toBe(503);
885
+ expect(res.json()).toEqual({ error: "tenant_unresolved" });
886
+ expect(client.prices.list).not.toHaveBeenCalled();
887
+ expect(mockClientForOrganization).not.toHaveBeenCalled();
888
+ expect(mockChargeWriteBudget).not.toHaveBeenCalled();
889
+ expect(mockOrganizationIdOfWorkspace).not.toHaveBeenCalled();
890
+ });
891
+
892
+ it.each<[string, () => void]>([
893
+ [
894
+ "a header-less call refused as key-required",
895
+ () =>
896
+ mockResolvePublicWorkspace.mockResolvedValue({
897
+ kind: "unresolved",
898
+ reason: "spoke-refused",
899
+ }),
900
+ ],
901
+ [
902
+ "an ambiguous resolution",
903
+ () =>
904
+ mockResolvePublicWorkspace.mockResolvedValue({
905
+ kind: "unresolved",
906
+ reason: "ambiguous",
907
+ }),
908
+ ],
909
+ [
910
+ "an unmatched host",
911
+ () =>
912
+ mockResolvePublicWorkspace.mockResolvedValue({
913
+ kind: "unresolved",
914
+ reason: "host-unmatched",
915
+ }),
916
+ ],
917
+ [
918
+ "a deployment off the database adapter",
919
+ () =>
920
+ mockResolvePublicWorkspace.mockResolvedValue({ kind: "not-required" }),
921
+ ],
922
+ [
923
+ "a workspace with no Organization row",
924
+ () => mockOrganizationIdOfWorkspace.mockResolvedValue(null),
925
+ ],
926
+ [
927
+ "an Organization with no connection",
928
+ () => mockConnectionSummary.mockResolvedValue(null),
929
+ ],
930
+ ])("%s takes the env path", async (_label, arrange) => {
931
+ arrange();
932
+
933
+ const res = await post();
934
+
935
+ expect(res.statusCode).toBe(500);
936
+ expect(res.json()).toEqual({ error: "stripe-not-configured" });
937
+ expect(mockChargeWriteBudget).not.toHaveBeenCalled();
938
+ expect(client.prices.list).not.toHaveBeenCalled();
939
+ });
940
+
941
+ it("an unreadable connection answers 502, never the env path", async () => {
942
+ mockConnectionSummary.mockResolvedValue("unreadable");
943
+ const res = await post();
944
+ expect(res.statusCode).toBe(502);
945
+ expect(res.json()).toEqual({ error: "checkout-unavailable" });
946
+ expect(mockReadWorkspaceSelection).not.toHaveBeenCalled();
947
+ });
948
+
949
+ it.each<[string, () => void]>([
950
+ [
951
+ "the resolver",
952
+ () =>
953
+ mockResolvePublicWorkspace.mockRejectedValue(
954
+ new Error("registry down"),
955
+ ),
956
+ ],
957
+ [
958
+ "the Organization read",
959
+ () =>
960
+ mockOrganizationIdOfWorkspace.mockRejectedValue(new Error("db down")),
961
+ ],
962
+ [
963
+ "the summary read",
964
+ () => mockConnectionSummary.mockRejectedValue(new Error("db down")),
965
+ ],
966
+ ])("a rejecting %s answers 502", async (_label, arrange) => {
967
+ arrange();
968
+ const res = await post();
969
+ expect(res.statusCode).toBe(502);
970
+ expect(res.json()).toEqual({ error: "checkout-unavailable" });
971
+ });
972
+
973
+ it("a body naming a workspace, an Organization or a site is ignored", async () => {
974
+ const res = await post({
975
+ ...BODY,
976
+ workspaceId: "wksp_00000000-0000-7000-8000-00000000dead",
977
+ organizationId: "org_00000000-0000-7000-8000-00000000dead",
978
+ site: "wksp_00000000-0000-7000-8000-00000000dead",
979
+ });
980
+
981
+ expect(res.statusCode).toBe(201);
982
+ expect(mockRecordCheckoutSession.mock.calls[0][0]).toMatchObject({
983
+ workspaceId: WS,
984
+ organizationId: ORG,
985
+ });
986
+ expect(client.checkout.sessions.create.mock.calls[0][0].metadata.site).toBe(
987
+ WS,
988
+ );
989
+ expect(mockOrganizationIdOfWorkspace).toHaveBeenCalledWith(WS);
990
+ });
991
+ });
992
+
993
+ // ── #9126: a resolved spoke with no connection never takes the env path ─────
994
+
995
+ describe("#9126 — a spoke's workspace with no Stripe connection is refused, never the env path", () => {
996
+ const SPOKE = { "x-ailk-spoke-key": "spoke-key-9126" };
997
+ const ENV_SESSION_ID = "cs_test_env9126";
998
+ const LOGGER_KEYS = new Set([
999
+ "level",
1000
+ "time",
1001
+ "pid",
1002
+ "hostname",
1003
+ "reqId",
1004
+ "msg",
1005
+ ]);
1006
+
1007
+ beforeEach(() => {
1008
+ // An env key is set and its Price sells, so the env path would answer
1009
+ // 201: a 404 below is the refusal, not a missing key or Price.
1010
+ process.env.STRIPE_SECRET_KEY =
1011
+ ["sk", "test", ""].join("_") + "Unconnected9126";
1012
+ mockEnvPricesList.mockResolvedValue({
1013
+ data: [
1014
+ {
1015
+ id: "price_Env9126",
1016
+ type: "recurring",
1017
+ product: { id: "prod_Env9126", metadata: {} },
1018
+ },
1019
+ ],
1020
+ });
1021
+ mockEnvSessionsCreate.mockResolvedValue({
1022
+ id: ENV_SESSION_ID,
1023
+ url: `https://checkout.stripe.com/c/pay/${ENV_SESSION_ID}`,
1024
+ });
1025
+ });
1026
+
1027
+ function unconnectedLines(from: number): Array<Record<string, unknown>> {
1028
+ return logged
1029
+ .slice(from)
1030
+ .flatMap((line) => {
1031
+ try {
1032
+ return [JSON.parse(line) as Record<string, unknown>];
1033
+ } catch {
1034
+ return [];
1035
+ }
1036
+ })
1037
+ .filter((entry) => entry.outcome === "unconnected");
1038
+ }
1039
+
1040
+ it.each<[string, () => void]>([
1041
+ [
1042
+ "no Organization row",
1043
+ () => mockOrganizationIdOfWorkspace.mockResolvedValue(null),
1044
+ ],
1045
+ [
1046
+ "an Organization with no connection",
1047
+ () => mockConnectionSummary.mockResolvedValue(null),
1048
+ ],
1049
+ ])(
1050
+ "a spoke's workspace with %s answers the one 404 with no Stripe call",
1051
+ async (_label, arrange) => {
1052
+ arrange();
1053
+ const from = logged.length;
1054
+
1055
+ const res = await post(BODY, SPOKE);
1056
+
1057
+ expect(res.statusCode).toBe(404);
1058
+ expect(res.json()).toEqual({ error: "unknown-product-code" });
1059
+ expect(envStripeConstructor()).not.toHaveBeenCalled();
1060
+ expect(mockEnvPricesList).not.toHaveBeenCalled();
1061
+ expect(mockEnvSessionsCreate).not.toHaveBeenCalled();
1062
+ expect(mockClientForOrganization).not.toHaveBeenCalled();
1063
+ expect(client.prices.list).not.toHaveBeenCalled();
1064
+ expect(mockChargeWriteBudget).not.toHaveBeenCalled();
1065
+ expect(mockRecordCheckoutSession).not.toHaveBeenCalled();
1066
+
1067
+ const lines = unconnectedLines(from);
1068
+ expect(lines).toHaveLength(1);
1069
+ // Everything but the logger's own bindings is what the route chose to log.
1070
+ const fields = Object.fromEntries(
1071
+ Object.entries(lines[0]!).filter(([key]) => !LOGGER_KEYS.has(key)),
1072
+ );
1073
+ expect(fields).toEqual({ outcome: "unconnected", workspaceId: WS });
1074
+ },
1075
+ );
1076
+
1077
+ it("answers before the env key is read: with no STRIPE_SECRET_KEY it is still the 404, never 500", async () => {
1078
+ delete process.env.STRIPE_SECRET_KEY;
1079
+ mockConnectionSummary.mockResolvedValue(null);
1080
+
1081
+ const res = await post(BODY, SPOKE);
1082
+
1083
+ expect(res.statusCode).toBe(404);
1084
+ expect(res.json()).toEqual({ error: "unknown-product-code" });
1085
+ });
1086
+
1087
+ it("a spoke's workspace whose Organization is connected still takes the Offerings path", async () => {
1088
+ const res = await post(BODY, SPOKE);
1089
+
1090
+ expect(res.statusCode).toBe(201);
1091
+ expect(res.json()).toEqual({ sessionId: SESSION_ID, url: SESSION_URL });
1092
+ expect(envStripeConstructor()).not.toHaveBeenCalled();
1093
+ });
1094
+
1095
+ it.each<[string, () => void]>([
1096
+ [
1097
+ "a deployment off the database adapter (not-required)",
1098
+ () =>
1099
+ mockResolvePublicWorkspace.mockResolvedValue({ kind: "not-required" }),
1100
+ ],
1101
+ [
1102
+ "a keyless call on a non-hub whose workspace has no Organization row",
1103
+ () => mockOrganizationIdOfWorkspace.mockResolvedValue(null),
1104
+ ],
1105
+ [
1106
+ "a keyless call on a non-hub whose Organization has no connection",
1107
+ () => mockConnectionSummary.mockResolvedValue(null),
1108
+ ],
1109
+ [
1110
+ "a keyless call a hub refused",
1111
+ () =>
1112
+ mockResolvePublicWorkspace.mockResolvedValue({
1113
+ kind: "unresolved",
1114
+ reason: "spoke-refused",
1115
+ }),
1116
+ ],
1117
+ ])("%s takes the env path, unchanged", async (_label, arrange) => {
1118
+ arrange();
1119
+ const from = logged.length;
1120
+
1121
+ const res = await post();
1122
+
1123
+ expect(res.statusCode).toBe(201);
1124
+ expect(res.json()).toEqual({
1125
+ sessionId: ENV_SESSION_ID,
1126
+ url: `https://checkout.stripe.com/c/pay/${ENV_SESSION_ID}`,
1127
+ });
1128
+ expect(mockEnvSessionsCreate).toHaveBeenCalledTimes(1);
1129
+ expect(mockChargeWriteBudget).not.toHaveBeenCalled();
1130
+ expect(client.prices.list).not.toHaveBeenCalled();
1131
+ expect(unconnectedLines(from)).toHaveLength(0);
1132
+ });
1133
+ });
1134
+
1135
+ // ── AC-5: the bucket, and every failure is 502 (A5, A8, K6) ─────────────────
1136
+
1137
+ describe("AC-5 — the per-request bucket and the failure answers", () => {
1138
+ function charge(key: string, limit: number) {
1139
+ return {
1140
+ scope: "offeringscheckout",
1141
+ charges: [{ key, limit }],
1142
+ windowMs: 60000,
1143
+ now: expect.any(Number),
1144
+ warn: expect.any(Function),
1145
+ };
1146
+ }
1147
+
1148
+ function expectCharged(ip: string) {
1149
+ expect(mockChargeWriteBudget).toHaveBeenCalledWith(charge(`ip,${ip}`, 10));
1150
+ expect(mockChargeWriteBudget).toHaveBeenCalledWith(charge(`ws,${WS}`, 60));
1151
+ }
1152
+
1153
+ function chargedKeys(): string[] {
1154
+ return mockChargeWriteBudget.mock.calls.flatMap(([input]) =>
1155
+ (input as { charges: Array<{ key: string }> }).charges.map((c) => c.key),
1156
+ );
1157
+ }
1158
+
1159
+ it("charges the per-IP and per-workspace buckets once per request, whatever the forwarded address", async () => {
1160
+ await post(BODY, { "x-forwarded-for": "203.0.113.7" });
1161
+ await post(BODY, { "x-forwarded-for": "198.51.100.9" });
1162
+
1163
+ expect(mockChargeWriteBudget).toHaveBeenCalledTimes(4);
1164
+ expectCharged("203.0.113.7");
1165
+ expectCharged("198.51.100.9");
1166
+ expect(chargedKeys()).toEqual([
1167
+ "ip,203.0.113.7",
1168
+ `ws,${WS}`,
1169
+ "ip,198.51.100.9",
1170
+ `ws,${WS}`,
1171
+ ]);
1172
+ });
1173
+
1174
+ it("a request its IP bucket refuses never spends the workspace's bucket", async () => {
1175
+ mockChargeWriteBudget.mockResolvedValueOnce({
1176
+ ok: false,
1177
+ retryAfterSeconds: 5,
1178
+ });
1179
+
1180
+ const res = await post(BODY, { "x-forwarded-for": "203.0.113.7" });
1181
+
1182
+ expect(res.statusCode).toBe(429);
1183
+ expect(chargedKeys()).toEqual(["ip,203.0.113.7"]);
1184
+ });
1185
+
1186
+ it.each<[string, Record<string, unknown>, number]>([
1187
+ [
1188
+ "a malformed body",
1189
+ { productCode: "bad/code", successUrl: "x", cancelUrl: "y" },
1190
+ 400,
1191
+ ],
1192
+ ["an ungrammatical key", { ...BODY, productCode: "Growth_Monthly" }, 404],
1193
+ ])("charges %s before the body is read", async (_label, body, status) => {
1194
+ const res = await post(body, { "x-forwarded-for": "203.0.113.7" });
1195
+ expect(res.statusCode).toBe(status);
1196
+ expect(mockChargeWriteBudget).toHaveBeenCalledTimes(2);
1197
+ expectCharged("203.0.113.7");
1198
+ });
1199
+
1200
+ it("an exhausted bucket answers 429 with Retry-After and no Stripe call", async () => {
1201
+ mockChargeWriteBudget.mockResolvedValue({
1202
+ ok: false,
1203
+ retryAfterSeconds: 7,
1204
+ });
1205
+
1206
+ const res = await post();
1207
+
1208
+ expect(res.statusCode).toBe(429);
1209
+ expect(res.headers["retry-after"]).toBe("7");
1210
+ expect(res.json()).toEqual({ error: "rate_limited", retryAfterSeconds: 7 });
1211
+ expect(client.prices.list).not.toHaveBeenCalled();
1212
+ expect(mockClientForOrganization).not.toHaveBeenCalled();
1213
+ expect(client.checkout.sessions.create).not.toHaveBeenCalled();
1214
+ });
1215
+
1216
+ it("the env path never charges it", async () => {
1217
+ mockConnectionSummary.mockResolvedValue(null);
1218
+ await post();
1219
+ expect(mockChargeWriteBudget).not.toHaveBeenCalled();
1220
+ });
1221
+
1222
+ it.each<[string, () => void]>([
1223
+ [
1224
+ "prices.list rejecting",
1225
+ () => client.prices.list.mockRejectedValue(new Error("unreachable")),
1226
+ ],
1227
+ [
1228
+ "checkout.sessions.create rejecting",
1229
+ () =>
1230
+ client.checkout.sessions.create.mockRejectedValue(
1231
+ new Error("stripe down"),
1232
+ ),
1233
+ ],
1234
+ [
1235
+ "a refused terms box",
1236
+ () =>
1237
+ client.checkout.sessions.create.mockRejectedValue(
1238
+ Object.assign(new Error("You must set a Terms of Service URL"), {
1239
+ type: "StripeInvalidRequestError",
1240
+ param: "consent_collection[terms_of_service]",
1241
+ }),
1242
+ ),
1243
+ ],
1244
+ [
1245
+ "the rows' store rejecting",
1246
+ () => mockReadWorkspaceSelection.mockRejectedValue(new Error("db down")),
1247
+ ],
1248
+ [
1249
+ "an unusable connection",
1250
+ () => mockClientForOrganization.mockResolvedValue({ kind: "unusable" }),
1251
+ ],
1252
+ [
1253
+ "a connection gone since the path decision",
1254
+ () => mockClientForOrganization.mockResolvedValue({ kind: "none" }),
1255
+ ],
1256
+ [
1257
+ "a rejected connection read",
1258
+ () => mockClientForOrganization.mockRejectedValue(new Error("db down")),
1259
+ ],
1260
+ [
1261
+ "rows read for another Organization than the path decision's",
1262
+ () =>
1263
+ mockOrganizationIdOfWorkspace
1264
+ .mockResolvedValueOnce(ORG)
1265
+ .mockResolvedValueOnce("org_00000000-0000-7000-8000-00000000dead"),
1266
+ ],
1267
+ ])("%s answers 502, never 500 or 201", async (_label, arrange) => {
1268
+ arrange();
1269
+
1270
+ const res = await post();
1271
+
1272
+ expect(res.statusCode).toBe(502);
1273
+ expect(res.json()).toEqual({ error: "checkout-unavailable" });
1274
+ expect(mockRecordCheckoutSession).not.toHaveBeenCalled();
1275
+ });
1276
+ });
1277
+
1278
+ // ── AC-6: no key, id or URL in a log line or a refusal body (C5, T6, NFR1) ──
1279
+
1280
+ describe("AC-6 — what the logs and the bodies never carry", () => {
1281
+ it("no log line holds a lookup key, a Price or Product id, a full session id or a URL", () => {
1282
+ expect(logged.length).toBeGreaterThan(0);
1283
+ const all = logged.join("\n");
1284
+ for (const secret of SECRETS) {
1285
+ expect(all).not.toContain(secret);
1286
+ }
1287
+ });
1288
+
1289
+ it("only the two success bodies hold a session id or URL, and no body holds a key or id", () => {
1290
+ expect(bodies.length).toBeGreaterThan(0);
1291
+ for (const { status, body } of bodies) {
1292
+ for (const secret of SECRETS) {
1293
+ if (secret === SESSION_ID && (status === 200 || status === 201))
1294
+ continue;
1295
+ if (secret === SESSION_URL && status === 201) continue;
1296
+ expect(body).not.toContain(secret);
1297
+ }
1298
+ }
1299
+ });
1300
+ });